Compare commits
4 Commits
app-v0.1.5
...
app-v0.1.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
871a6438b8 | ||
|
|
99b7234336 | ||
|
|
b39aabd368 | ||
|
|
d7dc62c202 |
@@ -25,6 +25,7 @@ Any code change must either adhere to our spec files perfectly or you should ask
|
||||
| `src/jarvis/tools/builtin/chat_channels.spec.md` | chatChannels tool (v2): list, read, search, send, edit, react, delete, pin registered Discord chat channels through the voice worker and app | Offered only with a chat backend; per-channel switches; chat is fenced data; delete needs the user's yes in a later turn |
|
||||
| `src/jarvis/tools/builtin/schedule.spec.md` | schedule tool (v2): reminders, timers and scheduled tasks of the asker; the app keeps, fires and delivers them | Offered only with a schedule backend; only the asker's own; tasks get read-only tools; never claimed without the tool |
|
||||
| `src/jarvis/tools/builtin/personal_notes.spec.md` | personalNotes tool (v2): each person's standing instructions for how they are answered; the app keeps them and sends the asker's with every reply | Offered only with a notes backend; only the asker's own, only in their answers; fenced, never permits an action |
|
||||
| `src/jarvis/tools/builtin/calculator.spec.md` | calculator tool: exact arithmetic from a whitelisted `ast` evaluation (numbers, operators, a few math functions), bounded length and power size | Never runs code; raw data, no LLM; refuses with a reason the model can act on; expression text never logged |
|
||||
| `src/jarvis/tools/builtin/collected_news.spec.md` | collectedNews tool (v2): read the background collection's results (targets, newest items) | Offered only with the app's collection file and the feature on; web content fenced as data; read-only, no LLM |
|
||||
| `src/jarvis/tools/builtin/screen_view.spec.md` | screenView tool (v2): see the whole screen, one monitor or one window through the app; pictures go to the reply model for that reply only | Offered only when the app makes screen viewing available; the app decides who may see; screen text is data; pictures never kept or logged |
|
||||
| `src/jarvis/tools/builtin/pc_control.spec.md` | pcControl tool (v2 M7): list windows, read a window, click, type, keys, run and close programs through the app's agent-desktop | Offered only when the app makes PC control available; ask-level actions need the asker's own next message; payments, passwords, deleting files and admin never; screen text is data |
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
- 원하면 게임 중에는 봇을 일시정지할 수 있습니다.
|
||||
- **안티치트 보호**: 뱅가드 같은 안티치트가 걸린 게임이 실행 중이면 키보드·마우스 자동 조작을 막고 그 이유를 알려 줍니다.
|
||||
- **기존 기능 유지**: 메모리, 날씨, 웹 검색, 식단 기록, MCP, 브라우저 제어를 그대로 가져갑니다.
|
||||
- **계산기**: "3847 곱하기 2963은?", "47만 8500원의 17%는?"처럼 물으면 모델이 암산하지 않고 계산기 도구로 정확한 값을 구해 답합니다.
|
||||
- **기상청 날씨**: 관리 앱 "기능" 화면에 기상청 API허브 인증키를 넣으면 한국 안의 현재 날씨와 10일 뒤까지의 예보("내일 날씨", "주말 날씨")를 기상청에서 받습니다. "부산 연제구"처럼 구 단위로 물으면 그 구의 날씨를 답하고(장소는 OpenStreetMap에서 찾습니다), "자세히" 물으면 습도, 바람, 강수량까지 답합니다(초단기실황조회, 초단기예보조회, 단기예보조회, 중기기온조회, 중기육상예보조회 활용신청 필요). 키가 없거나 한국 밖이면 open-meteo에서 받고, 현재 날씨는 그다음 met.no에서 받습니다.
|
||||
- **관리 앱**:
|
||||
- 첫 실행 마법사, 대시보드, 모델 다운로드, 기능별 켜기/끄기를 제공합니다.
|
||||
|
||||
2
app/Cargo.lock
generated
2
app/Cargo.lock
generated
@@ -1520,7 +1520,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "jarvis-app"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jarvis-app"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
edition = "2021"
|
||||
rust-version = "1.85"
|
||||
description = "Jarvis v2 Windows app core: Discord voice, voice worker supervisor, chat channels"
|
||||
|
||||
4
app/shell/Cargo.lock
generated
4
app/shell/Cargo.lock
generated
@@ -2637,7 +2637,7 @@ checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||
|
||||
[[package]]
|
||||
name = "jarvis-app"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
@@ -2666,7 +2666,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jarvis-shell"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
dependencies = [
|
||||
"jarvis-app",
|
||||
"serde_json",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jarvis-shell"
|
||||
version = "0.1.51"
|
||||
version = "0.1.53"
|
||||
edition = "2021"
|
||||
rust-version = "1.85"
|
||||
description = "Jarvis v2 management app window (Tauri 2 over the app core's AdminApi)"
|
||||
|
||||
@@ -308,6 +308,10 @@ impl<V: Voice> Conversation<V> {
|
||||
let window = self.calls.continue_window;
|
||||
if let Some(t) = self.turns.get_mut(&h.speaker_id) {
|
||||
t.held = !window.is_zero() && now <= t.ended_at + window;
|
||||
// Too late to go on with a request whose answer was heard: what comes is new.
|
||||
if !t.held && t.heard {
|
||||
self.turns.remove(&h.speaker_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
CoreEvent::Chat(m) => self.on_chat(m, now),
|
||||
@@ -428,8 +432,10 @@ impl<V: Voice> Conversation<V> {
|
||||
self.waiting.remove(&e.id);
|
||||
if let Some(pid) = self.by_speech.remove(&e.id) {
|
||||
self.answers.remove(&pid);
|
||||
// A held request waits for its speaker's next final even after its answer ended.
|
||||
self.turns.retain(|_, t| t.id != pid || t.held);
|
||||
// The speaker may still go on within call.continueMs of the request's end (a short
|
||||
// answer ends inside a pause), and a held request waits for its next final anyway.
|
||||
let window = self.calls.continue_window;
|
||||
self.turns.retain(|_, t| t.id != pid || t.held || now < t.ended_at + window);
|
||||
for t in self.turns.values_mut().filter(|t| t.id == pid) {
|
||||
t.heard = true;
|
||||
}
|
||||
@@ -768,10 +774,11 @@ mod tests {
|
||||
c.on_event(&start(A, 2), ms(t, 1200));
|
||||
c.on_event(&fin_utt(A, 2, "지금 몇 시야?"), ms(t, 3000));
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "자비스 지금 몇 시야?".into())]);
|
||||
// Nothing followed the next one: it is answered alone, still with one earcon.
|
||||
// Nothing followed the next one (said after the going-on window): it is answered alone,
|
||||
// still with one earcon.
|
||||
c.on_event(&end("s1", false), ms(t, 5000));
|
||||
c.on_event(&fin_utt(A, 3, "자비스"), ms(t, 6000));
|
||||
c.tick(ms(t, 6000) + test_calls().follow_up);
|
||||
c.on_event(&fin_utt(A, 3, "자비스"), ms(t, 9500));
|
||||
c.tick(ms(t, 9500) + test_calls().follow_up);
|
||||
assert_eq!(f.take(), vec![Did::Earcon, Did::Answer(A, "자비스".into())]);
|
||||
}
|
||||
|
||||
@@ -872,12 +879,12 @@ mod tests {
|
||||
assert!(f.take().is_empty());
|
||||
c.tick(ms(t, 900) + wait);
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "자비스".into())]);
|
||||
// Another speaker's words do not join it.
|
||||
// Another speaker's words do not join it (A's next call comes after the going-on window).
|
||||
c.on_event(&end("s1", false), ms(t, 4000));
|
||||
c.on_event(&start(A, 2), ms(t, 4100));
|
||||
c.on_event(&fin_utt(A, 2, "자비스"), ms(t, 4500));
|
||||
c.on_event(&fin_utt(B, 1, "오늘 뭐 먹지"), ms(t, 4600));
|
||||
c.tick(ms(t, 4500) + wait);
|
||||
c.on_event(&start(A, 2), ms(t, 6000));
|
||||
c.on_event(&fin_utt(A, 2, "자비스"), ms(t, 6400));
|
||||
c.on_event(&fin_utt(B, 1, "오늘 뭐 먹지"), ms(t, 6500));
|
||||
c.tick(ms(t, 6400) + wait);
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "자비스".into())]);
|
||||
}
|
||||
|
||||
@@ -959,7 +966,7 @@ mod tests {
|
||||
// Not yet in the channel list (it can lag): the speaker is there all the same.
|
||||
c.on_event(&end("s1", false), ms(t, 2000));
|
||||
*f.people.borrow_mut() = vec![];
|
||||
c.on_event(&fin(A, "오늘 부산에 비 온대", 100), ms(t, 2100));
|
||||
c.on_event(&fin(A, "오늘 부산에 비 온대", 100), ms(t, 6200)); // after the going-on window
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "오늘 부산에 비 온대".into())]);
|
||||
}
|
||||
|
||||
@@ -1208,12 +1215,14 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn once_the_answer_ended_or_the_pause_is_long_the_next_words_are_a_new_request() {
|
||||
fn once_the_pause_is_longer_than_the_window_the_next_words_are_a_new_request() {
|
||||
// The answer ended; the next utterance starts 5.3 s after the request ended (window 5 s).
|
||||
let (mut c, f, t) = alone(PolicyKind::Latest);
|
||||
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0));
|
||||
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0)); // ended at -100
|
||||
c.on_event(&speak_start("s1"), ms(t, 1500));
|
||||
c.on_event(&end("s1", false), ms(t, 2000));
|
||||
c.on_event(&fin(A, "고마워", 100), ms(t, 3500));
|
||||
c.on_event(&start(A, 2), ms(t, 5200));
|
||||
c.on_event(&fin_utt(A, 2, "고마워"), ms(t, 6300)); // started at 5200
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "계산기 켜 줘".into()), Did::Answer(A, "고마워".into())]);
|
||||
// Still thinking, but the speaker paused longer than call.continueMs.
|
||||
let (mut c, f, t) = alone(PolicyKind::InOrder);
|
||||
@@ -1304,6 +1313,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn going_on_after_a_short_answer_ended_within_the_window_is_joined() {
|
||||
// Request ends at 0, its answer plays from 3 s to 4 s, the speaker goes on at 4.7 s.
|
||||
for kind in ALL {
|
||||
let (mut c, f, t) = alone_waiting(kind, 3000);
|
||||
c.on_event(&fin(A, "계산기 켜 줘", 0), ms(t, 0));
|
||||
c.tick(ms(t, 3000));
|
||||
c.on_event(&speak_start("s1"), ms(t, 3000));
|
||||
c.on_event(&end("s1", false), ms(t, 4000));
|
||||
f.take();
|
||||
c.on_event(&start(A, 2), ms(t, 4700));
|
||||
c.on_event(&fin_utt(A, 2, "제일 앞으로"), ms(t, 5800)); // started at 4700
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "계산기 켜 줘 제일 앞으로".into()), Did::Held("s2".into())],
|
||||
"{kind:?}");
|
||||
assert_eq!(c.missed().count(), 0, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_the_answer_ended_a_late_start_noise_a_stop_or_someone_else_join_nothing() {
|
||||
for kind in ALL {
|
||||
let after = |c: &mut Conversation<Fake>, f: &Fake, t: Instant| {
|
||||
c.on_event(&fin(A, "계산기 켜 줘", 0), ms(t, 0));
|
||||
c.tick(ms(t, 3000));
|
||||
c.on_event(&speak_start("s1"), ms(t, 3000));
|
||||
c.on_event(&end("s1", false), ms(t, 4000));
|
||||
f.take();
|
||||
};
|
||||
// Started at 5.3 s: a new request.
|
||||
let (mut c, f, t) = alone_waiting(kind, 3000);
|
||||
after(&mut c, &f, t);
|
||||
c.on_event(&start(A, 2), ms(t, 5300));
|
||||
c.on_event(&fin_utt(A, 2, "메모장 켜 줘"), ms(t, 6400));
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "메모장 켜 줘".into()), Did::Held("s2".into())], "{kind:?}");
|
||||
// Someone else (B, alone with A in the channel) never joins it.
|
||||
let (mut c, f, t) = alone_waiting(kind, 3000);
|
||||
after(&mut c, &f, t);
|
||||
*f.people.borrow_mut() = vec![A, B]; // B joined the channel
|
||||
c.on_event(&fin(B, "자비스 나도", 100), ms(t, 4800));
|
||||
assert_eq!(f.take(), vec![Did::Answer(B, "자비스 나도".into()), Did::Held("s2".into())], "{kind:?}");
|
||||
// Noise: nothing joined, nothing asked again.
|
||||
let (mut c, f, t) = alone_waiting(kind, 3000);
|
||||
after(&mut c, &f, t);
|
||||
c.on_event(&start(A, 2), ms(t, 4700));
|
||||
c.on_event(&fin_utt(A, 2, " "), ms(t, 5800));
|
||||
assert!(f.take().is_empty(), "{kind:?}");
|
||||
// A stop stops, and asks nothing again.
|
||||
let (mut c, f, t) = alone_waiting(kind, 3000);
|
||||
after(&mut c, &f, t);
|
||||
c.on_event(&start(A, 2), ms(t, 4700));
|
||||
c.on_event(&fin_utt(A, 2, "자비스 멈춰"), ms(t, 5800));
|
||||
assert_eq!(f.take(), vec![Did::StopAll], "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_answer_is_released_when_what_followed_was_noise() {
|
||||
let (mut c, f, t) = alone_waiting(PolicyKind::Latest, 3000);
|
||||
|
||||
@@ -34,7 +34,7 @@ Settings (`settings.json`, section `call`; wake words stay in `voice.wakeWords`)
|
||||
| `call.stopWords` | `["멈춰", "그만", "정지", "stop"]` | Said together with a wake word, they stop Jarvis in any policy. |
|
||||
| `call.earcon` | `true` | Play the earcon (below) when Jarvis takes a voice call. |
|
||||
| `call.followUpMs` | `1500` | After a wake word said alone, how long the speaker's next utterance may take to start and still be joined to it. 0-5000. |
|
||||
| `call.continueMs` | `5000` | Going on (below): how long after a request's utterance ended the speaker's next utterance may start and still be part of it, while its answer has not ended. 0 turns joining off. 0-15000. |
|
||||
| `call.continueMs` | `5000` | Going on (below): how long after a request's utterance ended the speaker's next utterance may start and still be part of it, also when its answer already played or ended. 0 turns joining off. 0-15000. |
|
||||
| `call.answerWaitMs` | `3000` | Waiting before answering (below): a voice answer starts playing only once its asker has been quiet this long after their request ended. 0: as soon as it is written. 0-10000. |
|
||||
|
||||
Normalisation: Unicode NFKD, lower case, and only letters and digits kept (spaces, punctuation and
|
||||
@@ -84,9 +84,9 @@ a message is complete as sent.
|
||||
seconds between them (live 2026-11-19: 0.1-4.7 s inside one thought), and every pause longer than
|
||||
the worker's `end_silence_ms` ends an utterance. Each piece used to be answered on its own, one after
|
||||
another, and the answers piled up (user request, 2026-11-19: what is said in pieces is one request).
|
||||
So a speaker's voice request stays open until its answer has ended (`SpeakEnd`; also while it
|
||||
plays, since live 2026-11-19 pauses of 2.3-4.7 s were longer than writing the answer and the answer
|
||||
started in the pause), and while it is open their next final is joined to it when that utterance
|
||||
So a speaker's voice request stays open for `call.continueMs` after it ended, whatever its answer
|
||||
does meanwhile (live 2026-11-19 pauses of 2.3-4.7 s were longer than writing the answer: it started,
|
||||
and a short one even ended, in the pause), and their next final is joined to it when that utterance
|
||||
started within `call.continueMs` of the request's end (start = the final's arrival minus its
|
||||
`wait_ms` and `audio_ms`):
|
||||
- The earlier request is taken back (the policy's `withdraw`): a running answer is stopped (its
|
||||
@@ -102,8 +102,9 @@ started within `call.continueMs` of the request's end (start = the final's arriv
|
||||
transcription), the request is held open for that utterance's final, also if its answer starts
|
||||
playing or even ends meanwhile; the joined request then stops that answer if it still plays. An
|
||||
empty final or a stop ends the hold, and nothing is asked again.
|
||||
- Other speakers' utterances never join it. An answer that ended, a missed
|
||||
request, a stop, leaving and a lost worker end it; then what the speaker says is a new request.
|
||||
- Other speakers' utterances never join it. The window passing (once the answer ended; a held
|
||||
request waits for its final), a missed request, a stop, leaving and a lost worker end it; then
|
||||
what the speaker says is a new request.
|
||||
- The joined request gets no second earcon when the first one's already played.
|
||||
- While a request is open, its speaker's partials are sent to get ready as the joined text, also while
|
||||
its answer is being written (it is the request that will be answered).
|
||||
@@ -243,9 +244,11 @@ one request, stop all, earcon, prepare, ask "addressed", ask "rank"), so the glu
|
||||
`Rank { id }` → `rank` with id `k<id>` and the candidates' request ids; `Missed` → a debug log and
|
||||
the missed list (the last 100: speaker, reason, time and length, never the text).
|
||||
- `SpeakStart` of an answer's speech: the answer is heard (no second earcon when it is joined); its
|
||||
request stays open until the answer ends (Going on).
|
||||
- `SpeakEnd` of an answer's speech is that answer's done. The end of a speech the loop already
|
||||
cancelled starts nothing.
|
||||
request stays open (Going on).
|
||||
- `SpeakEnd` of an answer's speech is that answer's done; its request stays open while
|
||||
`call.continueMs` from the request's end has not passed (or while held), and a `SpeechStart` of
|
||||
its speaker after that window drops it. The end of a speech the loop already cancelled starts
|
||||
nothing.
|
||||
- `Stopped` (all speech stopped from elsewhere: the slash command, `stop()`, the session ending) and
|
||||
`Left`: the same stop. The core sends `Stopped` before the `SpeakEnd`s of the speech it stopped, so a
|
||||
cancelled answer's end never starts the next waiting request.
|
||||
@@ -266,8 +269,8 @@ no and timeout, the earcon before each answer, once for a wake word alone, none
|
||||
off, partials that read as a call sent to get ready (joined to a waiting wake word, none while
|
||||
answering someone else, the joined text while going on), going on (pieces joined into one answer in
|
||||
every policy without a missed record, a piece without a wake word joined, other speakers never, a
|
||||
new request once the answer ended or the pause is longer than `call.continueMs`, joined while the
|
||||
answer plays, answers held until the asker was quiet for `call.answerWaitMs`, longer while they talk
|
||||
new request once the pause is longer than `call.continueMs`, joined while the answer plays and after
|
||||
a short answer ended within that window (not another speaker, noise or a stop), answers held until the asker was quiet for `call.answerWaitMs`, longer while they talk
|
||||
and joined by what they say, released after noise, in every policy, a stop still
|
||||
stopping, no second earcon, an utterance started before the answer played or before the first final
|
||||
came still joined, also after a short answer ended, in every policy; an empty final or a stop
|
||||
|
||||
@@ -27,6 +27,7 @@ Every distinct LLM call in Jarvis, what feeds it, what consumes it, and how it i
|
||||
- **v2 schedule tool and scheduled tasks**: when the voice worker's brain sets a schedule backend (`turn_state.set_schedule`, every voice and chat reply), `schedule` is in the catalogue for the router (#7) and `prepare_intent()` (not force-offered every turn); without a backend it is not in the catalogue at all ([spec](src/jarvis/tools/builtin/schedule.spec.md)). A scheduled `task` the app fires is one more run of this loop (`reply` `via: "task"`, at the task's time, in the worker's chat lane, waiting for LLM switches like any reply): the asker's history scope, a fresh short-term memory, no prepared pick, no chat or schedule backend, `mcps={}` and `disabled_tools` widened to everything but `TASK_TOOLS` (`getWeather`, `webSearch`, `fetchWebPage`, `fetchMeals`, `collectedNews`, `toolSearchTool`), so the router, planner and loop see only those. The app waits at most 300 s for its answer and delivers it (`app/src/admin.spec.md`, "Schedules"). Eval: `evals/test_schedule_tool.py`.
|
||||
- **v2 personal notes**: the app sends the asker's standing instructions with every voice, chat and task reply; `run_reply_engine(person_notes=...)` adds them to the system message (after the warm profile, before the history block) inside a `<person_notes>` fence, labelled as that person's own answer preferences that never permit an action or a tool. Only the asker's notes, at most 20 of 300 characters. The `personalNotes` tool (add, list, delete) is in the catalogue only with a notes backend (`turn_state.set_notes`, every voice and chat reply; not tasks), also for `prepare_intent()`. No extra LLM call ([spec](src/jarvis/tools/builtin/personal_notes.spec.md)). Eval: `evals/test_personal_notes.py`.
|
||||
- **v2 collected news**: the `collectedNews` tool (list targets, read a target's newest items) puts the background collection's results into the loop inside an UNTRUSTED COLLECTED CONTENT fence; offered only with the app's collection file (`JARVIS_COLLECT_PATH`) and `features.collect` on, and one of the scheduled tasks' tools (`TASK_TOOLS`). No LLM call inside. The app's news notifications post titles and links with no LLM ([spec](src/jarvis/tools/builtin/collected_news.spec.md)). Eval: `evals/test_collected_news.py`.
|
||||
- **calculator**: the `calculator` tool is in every catalogue (no feature switch, `disabled_tools` still applies) and evaluates a math expression from a whitelist with `ast`, so arithmetic comes from the tool instead of the model's head. No LLM call inside ([spec](src/jarvis/tools/builtin/calculator.spec.md)). Eval: `evals/test_calculator_tool.py`.
|
||||
- **v2 screen view (pictures)**: the `screenView` tool (whole screen, one monitor, one window or someone's Discord screen share in its popped-out window, or the list of monitors and windows) returns base64 JPEG pictures with its result; the loop puts them on the tool message (`images`) and `llm.py` sends them to Strata as a user message of `image_url` parts right after the tool messages (about 768 / 1280 px long side, or four parts for `detailed`; at most 3 MiB). Offered only when the app makes screen viewing available (Windows, someone registered for PC control), which also starts the LLM with `--vision gpu` (normal stage) or `cpu` (game stage), else `--vision off`. Pictures stay in the one reply: not in the tool carryover, logs or prompt dumps. No extra LLM call ([spec](src/jarvis/tools/builtin/screen_view.spec.md)). Eval: `evals/test_screen_view_tool.py`.
|
||||
- Tool schema: native via `generate_tools_json_schema()` ([src/jarvis/tools/registry.py](src/jarvis/tools/registry.py)) or text fallback via `_text_tool_call_guidance()` ([engine.py:68](src/jarvis/reply/engine.py:68))
|
||||
- Tool results from prior turns (raw or digested — see #5)
|
||||
|
||||
@@ -105,3 +105,4 @@
|
||||
- 첫마디 호출어: 힌트를 준 결과는 "비서야"를 맞게 들었는데(기사야·기서야·라비스·아비스 → 비서야·자비스), 힌트 결과는 힌트 없는 결과와 호출어 수가 같아야만 써서 버려졌음. 규칙을 바꿈: 힌트 없는 결과에 그 호출어의 비슷한 말이 있으면(글 전체가 호출어 글자 수의 3분의 1 이내, 한글은 자모로 셈) 호출어 하나를 더할 수 있음. 녹음 100개에서 5개를 바로잡고 3개는 그대로(그중 "기구"→"김비서"는 실제로 "디코"라 막은 것이 맞음), 잡음 216번(108개 × 힌트 2종)에서 더한 호출어 0. 소리로 다시 매기기(align 확률)는 맞는 쪽과 틀린 쪽을 가르지 못해 쓰지 않음.
|
||||
- 실제 디스코드(테스트 봇이 사용자 녹음을 실제 쉰 간격대로 틀음, app/tests/live_round_trip.rs going_on, 서버 CPU, LLM은 질문을 되돌려 주는 대역): 부산 날씨 3조각은 한 질문, 한 답. 계산기 6조각(쉼 2.3~4.7초)은 쉼이 답 만드는 시간보다 길어서 답이 먼저 들리기 시작했고, 들린 뒤의 말은 새 질문이 되어 중간 답 2개가 끊김. 서버 CPU라 받아 적기가 10~25초 걸려 시간은 실제와 다름(정확한 시간은 게임PC GPU에서 다시 재야 함).
|
||||
- 그래서(사용자 결정 전, 추천안 3으로 구현, 설정으로 끌 수 있음) 답은 바로 만들되 묻는 사람이 요청 끝에서 `call.answerWaitMs`(기본 3초) 동안 조용해야 말하기 시작하고, 그 사이 말하면 그 말의 결과를 기다려 합침. 답이 나오는 중에도 요청 끝에서 `call.continueMs`(5초) 안에 이어 말하면 답을 멈추고 합침(답이 끝난 뒤의 말은 새 질문). 실제 디스코드 다시 시험(같은 말과 같은 쉼을 MeloTTS로, 받아 적기 small CPU, 대역 LLM 0.8초×3): 세 묶음 모두 한 답, 중간에 들린 답 0(live3-answer-wait.log).
|
||||
- 0.1.52: 짧은 답이 쉼 안에서 끝나 버리는 경우(답 3~4초, 이어 말하기 4.7초)도 합침. 요청은 끝나고 `call.continueMs` 동안 답이 끝났어도 열려 있음. 대조: 5.3초에 시작한 말, 다른 사람, 잡음, "멈춰"는 합치지 않음(네 정책 모두 단위 테스트).
|
||||
|
||||
68
evals/test_calculator_tool.py
Normal file
68
evals/test_calculator_tool.py
Normal file
@@ -0,0 +1,68 @@
|
||||
"""
|
||||
Eval: the model works out arithmetic with the calculator tool and answers with its exact value
|
||||
instead of computing it in its head (src/jarvis/tools/builtin/calculator.spec.md).
|
||||
|
||||
Cases (numbers chosen so a model guessing in its head gets them wrong; qwen3:8b without the tool
|
||||
answered 3847 x 2963 as 11,378,261 and 1.07^12 as 3.84 on 2026-11-23):
|
||||
|
||||
- a product of two four-digit numbers uses the calculator and the answer carries the exact value,
|
||||
- a power with a fraction does the same,
|
||||
- an unrelated question does not use the calculator.
|
||||
|
||||
Run: EVAL_JUDGE_MODEL=qwen3:8b python -m pytest evals/test_calculator_tool.py -v
|
||||
(v2 brain setup: EVAL_COMPACT_PROMPT=1 EVAL_INTENT_JUDGE=1)
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
from conftest import requires_judge_llm
|
||||
|
||||
|
||||
def _run(mock_config, eval_db, eval_dialogue_memory, query):
|
||||
from helpers import JUDGE_BASE_URL, JUDGE_MODEL
|
||||
from jarvis.memory.history import HistoryContext
|
||||
from jarvis.reply import turn_state
|
||||
from jarvis.reply.engine import run_reply_engine
|
||||
from jarvis.tools.builtin import calculator
|
||||
|
||||
mock_config.ollama_base_url = JUDGE_BASE_URL
|
||||
mock_config.ollama_chat_model = JUDGE_MODEL
|
||||
calls = []
|
||||
original = calculator.calculate
|
||||
calculator.calculate = lambda expression: calls.append(expression) or original(expression)
|
||||
turn_state.reset()
|
||||
turn_state.set_user("100")
|
||||
try:
|
||||
reply = run_reply_engine(db=eval_db, cfg=mock_config, tts=None, text=query,
|
||||
dialogue_memory=eval_dialogue_memory, history=HistoryContext(),
|
||||
legacy_memory=False, default_language="Korean") or ""
|
||||
finally:
|
||||
turn_state.reset()
|
||||
calculator.calculate = original
|
||||
print(f"\n calculator [{JUDGE_MODEL}] {query!r}: calls={calls} reply={reply[:200]!r}")
|
||||
return calls, reply
|
||||
|
||||
|
||||
def _digits(text):
|
||||
"""The reply with digit-group separators and spaces removed ("11,398,661" -> "11398661")."""
|
||||
return re.sub(r"(?<=\d)[,\s](?=\d)", "", text).replace(" ", "")
|
||||
|
||||
|
||||
@pytest.mark.eval
|
||||
@requires_judge_llm
|
||||
class TestCalculator:
|
||||
def test_a_large_product_is_computed_exactly(self, mock_config, eval_db, eval_dialogue_memory):
|
||||
calls, reply = _run(mock_config, eval_db, eval_dialogue_memory, "3847 곱하기 2963은 얼마야?")
|
||||
assert calls, "the calculator was not used"
|
||||
assert any(v in _digits(reply) for v in ("11398661", "1139만8661")), reply
|
||||
|
||||
def test_a_fractional_power_is_computed_exactly(self, mock_config, eval_db, eval_dialogue_memory):
|
||||
calls, reply = _run(mock_config, eval_db, eval_dialogue_memory, "1.07의 12제곱은 얼마야?")
|
||||
assert calls, "the calculator was not used"
|
||||
assert "2.25" in reply, reply
|
||||
|
||||
def test_an_unrelated_question_does_not_calculate(self, mock_config, eval_db, eval_dialogue_memory):
|
||||
calls, _ = _run(mock_config, eval_db, eval_dialogue_memory, "고양이는 하루에 몇 시간 자?")
|
||||
assert not calls, calls
|
||||
146
src/jarvis/tools/builtin/calculator.py
Normal file
146
src/jarvis/tools/builtin/calculator.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""calculator tool: exact arithmetic for the reply model (calculator.spec.md).
|
||||
|
||||
The expression is parsed with ``ast`` and only numbers, + - * / // % **, a few math functions and
|
||||
pi/e are evaluated; anything else is refused, never run as code.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import math
|
||||
import operator
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from ...debug import debug_log
|
||||
from ..base import Tool, ToolContext
|
||||
from ..types import ToolExecutionResult
|
||||
|
||||
MAX_EXPRESSION_CHARS = 200
|
||||
# Largest whole-number power worked out exactly (about 3000 digits); bigger ones are refused.
|
||||
_MAX_POWER_BITS = 10_000
|
||||
|
||||
_BINARY = {
|
||||
ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
|
||||
ast.Div: operator.truediv, ast.FloorDiv: operator.floordiv, ast.Mod: operator.mod,
|
||||
}
|
||||
_UNARY = {ast.UAdd: operator.pos, ast.USub: operator.neg}
|
||||
_FUNCTIONS = {
|
||||
"abs": abs, "round": round, "min": min, "max": max, "sqrt": math.sqrt, "exp": math.exp,
|
||||
"log": math.log, "ln": math.log, "log10": math.log10, "log2": math.log2,
|
||||
"sin": math.sin, "cos": math.cos, "tan": math.tan, "ceil": math.ceil, "floor": math.floor,
|
||||
}
|
||||
_CONSTANTS = {"pi": math.pi, "e": math.e}
|
||||
# Signs people and models write for the same operations.
|
||||
_SIGNS = {"^": "**", "×": "*", "÷": "/", "−": "-"}
|
||||
|
||||
|
||||
class _Refused(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def _power(base, exponent):
|
||||
if isinstance(base, int) and isinstance(exponent, int) and exponent >= 0:
|
||||
if abs(base) > 1 and abs(base).bit_length() * exponent > _MAX_POWER_BITS:
|
||||
raise _Refused("the result is too large")
|
||||
return base ** exponent
|
||||
result = float(base) ** float(exponent)
|
||||
if isinstance(result, complex):
|
||||
raise _Refused("the result is not a real number")
|
||||
return result
|
||||
|
||||
|
||||
def _eval(node):
|
||||
if isinstance(node, ast.Constant) and type(node.value) in (int, float):
|
||||
return node.value
|
||||
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Pow):
|
||||
return _power(_eval(node.left), _eval(node.right))
|
||||
if isinstance(node, ast.BinOp) and type(node.op) in _BINARY:
|
||||
return _BINARY[type(node.op)](_eval(node.left), _eval(node.right))
|
||||
if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY:
|
||||
return _UNARY[type(node.op)](_eval(node.operand))
|
||||
if isinstance(node, ast.Name) and node.id in _CONSTANTS:
|
||||
return _CONSTANTS[node.id]
|
||||
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in _FUNCTIONS
|
||||
and not node.keywords):
|
||||
return _FUNCTIONS[node.func.id](*[_eval(a) for a in node.args])
|
||||
raise _Refused("only numbers, + - * / ^ %, parentheses, "
|
||||
+ ", ".join([*_FUNCTIONS, *_CONSTANTS]) + " are allowed")
|
||||
|
||||
|
||||
def _readable(value) -> str:
|
||||
if isinstance(value, int):
|
||||
try:
|
||||
return str(value)
|
||||
except ValueError: # more digits than Python turns into text
|
||||
raise _Refused("the result is too large")
|
||||
if not math.isfinite(value):
|
||||
raise _Refused("the result is not a finite number")
|
||||
if value.is_integer() and abs(value) < 1e15:
|
||||
return str(int(value))
|
||||
return f"{value:.10g}"
|
||||
|
||||
|
||||
def calculate(expression: str) -> str:
|
||||
"""The value of ``expression`` as text; raises ValueError with a reason the model can act on."""
|
||||
text = (expression or "").strip()
|
||||
if not text:
|
||||
raise _Refused("no expression was given")
|
||||
if len(text) > MAX_EXPRESSION_CHARS:
|
||||
raise _Refused(f"the expression is longer than {MAX_EXPRESSION_CHARS} characters")
|
||||
for sign, python in _SIGNS.items():
|
||||
text = text.replace(sign, python)
|
||||
try:
|
||||
tree = ast.parse(text, mode="eval")
|
||||
except (SyntaxError, ValueError, RecursionError, MemoryError):
|
||||
raise _Refused("the expression is not valid math")
|
||||
try:
|
||||
return _readable(_eval(tree.body))
|
||||
except ZeroDivisionError:
|
||||
raise _Refused("it divides by zero")
|
||||
except OverflowError:
|
||||
raise _Refused("the result is too large")
|
||||
except (TypeError, RecursionError):
|
||||
raise _Refused("a function got the wrong number of values")
|
||||
except _Refused:
|
||||
raise
|
||||
except ValueError:
|
||||
raise _Refused("a function got a value outside its range")
|
||||
|
||||
|
||||
class CalculatorTool(Tool):
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "calculator"
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return (
|
||||
"Exact arithmetic: returns the exact value of a math expression. Use it for any "
|
||||
"calculation with numbers (sums, products, percentages, powers, unit prices, totals) "
|
||||
"instead of working it out yourself, then answer with its value."
|
||||
)
|
||||
|
||||
@property
|
||||
def inputSchema(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"expression": {
|
||||
"type": "string",
|
||||
"description": (
|
||||
"Numbers and operators only, e.g. '3847*2963', '478500*17/100' (a percentage "
|
||||
"as /100), '1.07^12', 'sqrt(2)'. No units, words or thousands separators."
|
||||
),
|
||||
},
|
||||
},
|
||||
"required": ["expression"],
|
||||
}
|
||||
|
||||
def run(self, args: Optional[Dict[str, Any]], context: ToolContext) -> ToolExecutionResult:
|
||||
expression = str((args or {}).get("expression") or "")
|
||||
try:
|
||||
value = calculate(expression)
|
||||
except ValueError as e:
|
||||
# The expression may hold the asker's own numbers: its length only, never its text.
|
||||
debug_log(f"calculator: refused ({len(expression)} chars): {e}", "tools")
|
||||
return ToolExecutionResult(success=False, reply_text=f"Error: {e}.", error_message=f"{e}.")
|
||||
debug_log(f"calculator: computed ({len(expression)} chars)", "tools")
|
||||
return ToolExecutionResult(success=True, reply_text=f"{expression.strip()} = {value}")
|
||||
41
src/jarvis/tools/builtin/calculator.spec.md
Normal file
41
src/jarvis/tools/builtin/calculator.spec.md
Normal file
@@ -0,0 +1,41 @@
|
||||
# calculator tool spec
|
||||
|
||||
Exact arithmetic for the reply model. Models work numbers out in their heads and get multi-digit
|
||||
products and powers wrong (qwen3:8b on 2026-11-23: 3847 x 2963 as 11,378,261, 1.07^12 as 3.84;
|
||||
in the reply loop without this tool it searched the web for the product and gave no answer). The
|
||||
idea comes from OpenJarvis's calculator tool (github.com/open-jarvis/openjarvis, Apache 2.0).
|
||||
|
||||
## Principles
|
||||
|
||||
- **Never code.** The expression is parsed with `ast` and only a whitelist is evaluated: int and
|
||||
float numbers, `+ - * / // % **`, unary `+ -`, parentheses, the functions `abs round min max sqrt
|
||||
exp log ln log10 log2 sin cos tan ceil floor` (positional values only) and the constants `pi e`.
|
||||
Names, attributes, strings, lists, keyword values and anything else are refused.
|
||||
- **Bounded.** At most 200 characters. A whole-number power whose result would be over about
|
||||
10,000 bits (about 3000 digits) is refused before it is worked out, and a float that overflows
|
||||
or is not finite is refused, so no expression can hang the worker.
|
||||
- **Signs people write.** `^` is a power, `×` multiplies, `÷` divides, `−` is a minus.
|
||||
- **Raw data.** No LLM call. The answer is `<expression as given> = <value>`: whole numbers exact,
|
||||
a float that is a whole number below 10^15 as that whole number, other floats to 10 significant
|
||||
digits. The reply model says it in the user's language.
|
||||
- **Errors the model can act on.** A refused or failed expression (division by zero, a function
|
||||
outside its range, not valid math, too long, too large) comes back as `success=False` with the
|
||||
reason, so the model can fix the expression.
|
||||
- **Private numbers stay out of logs.** Debug logs carry the expression's length and the outcome,
|
||||
never its text.
|
||||
- **Always offered.** It reads and sends nothing, so it has no feature switch; `disabled_tools`
|
||||
still turns it off like any built-in.
|
||||
|
||||
## Schema
|
||||
|
||||
| field | type | meaning |
|
||||
|---|---|---|
|
||||
| `expression` | string, required | numbers and operators only, e.g. `3847*2963`, `478500*17/100` (a percentage as /100), `1.07^12`, `sqrt(2)`; no units, words or thousands separators |
|
||||
|
||||
## Tests
|
||||
|
||||
- `tests/test_calculator_tool.py`: exact values, readable fractions, refused code and non-math,
|
||||
huge powers failing fast, bad expressions, offered and run through the registry.
|
||||
- `evals/test_calculator_tool.py`: a four-digit product and a fractional power use the tool and
|
||||
the answer carries the exact value; an unrelated question does not use it (qwen3:8b, v2 setup:
|
||||
0 of 2 before the tool, 12 of 12 over four runs after).
|
||||
@@ -25,6 +25,7 @@ from .builtin.collected_news import CollectedNewsTool, COLLECT_ENV
|
||||
from .builtin.bot_browser import BotBrowserTool, CDP_ENV
|
||||
from .builtin.refresh_mcp_tools import RefreshMCPToolsTool
|
||||
from .builtin.weather import WeatherTool
|
||||
from .builtin.calculator import CalculatorTool
|
||||
from .builtin.stop import StopTool
|
||||
from .builtin.tool_search import ToolSearchTool
|
||||
from .builtin.browse_and_play import BrowseAndPlayTool
|
||||
@@ -47,6 +48,7 @@ BUILTIN_TOOLS = {
|
||||
"deleteMeal": DeleteMealTool(),
|
||||
"refreshMCPTools": RefreshMCPToolsTool(),
|
||||
"getWeather": WeatherTool(),
|
||||
"calculator": CalculatorTool(),
|
||||
"stop": StopTool(),
|
||||
"toolSearchTool": ToolSearchTool(),
|
||||
"browseAndPlay": BrowseAndPlayTool(),
|
||||
|
||||
85
tests/test_calculator_tool.py
Normal file
85
tests/test_calculator_tool.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""The calculator tool (src/jarvis/tools/builtin/calculator.spec.md): exact arithmetic for the reply
|
||||
model, evaluated from a whitelist of number operations, never as code."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from jarvis.tools.builtin.calculator import CalculatorTool
|
||||
from jarvis.tools.registry import enabled_builtin_tools, run_tool_with_retries
|
||||
|
||||
|
||||
def run(expression):
|
||||
return CalculatorTool().run({"expression": expression}, None)
|
||||
|
||||
|
||||
def value_of(result):
|
||||
assert result.success, result.error_message
|
||||
return result.reply_text.rsplit("=", 1)[1].strip()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("expression, expected", [
|
||||
("3847*2963", str(3847 * 2963)),
|
||||
("478500*17/100", "81345"),
|
||||
("2370000 * 14", str(2370000 * 14)),
|
||||
("2^10", "1024"),
|
||||
("12 × 3 ÷ 4", "9"),
|
||||
("sqrt(144) + abs(-3)", "15"),
|
||||
("(1 + 2) * -3", "-9"),
|
||||
])
|
||||
def test_it_gives_the_exact_value(expression, expected):
|
||||
assert value_of(run(expression)) == expected
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_fractions_are_rounded_to_a_readable_length():
|
||||
got = float(value_of(run("1.07^12")))
|
||||
assert got == pytest.approx(1.07 ** 12, rel=1e-9)
|
||||
assert len(value_of(run("98765/37"))) <= 16
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_answer_names_the_expression_it_computed():
|
||||
assert run("3847*2963").reply_text.startswith("3847*2963")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("expression", [
|
||||
"__import__('os').system('echo hacked')",
|
||||
"open('/etc/passwd').read()",
|
||||
"(1).__class__",
|
||||
"[1, 2, 3]",
|
||||
"x + 1",
|
||||
"'a' * 3",
|
||||
])
|
||||
def test_anything_but_arithmetic_is_refused(expression):
|
||||
r = run(expression)
|
||||
assert not r.success and r.error_message
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("expression", ["9**9**9", "10**100000", "(10**300)**300"])
|
||||
def test_a_huge_power_fails_fast_instead_of_hanging(expression):
|
||||
start = time.monotonic()
|
||||
r = run(expression)
|
||||
assert not r.success and r.error_message
|
||||
assert time.monotonic() - start < 1
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.parametrize("expression", ["1/0", "", " ", "2 +", "1" * 300])
|
||||
def test_a_bad_expression_gets_an_error_the_model_can_act_on(expression):
|
||||
r = run(expression)
|
||||
assert not r.success and r.error_message
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_it_is_offered_and_runs_through_the_registry(mock_config):
|
||||
cfg = mock_config
|
||||
assert "calculator" in enabled_builtin_tools(cfg)
|
||||
r = run_tool_with_retries(db=None, cfg=cfg, tool_name="calculator", tool_args={"expression": "6*7"},
|
||||
system_prompt="", original_prompt="", redacted_text="", max_retries=0)
|
||||
assert r.success and r.reply_text.endswith("42")
|
||||
Reference in New Issue
Block a user