Compare commits
14 Commits
app-v0.1.4
...
app-v0.1.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3d1b6a794 | ||
|
|
4cdfecee82 | ||
|
|
c35737e33f | ||
|
|
fc4b77f826 | ||
|
|
871a6438b8 | ||
|
|
99b7234336 | ||
|
|
b39aabd368 | ||
|
|
d7dc62c202 | ||
|
|
b64097ef0d | ||
|
|
81bd8bd573 | ||
|
|
e716065538 | ||
|
|
41f539dd48 | ||
|
|
b30aa4a0db | ||
|
|
835b547ca2 |
@@ -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.49"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jarvis-app"
|
||||
version = "0.1.49"
|
||||
version = "0.1.55"
|
||||
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.49"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
@@ -2666,7 +2666,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "jarvis-shell"
|
||||
version = "0.1.49"
|
||||
version = "0.1.55"
|
||||
dependencies = [
|
||||
"jarvis-app",
|
||||
"serde_json",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jarvis-shell"
|
||||
version = "0.1.49"
|
||||
version = "0.1.55"
|
||||
edition = "2021"
|
||||
rust-version = "1.85"
|
||||
description = "Jarvis v2 management app window (Tauri 2 over the app core's AdminApi)"
|
||||
|
||||
@@ -35,6 +35,9 @@ pub struct CallSettings {
|
||||
/// their last utterance's end, is still asking: what they say is joined to the request
|
||||
/// (`call.continueMs`; zero turns it off).
|
||||
pub continue_window: Duration,
|
||||
/// A voice answer starts playing only once its asker has been quiet this long after their request
|
||||
/// ended (they may go on); it is written meanwhile (`call.answerWaitMs`; zero: as soon as written).
|
||||
pub answer_wait: Duration,
|
||||
/// Play the earcon when Jarvis takes a voice call (`call.earcon`).
|
||||
pub earcon: bool,
|
||||
}
|
||||
@@ -51,6 +54,7 @@ impl Default for CallSettings {
|
||||
stop_words: ["멈춰", "그만", "정지", "stop"].map(String::from).to_vec(),
|
||||
follow_up: Duration::from_millis(1500),
|
||||
continue_window: Duration::from_millis(5000),
|
||||
answer_wait: Duration::from_millis(3000),
|
||||
earcon: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,10 @@ pub struct Room {
|
||||
pub trait Voice {
|
||||
/// Have the brain answer and speak it; the speech request id, or None when it cannot. `heard`:
|
||||
/// when the request's speech ended and its final arrived (the dashboard times the answer by it).
|
||||
fn answer(&self, user: u64, text: &str, heard: (Instant, Instant)) -> Option<String>;
|
||||
/// `hold`: the answer is written but does not start playing until `release`.
|
||||
fn answer(&self, user: u64, text: &str, heard: (Instant, Instant), hold: bool) -> Option<String>;
|
||||
/// Let a held answer play.
|
||||
fn release(&self, id: &str);
|
||||
/// Stop one speech request.
|
||||
fn cancel(&self, id: &str);
|
||||
/// Stop all speech at once.
|
||||
@@ -57,8 +60,11 @@ pub trait Voice {
|
||||
}
|
||||
|
||||
impl Voice for DiscordCore {
|
||||
fn answer(&self, user: u64, text: &str, heard: (Instant, Instant)) -> Option<String> {
|
||||
DiscordCore::answer(self, user, text, heard)
|
||||
fn answer(&self, user: u64, text: &str, heard: (Instant, Instant), hold: bool) -> Option<String> {
|
||||
DiscordCore::answer(self, user, text, heard, hold)
|
||||
}
|
||||
fn release(&self, id: &str) {
|
||||
DiscordCore::release(self, id)
|
||||
}
|
||||
fn cancel(&self, id: &str) {
|
||||
DiscordCore::cancel(self, id)
|
||||
@@ -170,6 +176,8 @@ pub struct Conversation<V: Voice> {
|
||||
/// Each speaker's latest voice request whose answer has not been heard yet: what they say next
|
||||
/// may still be part of it ("Going on").
|
||||
turns: HashMap<u64, Turn>,
|
||||
/// Held answers (speech id): their asker, and when they will have been quiet for `call.answerWaitMs`.
|
||||
waiting: HashMap<String, (u64, Instant)>,
|
||||
}
|
||||
|
||||
/// A voice request whose answer is not heard yet.
|
||||
@@ -202,7 +210,7 @@ impl<V: Voice> Conversation<V> {
|
||||
Self { voice, calls, policy: Policy::new(policy), next_id: 0, answers: HashMap::new(),
|
||||
by_speech: HashMap::new(), asks: HashMap::new(), missed: MissedLog::default(), chat: ChatCalls::default(),
|
||||
chat_answers: HashMap::new(), started: HashMap::new(), wakes: HashMap::new(),
|
||||
chimed: HashSet::new(), turns: HashMap::new() }
|
||||
chimed: HashSet::new(), turns: HashMap::new(), waiting: HashMap::new() }
|
||||
}
|
||||
|
||||
/// Answer the registered chat channels too.
|
||||
@@ -272,6 +280,24 @@ impl<V: Voice> Conversation<V> {
|
||||
}
|
||||
|
||||
pub fn on_event(&mut self, ev: &CoreEvent, now: Instant) {
|
||||
self.handle(ev, now);
|
||||
self.release_due(now);
|
||||
}
|
||||
|
||||
/// Held answers whose asker has been quiet for `call.answerWaitMs` start playing; while the asker
|
||||
/// talks, their answer waits for what they say (it may join the request).
|
||||
fn release_due(&mut self, now: Instant) {
|
||||
let due: Vec<String> = self.waiting.iter()
|
||||
.filter(|(_, (speaker, at))| now >= *at && !self.started.contains_key(speaker))
|
||||
.map(|(sid, _)| sid.clone()).collect();
|
||||
for sid in due {
|
||||
self.waiting.remove(&sid);
|
||||
debug_log!("conversation", "release speech={sid}");
|
||||
self.voice.release(&sid);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(&mut self, ev: &CoreEvent, now: Instant) {
|
||||
match ev {
|
||||
CoreEvent::SpeechStart(h) => {
|
||||
self.policy.utterance_open(h.speaker_id);
|
||||
@@ -282,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),
|
||||
@@ -361,7 +391,7 @@ impl<V: Voice> Conversation<V> {
|
||||
let id = format!("q{}", req.id);
|
||||
if self.voice.ask_addressed(&id, speaker, &text, room) {
|
||||
self.turns.insert(speaker, Turn { id: req.id, text: req.text.clone(),
|
||||
ended_at: req.ended_at, ask: Some(id.clone()), held: false, heard: false });
|
||||
ended_at: req.ended_at, ask: Some(id.clone()), held: self.holds(speaker), heard: false });
|
||||
self.asks.insert(id, (req, now));
|
||||
} else {
|
||||
let a = self.policy.utterance_closed(speaker, now);
|
||||
@@ -390,19 +420,25 @@ impl<V: Voice> Conversation<V> {
|
||||
let a = self.policy.ranked(rank_id, &order, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
// The answer is heard: what its asker says next is a new request.
|
||||
// The answer is heard; while it plays, its asker may still go on (within call.continueMs).
|
||||
CoreEvent::SpeakStart(id) => {
|
||||
if let Some(pid) = self.by_speech.get(id).copied() {
|
||||
self.turns.retain(|_, t| t.id != pid || t.held);
|
||||
for t in self.turns.values_mut().filter(|t| t.id == pid) {
|
||||
t.heard = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
CoreEvent::SpeakEnd(e) => {
|
||||
self.waiting.remove(&e.id);
|
||||
if let Some(pid) = self.by_speech.remove(&e.id) {
|
||||
self.answers.remove(&pid);
|
||||
self.turns.retain(|_, t| t.id != pid);
|
||||
// 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;
|
||||
}
|
||||
debug_log!("conversation", "answer req={pid} done played={} cancelled={} failed={}",
|
||||
e.played, e.cancelled, e.failed);
|
||||
let a = self.policy.answer_done(pid, now);
|
||||
@@ -429,10 +465,17 @@ impl<V: Voice> Conversation<V> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The speaker's next utterance already started (a pause shorter than the first final's
|
||||
/// transcription): their new request is held open for it from the start.
|
||||
fn holds(&self, speaker: u64) -> bool {
|
||||
!self.calls.continue_window.is_zero() && self.started.contains_key(&speaker)
|
||||
}
|
||||
|
||||
/// A voice request goes to the policy; until its answer is heard, its speaker may go on.
|
||||
fn voice_request(&mut self, req: Request, now: Instant) {
|
||||
let held = self.holds(req.speaker);
|
||||
self.turns.insert(req.speaker, Turn { id: req.id, text: req.text.clone(), ended_at: req.ended_at, ask: None,
|
||||
held: false, heard: false });
|
||||
held, heard: false });
|
||||
let a = self.policy.request(req, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
@@ -454,7 +497,8 @@ impl<V: Voice> Conversation<V> {
|
||||
return None;
|
||||
}
|
||||
let t = self.turns.remove(&speaker).expect("checked");
|
||||
let earcon_played = self.chimed.remove(&t.id) || (self.calls.earcon && self.answers.contains_key(&t.id));
|
||||
let earcon_played = self.chimed.remove(&t.id)
|
||||
|| (self.calls.earcon && (self.answers.contains_key(&t.id) || t.heard));
|
||||
debug_log!("conversation", "going on req={} speaker={speaker}", t.id);
|
||||
match t.ask {
|
||||
Some(q) => {
|
||||
@@ -472,6 +516,7 @@ impl<V: Voice> Conversation<V> {
|
||||
fn stop_everything(&mut self, now: Instant) {
|
||||
self.wakes.clear();
|
||||
self.turns.clear();
|
||||
self.waiting.clear();
|
||||
let a = self.policy.stop();
|
||||
self.apply(a, now);
|
||||
self.chimed.clear(); // nothing is waiting any more
|
||||
@@ -504,26 +549,33 @@ impl<V: Voice> Conversation<V> {
|
||||
}
|
||||
let a = self.policy.tick(now);
|
||||
self.apply(a, now);
|
||||
self.release_due(now);
|
||||
}
|
||||
|
||||
pub fn next_deadline(&self) -> Option<Instant> {
|
||||
let asks = self.asks.values().map(|(_, at)| *at + ADDRESSED_TIMEOUT);
|
||||
let wakes = self.wakes.values().filter_map(|(_, d)| *d);
|
||||
self.policy.next_deadline().into_iter().chain(asks).chain(wakes).min()
|
||||
// Not while the asker talks: their final decides.
|
||||
let held = self.waiting.values().filter(|(s, _)| !self.started.contains_key(s)).map(|(_, at)| *at);
|
||||
self.policy.next_deadline().into_iter().chain(asks).chain(wakes).chain(held).min()
|
||||
}
|
||||
|
||||
fn apply(&mut self, actions: Vec<Action>, now: Instant) {
|
||||
for action in actions {
|
||||
match action {
|
||||
Action::Answer(r) => match {
|
||||
// The earcon plays first, then the answer as soon as it is written.
|
||||
// The earcon plays first, then the answer once it is written and its asker has
|
||||
// been quiet for call.answerWaitMs.
|
||||
if self.calls.earcon && !self.chimed.remove(&r.id) {
|
||||
self.voice.earcon();
|
||||
}
|
||||
self.voice.answer(r.speaker, &r.text, (r.ended_at, r.arrived_at))
|
||||
self.voice.answer(r.speaker, &r.text, (r.ended_at, r.arrived_at), !self.calls.answer_wait.is_zero())
|
||||
} {
|
||||
Some(sid) => {
|
||||
debug_log!("conversation", "answer req={} speaker={} speech={sid}", r.id, r.speaker);
|
||||
if !self.calls.answer_wait.is_zero() {
|
||||
self.waiting.insert(sid.clone(), (r.speaker, r.ended_at + self.calls.answer_wait));
|
||||
}
|
||||
self.by_speech.insert(sid.clone(), r.id);
|
||||
self.answers.insert(r.id, sid);
|
||||
}
|
||||
@@ -535,6 +587,7 @@ impl<V: Voice> Conversation<V> {
|
||||
Action::StopAnswer(pid) => {
|
||||
if let Some(sid) = self.answers.remove(&pid) {
|
||||
self.by_speech.remove(&sid);
|
||||
self.waiting.remove(&sid);
|
||||
self.voice.cancel(&sid);
|
||||
}
|
||||
}
|
||||
@@ -589,7 +642,7 @@ mod tests {
|
||||
|
||||
/// The tests call Jarvis by one wake word of their own, whatever the default is.
|
||||
fn test_calls() -> CallSettings {
|
||||
CallSettings { wake_words: vec!["자비스".into()], ..CallSettings::default() }
|
||||
CallSettings { wake_words: vec!["자비스".into()], answer_wait: Duration::ZERO, ..CallSettings::default() }
|
||||
}
|
||||
use crate::discord::{Heard, HeardFinal};
|
||||
use crate::playback::PlaybackEnd;
|
||||
@@ -601,6 +654,9 @@ mod tests {
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum Did {
|
||||
Answer(u64, String),
|
||||
/// The answer just asked for is held until released.
|
||||
Held(String),
|
||||
Release(String),
|
||||
Cancel(String),
|
||||
StopAll,
|
||||
Earcon,
|
||||
@@ -625,10 +681,17 @@ mod tests {
|
||||
people: Rc<RefCell<Vec<u64>>>,
|
||||
}
|
||||
impl Voice for Fake {
|
||||
fn answer(&self, user: u64, text: &str, _heard: (Instant, Instant)) -> Option<String> {
|
||||
fn answer(&self, user: u64, text: &str, _heard: (Instant, Instant), hold: bool) -> Option<String> {
|
||||
*self.n.borrow_mut() += 1;
|
||||
let id = format!("s{}", self.n.borrow());
|
||||
self.did.borrow_mut().push(Did::Answer(user, text.into()));
|
||||
Some(format!("s{}", self.n.borrow()))
|
||||
if hold {
|
||||
self.did.borrow_mut().push(Did::Held(id.clone()));
|
||||
}
|
||||
Some(id)
|
||||
}
|
||||
fn release(&self, id: &str) {
|
||||
self.did.borrow_mut().push(Did::Release(id.into()));
|
||||
}
|
||||
fn cancel(&self, id: &str) {
|
||||
self.did.borrow_mut().push(Did::Cancel(id.into()));
|
||||
@@ -711,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())]);
|
||||
}
|
||||
|
||||
@@ -815,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())]);
|
||||
}
|
||||
|
||||
@@ -902,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())]);
|
||||
}
|
||||
|
||||
@@ -1151,13 +1215,15 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn once_the_answer_is_heard_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(&fin(A, "고마워", 100), ms(t, 2500));
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "계산기 켜 줘".into()), Did::Cancel("s1".into()),
|
||||
Did::Answer(A, "고마워".into())]);
|
||||
c.on_event(&end("s1", false), ms(t, 2000));
|
||||
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);
|
||||
let pause = test_calls().continue_window.as_millis() as u64;
|
||||
@@ -1202,6 +1268,200 @@ mod tests {
|
||||
assert_eq!(f.take(), vec![Did::Cancel("s1".into()), Did::Answer(A, "고마워".into())]);
|
||||
}
|
||||
|
||||
const ALL: [PolicyKind; 4] = [PolicyKind::Latest, PolicyKind::InOrder, PolicyKind::First, PolicyKind::Important];
|
||||
|
||||
/// Alone with Jarvis, answers held until the asker has been quiet for `wait_ms`.
|
||||
fn alone_waiting(kind: PolicyKind, wait_ms: u64) -> (Conversation<Fake>, Fake, Instant) {
|
||||
let f = Fake::default();
|
||||
let calls = CallSettings { mode: CallMode::Addressed, earcon: false, answer_wait: Duration::from_millis(wait_ms),
|
||||
..test_calls() };
|
||||
let policy = PolicySettings { kind, collect: Duration::ZERO, ..PolicySettings::default() };
|
||||
*f.people.borrow_mut() = vec![A];
|
||||
(Conversation::new(f.clone(), calls, policy), f, Instant::now())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_starts_only_after_its_asker_was_quiet_for_the_wait() {
|
||||
// Live 2026-11-19: pauses inside one thought were up to 4.7 s, longer than writing an answer.
|
||||
for kind in ALL {
|
||||
let (mut c, f, t) = alone_waiting(kind, 3000);
|
||||
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0)); // ended at -100
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "계산기 켜 줘".into()), Did::Held("s1".into())], "{kind:?}");
|
||||
assert_eq!(c.next_deadline(), Some(ms(t, 2900)), "{kind:?}");
|
||||
c.tick(ms(t, 2800));
|
||||
assert!(f.take().is_empty(), "{kind:?}");
|
||||
c.tick(ms(t, 2900));
|
||||
assert_eq!(f.take(), vec![Did::Release("s1".into())], "{kind:?}");
|
||||
assert_eq!(c.next_deadline(), None, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_answer_waits_while_its_asker_talks_and_their_words_join_it() {
|
||||
for kind in ALL {
|
||||
let (mut c, f, t) = alone_waiting(kind, 3000);
|
||||
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0));
|
||||
f.take();
|
||||
c.on_event(&start(A, 2), ms(t, 2000));
|
||||
c.tick(ms(t, 2900));
|
||||
assert!(f.take().is_empty(), "still talking ({kind:?})");
|
||||
c.on_event(&fin_utt(A, 2, "메모장도"), ms(t, 3500));
|
||||
assert_eq!(f.take(), vec![Did::Cancel("s1".into()), Did::Answer(A, "계산기 켜 줘 메모장도".into()),
|
||||
Did::Held("s2".into())], "{kind:?}");
|
||||
c.tick(ms(t, 6400)); // the joined request ended at 3400
|
||||
assert_eq!(f.take(), vec![Did::Release("s2".into())], "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0));
|
||||
c.on_event(&start(A, 2), ms(t, 2000));
|
||||
c.tick(ms(t, 2900));
|
||||
f.take();
|
||||
c.on_event(&fin_utt(A, 2, " "), ms(t, 3500));
|
||||
assert_eq!(f.take(), vec![Did::Release("s1".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn going_on_while_the_answer_plays_stops_it_and_answers_all_of_it() {
|
||||
// A pause longer than the wait: the answer started, then the speaker went on within
|
||||
// call.continueMs of their request's end.
|
||||
for kind in ALL {
|
||||
let (mut c, f, t) = alone_waiting(kind, 3000);
|
||||
c.on_event(&fin(A, "계산기 켜 줘", 100), ms(t, 0));
|
||||
c.tick(ms(t, 2900));
|
||||
c.on_event(&speak_start("s1"), ms(t, 3000));
|
||||
f.take();
|
||||
c.on_event(&fin(A, "제일 앞으로", 100), ms(t, 5000)); // started at 3900, 4 s after the end
|
||||
assert_eq!(f.take(), vec![Did::Cancel("s1".into()), Did::Answer(A, "계산기 켜 줘 제일 앞으로".into()),
|
||||
Did::Held("s2".into())], "{kind:?}");
|
||||
assert_eq!(c.missed().count(), 0, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn going_on_is_joined_even_when_the_short_answer_already_ended() {
|
||||
// Final -> next SpeechStart -> the answer plays and ends -> next Final.
|
||||
for kind in ALL {
|
||||
let (mut c, f, t) = alone(kind);
|
||||
c.on_event(&fin(A, "지금 화면 봐봐", 100), ms(t, 0));
|
||||
c.on_event(&start(A, 2), ms(t, 1000));
|
||||
c.on_event(&speak_start("s1"), ms(t, 1500));
|
||||
c.on_event(&end("s1", false), ms(t, 2500));
|
||||
c.on_event(&fin_utt(A, 2, "디코 화면 공유 창에 가려져 있잖아"), ms(t, 4000));
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "지금 화면 봐봐".into()),
|
||||
Did::Answer(A, "지금 화면 봐봐 디코 화면 공유 창에 가려져 있잖아".into())], "{kind:?}");
|
||||
assert_eq!(c.missed().count(), 0, "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn going_on_that_started_before_the_first_final_is_joined() {
|
||||
// A very short pause: the next utterance starts before the first one's final arrives.
|
||||
for kind in ALL {
|
||||
let (mut c, f, t) = alone(kind);
|
||||
c.on_event(&start(A, 1), ms(t, 0));
|
||||
c.on_event(&start(A, 2), ms(t, 1000));
|
||||
c.on_event(&fin_utt(A, 1, "지금 화면 봐봐"), ms(t, 1100));
|
||||
c.on_event(&speak_start("s1"), ms(t, 1600));
|
||||
c.on_event(&fin_utt(A, 2, "디코 화면 공유 창에 가려져 있잖아"), ms(t, 3000));
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "지금 화면 봐봐".into()), Did::Cancel("s1".into()),
|
||||
Did::Answer(A, "지금 화면 봐봐 디코 화면 공유 창에 가려져 있잖아".into())], "{kind:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_request_whose_next_final_is_empty_or_a_stop_is_not_asked_again() {
|
||||
for kind in ALL {
|
||||
for last in ["", "자비스 멈춰"] {
|
||||
// (a) the answer already ended.
|
||||
let (mut c, f, t) = alone(kind);
|
||||
c.on_event(&fin(A, "지금 화면 봐봐", 100), ms(t, 0));
|
||||
c.on_event(&start(A, 2), ms(t, 1000));
|
||||
c.on_event(&speak_start("s1"), ms(t, 1500));
|
||||
c.on_event(&end("s1", false), ms(t, 2500));
|
||||
c.on_event(&fin_utt(A, 2, last), ms(t, 4000));
|
||||
let did = f.take();
|
||||
assert_eq!(did.iter().filter(|d| matches!(d, Did::Answer(..))).count(), 1, "{kind:?} {last:?}");
|
||||
// What follows is a new request, not joined to the old one.
|
||||
c.on_event(&fin(A, "고마워", 100), ms(t, 5000));
|
||||
assert_eq!(f.take().into_iter().filter(|d| matches!(d, Did::Answer(..))).collect::<Vec<_>>(),
|
||||
vec![Did::Answer(A, "고마워".into())], "{kind:?} {last:?}");
|
||||
// (b) the next utterance started before the first final, the answer is playing.
|
||||
let (mut c, f, t) = alone(kind);
|
||||
c.on_event(&start(A, 1), ms(t, 0));
|
||||
c.on_event(&start(A, 2), ms(t, 1000));
|
||||
c.on_event(&fin_utt(A, 1, "지금 화면 봐봐"), ms(t, 1100));
|
||||
c.on_event(&speak_start("s1"), ms(t, 1600));
|
||||
c.on_event(&fin_utt(A, 2, last), ms(t, 3000));
|
||||
let did = f.take();
|
||||
assert_eq!(did.iter().filter(|d| matches!(d, Did::Answer(..))).count(), 1, "{kind:?} {last:?}");
|
||||
if last.is_empty() {
|
||||
assert!(!did.contains(&Did::Cancel("s1".into())), "noise does not stop the answer ({kind:?})");
|
||||
} else {
|
||||
assert!(did.contains(&Did::StopAll), "{kind:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn going_on_lets_the_brain_get_ready_for_the_joined_request() {
|
||||
let (mut c, f, t) = alone(PolicyKind::Latest);
|
||||
|
||||
@@ -34,7 +34,8 @@ 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 is not heard yet. 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
|
||||
combining marks dropped). NFKD splits Hangul syllables into their letters, so "자비즈" is one letter
|
||||
@@ -83,8 +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 is heard (the first audio of its speech
|
||||
plays, `SpeakStart`), 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
|
||||
@@ -96,14 +98,26 @@ started within `call.continueMs` of the request's end (start = the final's arriv
|
||||
a stop (a stop stops, as always) and an empty final (noise the worker rejected: nothing is joined
|
||||
or asked again, the request goes on as it was).
|
||||
- When the speaker's next utterance starts (`SpeechStart`) within `call.continueMs` of the request's
|
||||
end, the request is held open for that utterance's final, also if its answer starts playing
|
||||
meanwhile; the joined request then stops that answer. An empty final ends the hold.
|
||||
- Other speakers' utterances never join it. An answer already heard, 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.
|
||||
end, or had already started when the request's final came (a pause shorter than the
|
||||
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. 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).
|
||||
|
||||
**Waiting before answering.** So that a pause inside one thought does not get an answer, a voice
|
||||
answer is written at once but starts playing only when its asker has been quiet for
|
||||
`call.answerWaitMs` after the request ended (default 3 s: 8 of the 10 pauses inside one thought
|
||||
measured live 2026-11-19 were shorter). While the asker is talking when that time comes, the answer
|
||||
waits for that utterance's final: it joins the request (Going on, the held answer is cancelled and
|
||||
the joined one waits again from its own end), or, when it is empty or not joined, the answer plays.
|
||||
A stop stops it as always. The earcon is not held: it still tells the asker at once that Jarvis
|
||||
heard them. Answers queued behind a held one wait their turn.
|
||||
|
||||
**Earcon.** A short two-tone "띠링" (about 0.3 s, made by the app, `app/src/earcon.rs`) tells the
|
||||
speaker Jarvis heard the call, long before the answer is written: it is the first sound after a call.
|
||||
It plays right before each voice answer starts (the policy's `Answer`), and at once when a wake word
|
||||
@@ -224,14 +238,17 @@ one request, stop all, earcon, prepare, ask "addressed", ask "rank"), so the glu
|
||||
judgement) closes the utterance, and no answer within 5 s counts as no, also when the answer arrives
|
||||
after that but before the timer ran.
|
||||
- Policy actions: `Answer` → the earcon (unless it already played for this request), then
|
||||
`answer(user, text)` (the brain answers and the answer is spoken; when it
|
||||
cannot be queued the answer is done at once); `StopAnswer` → `cancel` of that answer's speech;
|
||||
`answer(user, text, hold)` (the brain answers and the answer is spoken; held, with a non-zero
|
||||
`call.answerWaitMs`, until `release` when its asker has been quiet for it; when it cannot be
|
||||
queued the answer is done at once); `StopAnswer` → `cancel` of that answer's speech;
|
||||
`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, its request is no longer open (Going on),
|
||||
unless its speaker already started their next utterance (held).
|
||||
- `SpeakEnd` of an answer's speech is that answer's done. The end of a speech the loop already
|
||||
cancelled starts nothing.
|
||||
- `SpeakStart` of an answer's speech: the answer is heard (no second earcon when it is joined); its
|
||||
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.
|
||||
@@ -252,9 +269,12 @@ 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 is heard or the pause is longer than `call.continueMs`, a stop still
|
||||
stopping, no second earcon, an utterance started before the answer played still joined, an empty
|
||||
final joining nothing), interruption cancelling the right speech, a ranking deciding, end times from
|
||||
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
|
||||
after a hold asking nothing again), interruption cancelling the right speech, a ranking deciding, end times from
|
||||
`wait_ms`, and chat: an answer posted as a reply once, per-channel switches, no answers to bots or to
|
||||
a stop, chat wake words and designated people, a failed answer posting nothing). `tests/worker_protocol.rs` checks an answer spoken under its id and both judgements against
|
||||
the real Python worker with a fake brain.
|
||||
|
||||
@@ -563,15 +563,26 @@ impl DiscordCore {
|
||||
/// `SpeakStart` and `SpeakEnd` follow as for `say`), or None when not in a voice channel. It ends as
|
||||
/// failed when the brain gives no answer. `heard`: when the request's speech ended and its final
|
||||
/// arrived, passed on in `AnswerAsked`.
|
||||
pub fn answer(&self, user: u64, text: &str, heard: (Instant, Instant)) -> Option<String> {
|
||||
pub fn answer(&self, user: u64, text: &str, heard: (Instant, Instant), hold: bool) -> Option<String> {
|
||||
self.voice_channel_id()?;
|
||||
let id = with_playback(&self.inner, |p| p.adopt());
|
||||
let id = with_playback(&self.inner, |p| {
|
||||
let id = p.adopt();
|
||||
if hold {
|
||||
p.hold(&id);
|
||||
}
|
||||
id
|
||||
});
|
||||
let _ = self.inner.events.send(CoreEvent::AnswerAsked { id: id.clone(), user, ended_at: heard.0,
|
||||
final_at: heard.1 });
|
||||
self.inner.worker.reply_in(&id, user, text, "voice", true, None, ¬es_of(&self.inner, user));
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// Let an answer held by `answer(.., hold)` play.
|
||||
pub fn release(&self, id: &str) {
|
||||
with_playback(&self.inner, |p| p.release(id));
|
||||
}
|
||||
|
||||
/// Play the earcon in the voice channel, queued like speech. The request id, or None when not in a
|
||||
/// voice channel.
|
||||
pub fn earcon(&self) -> Option<String> {
|
||||
|
||||
@@ -171,7 +171,9 @@ and the late "left" update cancelled the new join (seen on real Discord).
|
||||
long the clip playing when it was stopped had played, timed from when it was handed to the player)
|
||||
so its voice recordings keep only what was heard (`voice_worker.spec.md`, "Recordings").
|
||||
- **Answering** (M4): `answer(user, text)` queues a request like `say` whose speech the worker makes
|
||||
from the brain's answer (`reply` with `speak`, under the request's id) and returns its id. No answer
|
||||
from the brain's answer (`reply` with `speak`, under the request's id) and returns its id. With
|
||||
`hold` it is written but does not start playing until `release(id)` (an answer that fails while held
|
||||
still ends at once and lets the queue go on). No answer
|
||||
from the brain, a refused `reply` (`brain_unavailable`) or a lost worker ends it as failed.
|
||||
`cancel(id)` stops one request (its clip if playing, the worker's unsent sentences, or the speech of
|
||||
an answer still being written) and the rest of the queue goes on. `ask_addressed(id, user, text)` and
|
||||
|
||||
@@ -48,6 +48,8 @@ struct Request {
|
||||
failed: bool,
|
||||
played: u32,
|
||||
started: bool,
|
||||
/// Not to start playing until released (`hold`).
|
||||
held: bool,
|
||||
}
|
||||
|
||||
pub struct Playback<B: TtsBackend, S: ClipSink> {
|
||||
@@ -81,7 +83,7 @@ impl<B: TtsBackend, S: ClipSink> Playback<B, S> {
|
||||
self.counter += 1;
|
||||
let id = format!("r{}", self.counter);
|
||||
self.queue.push_back(Request { id: id.clone(), chunks: BTreeMap::new(), next: 0, done: false, failed: false,
|
||||
played: 0, started: false });
|
||||
played: 0, started: false, held: false });
|
||||
crate::debug_log!("play", "say id={id} chars={} more={more} queued={}", text.chars().count(), self.queue.len());
|
||||
self.backend.tts(&id, text, more);
|
||||
id
|
||||
@@ -93,7 +95,7 @@ impl<B: TtsBackend, S: ClipSink> Playback<B, S> {
|
||||
self.counter += 1;
|
||||
let id = format!("r{}", self.counter);
|
||||
self.queue.push_back(Request { id: id.clone(), chunks: BTreeMap::new(), next: 0, done: false, failed: false,
|
||||
played: 0, started: false });
|
||||
played: 0, started: false, held: false });
|
||||
crate::debug_log!("play", "answer id={id} queued={}", self.queue.len());
|
||||
id
|
||||
}
|
||||
@@ -103,7 +105,7 @@ impl<B: TtsBackend, S: ClipSink> Playback<B, S> {
|
||||
self.counter += 1;
|
||||
let id = format!("r{}", self.counter);
|
||||
self.queue.push_back(Request { id: id.clone(), chunks: BTreeMap::from([(0, pcm)]), next: 0, done: true,
|
||||
failed: false, played: 0, started: false });
|
||||
failed: false, played: 0, started: false, held: false });
|
||||
crate::debug_log!("play", "clip id={id} queued={}", self.queue.len());
|
||||
self.pump();
|
||||
id
|
||||
@@ -118,6 +120,22 @@ impl<B: TtsBackend, S: ClipSink> Playback<B, S> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep a request that has not started from starting until `release` (the asker may go on).
|
||||
pub fn hold(&mut self, id: &str) {
|
||||
if let Some(r) = self.queue.iter_mut().find(|r| r.id == id && !r.started) {
|
||||
r.held = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Let a held request play.
|
||||
pub fn release(&mut self, id: &str) {
|
||||
if let Some(r) = self.queue.iter_mut().find(|r| r.id == id && r.held) {
|
||||
r.held = false;
|
||||
crate::debug_log!("play", "release id={id}");
|
||||
self.pump();
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop one request: its clip if it is playing, its unsent sentences at the worker. The rest of the
|
||||
/// queue goes on.
|
||||
pub fn cancel(&mut self, id: &str) {
|
||||
@@ -207,6 +225,9 @@ impl<B: TtsBackend, S: ClipSink> Playback<B, S> {
|
||||
head.next = first;
|
||||
}
|
||||
}
|
||||
if head.held && head.chunks.contains_key(&head.next) {
|
||||
return;
|
||||
}
|
||||
if let Some(pcm) = head.chunks.remove(&head.next) {
|
||||
head.next += 1;
|
||||
head.played += 1;
|
||||
@@ -480,4 +501,28 @@ mod tests {
|
||||
assert_eq!(f.0.borrow().cancelled, vec![id.clone()]);
|
||||
assert!(p.take_events().contains(&end(&cue2, 0, true, false)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_answer_waits_for_its_release_and_a_failed_one_does_not_block() {
|
||||
let (mut p, f) = setup();
|
||||
let id = p.adopt();
|
||||
p.hold(&id);
|
||||
p.audio(&id, 0, b("a0"));
|
||||
p.done(&done(&id, false));
|
||||
assert!(f.0.borrow().played.is_empty(), "written, but held");
|
||||
assert!(p.take_events().is_empty());
|
||||
p.release(&id);
|
||||
assert_eq!(f.0.borrow().played, vec!["a0"]);
|
||||
assert_eq!(p.take_events(), vec![PlaybackEvent::Start(id.clone())]);
|
||||
// An answer that failed while held ends at once, and the next request plays.
|
||||
p.clip_ended();
|
||||
p.take_events();
|
||||
let bad = p.adopt();
|
||||
p.hold(&bad);
|
||||
let next = p.say("b", false);
|
||||
p.audio(&next, 0, b("b0"));
|
||||
p.fail(&bad);
|
||||
assert_eq!(f.0.borrow().played, vec!["a0", "b0"]);
|
||||
assert_eq!(p.take_events()[0], end(&bad, 0, false, true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -454,6 +454,7 @@ fn parse_call(raw: &Map<String, Value>, wake_words: &[String], d: &CallSettings)
|
||||
stop_words,
|
||||
follow_up: get_ms(call, "followUpMs", "call", d.follow_up, 5000)?,
|
||||
continue_window: get_ms(call, "continueMs", "call", d.continue_window, 15000)?,
|
||||
answer_wait: get_ms(call, "answerWaitMs", "call", d.answer_wait, 10000)?,
|
||||
earcon: get_bool(call, "earcon", "call", d.earcon)?,
|
||||
},
|
||||
chat_wake_words,
|
||||
|
||||
@@ -96,6 +96,7 @@ pub fn fields() -> Vec<Field> {
|
||||
json!(["멈춰", "그만", "정지", "stop"]), "정지 명령"),
|
||||
f("call.followUpMs", Call, Int { min: 0, max: 5000 }, json!(1500), "호출어 뒤 이어 말하기 대기(ms)"),
|
||||
f("call.continueMs", Call, Int { min: 0, max: 15000 }, json!(5000), "끊어 말한 문장 합치기(ms)"),
|
||||
f("call.answerWaitMs", Call, Int { min: 0, max: 10000 }, json!(3000), "말이 끝나고 답하기 전 기다림(ms)"),
|
||||
f("call.earcon", Call, Bool, json!(true), "부르면 효과음"),
|
||||
f("response.policy", Response, Choice { values: &["first", "inOrder", "latest", "important"] },
|
||||
json!("latest"), "동시 대화 응답 정책"),
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
//! cargo test --release --test live_round_trip -- --nocapture
|
||||
//!
|
||||
//! On Linux, put the pip CUDA libraries on LD_LIBRARY_PATH (nvidia/cublas/lib, nvidia/cudnn/lib).
|
||||
//! JARVIS_LIVE_WORKER_ARGS adds worker arguments (e.g. "--stt-device cpu --stt-compute int8").
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -165,16 +166,23 @@ fn background_voices(url: String, token: String, samples: Vec<Vec<i16>>, stop: A
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn conversation_round_trip_on_real_discord() {
|
||||
if std::env::var("JARVIS_LIVE_ROUND_TRIP").as_deref() != Ok("1") {
|
||||
eprintln!("skipped: set JARVIS_LIVE_ROUND_TRIP=1");
|
||||
return;
|
||||
}
|
||||
/// Both bots in the voice channel: the speaker bot (the "person") and Jarvis running the app's services
|
||||
/// from a fresh data folder, with `call` as the settings' call section.
|
||||
struct Live {
|
||||
speaker_id: u64,
|
||||
speaker_songbird: Arc<Songbird>,
|
||||
s_shards: Arc<serenity::gateway::ShardManager>,
|
||||
services: jarvis_app::services::Services,
|
||||
core: jarvis_app::discord::DiscordCore,
|
||||
events: Arc<Mutex<Vec<(Instant, CoreEvent)>>>,
|
||||
call: Arc<tokio::sync::Mutex<songbird::Call>>,
|
||||
ears: Ears,
|
||||
guild: u64,
|
||||
}
|
||||
|
||||
async fn start_live(call_settings: impl FnOnce(u64) -> Value) -> Live {
|
||||
let guild: u64 = env("JARVIS_LIVE_GUILD").parse().unwrap();
|
||||
let voice: u64 = env("JARVIS_LIVE_VOICE_CHANNEL").parse().unwrap();
|
||||
let rounds: usize = std::env::var("JARVIS_LIVE_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(2);
|
||||
let questions = PathBuf::from(env("JARVIS_LIVE_QUESTIONS"));
|
||||
env("JARVIS_LIVE_LLM_URL"); // the services point the brain at it (llm.url)
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
|
||||
@@ -208,21 +216,26 @@ async fn conversation_round_trip_on_real_discord() {
|
||||
if let Ok(m) = std::env::var("JARVIS_MELO_PYTHON") {
|
||||
args.extend(["--melo-python".to_string(), m]);
|
||||
}
|
||||
// e.g. "--stt-device cpu --stt-compute int8 --melo-device cpu" on a host without a GPU
|
||||
if let Ok(extra) = std::env::var("JARVIS_LIVE_WORKER_ARGS") {
|
||||
args.extend(extra.split_whitespace().map(String::from));
|
||||
}
|
||||
std::fs::write(data.join("config").join("settings.json"), serde_json::to_string_pretty(&json!({
|
||||
"discord": {"guildId": guild.to_string(), "voiceChannelId": voice.to_string()},
|
||||
// The "person" here is a bot, so bots must be heard; the recorded questions call "자비스".
|
||||
"voice": {"listenToBots": true, "wakeWords": ["자비스"]},
|
||||
"call": call_settings(speaker_id),
|
||||
"voiceWorker": {"python": env("JARVIS_VOICE_PYTHON"), "cwd": root.join("../src"), "args": args},
|
||||
"llm": {"url": env("JARVIS_LIVE_LLM_URL")},
|
||||
})).unwrap()).unwrap();
|
||||
std::env::set_var("JARVIS_DISCORD_TOKEN", &bot_token);
|
||||
let services = tokio::time::timeout(Duration::from_secs(300), start_services(&data, Arc::new(Llm::new(&data)))).await
|
||||
let mut services = tokio::time::timeout(Duration::from_secs(300), start_services(&data, Arc::new(Llm::new(&data)))).await
|
||||
.expect("services start in time").expect("services start");
|
||||
services.worker.wait_ready(Duration::from_secs(240)).await.expect("worker ready");
|
||||
let core = services.core.clone();
|
||||
let events: Arc<Mutex<Vec<(Instant, CoreEvent)>>> = Arc::default();
|
||||
let ev2 = events.clone();
|
||||
let mut rx = services.events;
|
||||
let mut rx = std::mem::replace(&mut services.events, mpsc::unbounded_channel().1);
|
||||
tokio::spawn(async move {
|
||||
while let Some(e) = rx.recv().await {
|
||||
ev2.lock().unwrap().push((Instant::now(), e));
|
||||
@@ -240,6 +253,31 @@ async fn conversation_round_trip_on_real_discord() {
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(2)).await; // the DAVE group settles after the join
|
||||
|
||||
Live { speaker_id, speaker_songbird, s_shards, services, core, events, call, ears, guild }
|
||||
}
|
||||
|
||||
impl Live {
|
||||
async fn stop(self) {
|
||||
let _ = self.speaker_songbird.remove(GuildId::new(self.guild)).await;
|
||||
self.s_shards.shutdown_all().await;
|
||||
self.services.core.leave("test").await;
|
||||
self.services.core.close().await;
|
||||
self.services.worker.close();
|
||||
self.services.worker_process.stop().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn conversation_round_trip_on_real_discord() {
|
||||
if std::env::var("JARVIS_LIVE_ROUND_TRIP").as_deref() != Ok("1") {
|
||||
eprintln!("skipped: set JARVIS_LIVE_ROUND_TRIP=1");
|
||||
return;
|
||||
}
|
||||
let live = start_live(|_| json!({})).await;
|
||||
let rounds: usize = std::env::var("JARVIS_LIVE_ROUNDS").ok().and_then(|v| v.parse().ok()).unwrap_or(2);
|
||||
let questions = PathBuf::from(env("JARVIS_LIVE_QUESTIONS"));
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
let Live { speaker_id, ref services, ref core, ref events, ref call, ref ears, .. } = live;
|
||||
let refs: Value = serde_json::from_str(&std::fs::read_to_string(questions.join("refs.json")).unwrap()).unwrap();
|
||||
let qs: Vec<(String, Vec<u8>)> = refs["samples"].as_array().unwrap().iter()
|
||||
.map(|r| (r["text"].as_str().unwrap().to_owned(), std::fs::read(questions.join(r["file"].as_str().unwrap())).unwrap()))
|
||||
@@ -355,12 +393,7 @@ async fn conversation_round_trip_on_real_discord() {
|
||||
println!("live round trip {}", serde_json::to_string_pretty(&Value::Object(report.clone())).unwrap());
|
||||
})).await;
|
||||
|
||||
let _ = speaker_songbird.remove(GuildId::new(guild)).await;
|
||||
s_shards.shutdown_all().await;
|
||||
services.core.leave("test").await;
|
||||
services.core.close().await;
|
||||
services.worker.close();
|
||||
services.worker_process.stop().await;
|
||||
live.stop().await;
|
||||
if let Err(panic) = steps {
|
||||
std::panic::resume_unwind(panic);
|
||||
}
|
||||
@@ -371,3 +404,76 @@ async fn conversation_round_trip_on_real_discord() {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Going on (conversation.spec.md), live: the person's own recordings of one thing said in pieces,
|
||||
/// played with the pauses they really made, get one answer. Settings as the person's own app: they
|
||||
/// are the only designated person, `addressed` mode, alone with Jarvis.
|
||||
///
|
||||
/// JARVIS_LIVE_GOING_ON=1 (the env of conversation_round_trip_on_real_discord, without the questions)
|
||||
/// JARVIS_LIVE_PIECES=<dir with pieces.json: [{"name", "file"}], each file one 16 kHz mono wav of
|
||||
/// the pieces and the silence between them> cargo test --release --test live_round_trip going_on -- --nocapture
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn going_on_on_real_discord() {
|
||||
if std::env::var("JARVIS_LIVE_GOING_ON").as_deref() != Ok("1") {
|
||||
eprintln!("skipped: set JARVIS_LIVE_GOING_ON=1");
|
||||
return;
|
||||
}
|
||||
let dir = PathBuf::from(env("JARVIS_LIVE_PIECES"));
|
||||
let seqs: Value = serde_json::from_str(&std::fs::read_to_string(dir.join("pieces.json")).unwrap()).unwrap();
|
||||
let live = start_live(|speaker| json!({"designated": [speaker.to_string()], "designatedOnly": true, "mode": "addressed"})).await;
|
||||
let mut rows = vec![];
|
||||
let steps = futures_util::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(async {
|
||||
for s in seqs.as_array().unwrap() {
|
||||
let wav = std::fs::read(dir.join(s["file"].as_str().unwrap())).unwrap();
|
||||
until("Jarvis to finish speaking", 60_000, || !live.core.speaking()).await;
|
||||
let before = live.events.lock().unwrap().len();
|
||||
live.call.lock().await.play_only_input(Input::from(wav.clone()));
|
||||
tokio::time::sleep(Duration::from_secs_f64(speech_end_seconds(&wav))).await;
|
||||
// Done when nothing is playing and nothing new came for 10 s (at most 60 s).
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
let (mut seen, mut quiet_since) = (0, Instant::now());
|
||||
while Instant::now() < deadline {
|
||||
let n = live.events.lock().unwrap().len();
|
||||
if n != seen || live.core.speaking() {
|
||||
(seen, quiet_since) = (n, Instant::now());
|
||||
} else if quiet_since.elapsed() > Duration::from_secs(10) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
}
|
||||
let ev = live.events.lock().unwrap()[before..].to_vec();
|
||||
let heard: Vec<String> = ev.iter().filter_map(|(_, e)| match e {
|
||||
CoreEvent::Final(f) if f.heard.speaker_id == live.speaker_id => Some(f.text.clone()),
|
||||
_ => None,
|
||||
}).collect();
|
||||
let answers: Vec<Value> = ev.iter().filter_map(|(_, e)| match e {
|
||||
CoreEvent::ReplyText { id, text, failed } => {
|
||||
let end = ev.iter().find_map(|(_, e)| match e {
|
||||
CoreEvent::SpeakEnd(x) if &x.id == id => Some(x.clone()),
|
||||
_ => None,
|
||||
});
|
||||
Some(json!({"text": text, "failed": failed, "played": end.as_ref().map(|x| x.played),
|
||||
"cancelled": end.as_ref().map(|x| x.cancelled)}))
|
||||
}
|
||||
_ => None,
|
||||
}).collect();
|
||||
let asked = ev.iter().filter(|(_, e)| matches!(e, CoreEvent::AnswerAsked { .. })).count();
|
||||
rows.push(json!({"name": s["name"], "heard": heard, "asked": asked, "answers": answers}));
|
||||
println!("going on {}", rows.last().unwrap());
|
||||
tokio::time::sleep(Duration::from_millis(1500)).await;
|
||||
}
|
||||
})).await;
|
||||
live.stop().await;
|
||||
if let Err(panic) = steps {
|
||||
std::panic::resume_unwind(panic);
|
||||
}
|
||||
// One thing said in pieces: one answer heard to its end, and no other answer heard.
|
||||
for r in &rows {
|
||||
let heard = |a: &&Value| a["played"].as_u64().is_some_and(|p| p > 0);
|
||||
let whole: Vec<&Value> = r["answers"].as_array().unwrap().iter().filter(heard)
|
||||
.filter(|a| a["cancelled"] == json!(false)).collect();
|
||||
let cut: Vec<&Value> = r["answers"].as_array().unwrap().iter().filter(heard)
|
||||
.filter(|a| a["cancelled"] == json!(true)).collect();
|
||||
assert!(whole.len() == 1 && cut.is_empty(), "{}: not one answer: {r}", r["name"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -96,3 +96,13 @@
|
||||
- 빈 결과의 원인은 확신도 기준(-0.7). -0.85/-1.0으로 낮추면 헤드셋 7.5%, 잡음 10dB 15.5%, 5dB 30.2%, 빈 결과 원본 17→15/10개. 대신 잡음 108개(VAD 없이 바로 넣음)에서 글자가 나온 것이 16→27/32개. 실제 워커는 VAD가 먼저 거르므로(M1: 108개 중 5개만 모델까지 감) 기준 변경은 VAD를 포함한 잡음 시험으로 다시 재고 사용자가 정할 것. 이번에는 바꾸지 않음.
|
||||
- 작은 목소리+마이크 잡음(약 SNR 5dB)은 어떤 설정으로도 50% 안팎이라, 소리 앞단의 잡음 제거(모델) 같은 다른 방향이 필요함. 아직 미검증.
|
||||
- 근거: groups/javis_bot/evidence/2026-11-19/stt-plan/harsh/ (build.py 조건 정의, harsh.py, gate.py, 결과 JSON).
|
||||
- 2026-11-19 밤 (0.1.50): 악조건 두 갈래를 같은 자료(녹음 100개 × 7조건, 정답 16개)로 비교. 근거: evidence/2026-11-19/stt-plan/harsh2/.
|
||||
- 앞단 잡음 제거 3종(DeepFilterNet3, RNNoise, noisereduce)은 전부 나빠서 넣지 않음. 원본 7.0% → 13.8/9.6/11.0%, 싼 헤드셋 13.8% → 21.8/11.4/19.5%, 잡음 10dB 18.9% → 44.9/48.3/31.6%. DeepFilterNet은 작은 목소리에서 없는 말을 길게 지어냈고(108.6%), VAD를 지난 잡음 5개를 모두 글자로 만듦. 디스코드가 이미 보내는 쪽에서 잡음 제거(Krisp)를 하고, Whisper는 잡음 섞인 소리로 학습되어 제거 흔적이 더 해로움.
|
||||
- 확신도 기준: 실제 워커처럼 VAD와 분할기로 자른 잡음만 넣으면 모델까지 가는 것은 108개 중 5개(웃음). 기준을 -0.8로만 낮춰도 그중 1개가 "감사합니다."가 되고, VAD 없이 넣은 108개도 16→20개. 그래서 기준 자체는 -0.7 그대로.
|
||||
- 대신 살리기: 문맥 없는 결과가 -0.7에 조금 못 미쳐도(-0.8 이상) 문맥을 준 결과가 기준을 넘고 가까우면 그것을 씀. 실제 코드로 다시 잼(verify.py): 원본 7.0%, 헤드셋 13.8→7.5%, 빈 결과 대부분 1~2개 줄어듦, 잡음 0/5와 16/108 그대로, 최종 전사 평균 178~180ms(p95 246~254ms), 10명 한 묶음 1.1초.
|
||||
- 남은 문제(수치 그대로): 작은 목소리+마이크 잡음 51.4%(빈 결과 48/100), 잡음 5dB 33.9%(34/100), 잡음 10dB 18.9%(23/100). 이번에 본 방법(모델 7종, 문맥, 기준, 잡음 제거 3종)으로는 나아지지 않음. 다음 후보는 이런 조건의 실제 녹음으로 미세조정한 모델이나, 보내는 사람 쪽 디스코드 설정(입력 감도, 잡음 제거) 안내.
|
||||
- 2026-11-19 밤 (0.1.50 뒤): 근거 evidence/2026-11-19/stt-plan/wake/.
|
||||
- 첫마디 호출어: 힌트를 준 결과는 "비서야"를 맞게 들었는데(기사야·기서야·라비스·아비스 → 비서야·자비스), 힌트 결과는 힌트 없는 결과와 호출어 수가 같아야만 써서 버려졌음. 규칙을 바꿈: 힌트 없는 결과에 그 호출어의 비슷한 말이 있으면(글 전체가 호출어 글자 수의 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
|
||||
169
src/jarvis/tools/builtin/calculator.py
Normal file
169
src/jarvis/tools/builtin/calculator.py
Normal file
@@ -0,0 +1,169 @@
|
||||
"""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. Numbers are exact fractions as
|
||||
written (1.1 is 11/10), so + - * / // % and whole-number powers have no binary rounding; only the
|
||||
math functions and fractional powers work in floats.
|
||||
"""
|
||||
|
||||
import ast
|
||||
import math
|
||||
import operator
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from fractions import Fraction
|
||||
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 exact power worked out (about 3000 digits); bigger ones are refused.
|
||||
_MAX_POWER_BITS = 10_000
|
||||
# Largest power of ten a written number may carry (1e4000); bigger ones are refused unparsed.
|
||||
_MAX_LITERAL_EXPONENT = 4000
|
||||
|
||||
_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, Fraction)) and isinstance(exponent, (int, Fraction)) and exponent == int(exponent):
|
||||
base, exponent = Fraction(base), int(exponent)
|
||||
size = max(abs(base.numerator).bit_length(), base.denominator.bit_length())
|
||||
if size > 1 and size * abs(exponent) > _MAX_POWER_BITS:
|
||||
raise _Refused("the result has too many digits")
|
||||
return base ** exponent
|
||||
result = float(base) ** float(exponent)
|
||||
if isinstance(result, complex):
|
||||
raise _Refused("the result is not a real number")
|
||||
return result
|
||||
|
||||
|
||||
def _number(node, text):
|
||||
if type(node.value) is int:
|
||||
return Fraction(node.value)
|
||||
# A float as written in the expression, not the float ast already rounded it to: 1.1 is 11/10,
|
||||
# 1.0000000000000001 stays above 1, and 1e-400 is not 0.
|
||||
try:
|
||||
written = Decimal(ast.get_source_segment(text, node) or "")
|
||||
except InvalidOperation:
|
||||
return Fraction(repr(node.value))
|
||||
if not written.is_finite() or abs(written.adjusted()) > _MAX_LITERAL_EXPONENT:
|
||||
raise _Refused("a number has too many digits")
|
||||
return Fraction(written)
|
||||
|
||||
|
||||
def _eval(node, text):
|
||||
if isinstance(node, ast.Constant) and type(node.value) in (int, float):
|
||||
return _number(node, text)
|
||||
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Pow):
|
||||
return _power(_eval(node.left, text), _eval(node.right, text))
|
||||
if isinstance(node, ast.BinOp) and type(node.op) in _BINARY:
|
||||
return _BINARY[type(node.op)](_eval(node.left, text), _eval(node.right, text))
|
||||
if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY:
|
||||
return _UNARY[type(node.op)](_eval(node.operand, text))
|
||||
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, text) for a in node.args])
|
||||
raise _Refused("only numbers, + - * / ^ %, parentheses, "
|
||||
+ ", ".join([*_FUNCTIONS, *_CONSTANTS]) + " are allowed")
|
||||
|
||||
|
||||
def _readable(value) -> str:
|
||||
if isinstance(value, (int, Fraction)) and value == int(value):
|
||||
try:
|
||||
return str(int(value))
|
||||
except ValueError: # more digits than Python turns into text
|
||||
raise _Refused("the result has too many digits")
|
||||
value = float(value)
|
||||
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, text))
|
||||
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}")
|
||||
48
src/jarvis/tools/builtin/calculator.spec.md
Normal file
48
src/jarvis/tools/builtin/calculator.spec.md
Normal file
@@ -0,0 +1,48 @@
|
||||
# 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. An exact power whose result would be over about 10,000
|
||||
bits (about 3000 digits, also tiny ones such as `2^-100000`) 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.
|
||||
- **Exact as written.** Numbers are exact fractions as written (`1.1` is 11/10, not the nearest
|
||||
binary float), so `+ - * / // %` and whole-number powers have no rounding error: `ceil(1.1*100)`
|
||||
is 110 and `floor(0.3/0.1)` is 3. Only the math functions, `pi`, `e` and fractional powers work
|
||||
in floats.
|
||||
A number is read from its written text, so decimals longer than 17 digits and exponents beyond
|
||||
the float range stay as written too (`ceil(1.0000000000000001)` is 2, `1e-400/1e-400` is 1); a
|
||||
written number past 1e4000 (or below 1e-4000) is refused.
|
||||
- **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 values 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, decimals exact as written, 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(),
|
||||
|
||||
@@ -6,6 +6,7 @@ import glob
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unicodedata
|
||||
import zlib
|
||||
|
||||
import numpy as np
|
||||
@@ -19,9 +20,13 @@ SR = 16000
|
||||
# over it: every hallucination stayed below, real speech above except two short words in loud noise.
|
||||
# Whisper's no_speech_prob is not used: large-v3-turbo reports 0.0 for silence and noise alike.
|
||||
MIN_MEAN_LOGPROB = -0.7
|
||||
MAX_COMPRESSION_RATIO = 2.4
|
||||
MAX_COMPRESSION_RATIO = 2.4 # repetition loops ("A B A B A B ...") compress far better than speech
|
||||
# faster-whisper keeps at most this many previous-text tokens in a prompt (max_length // 2 - 1).
|
||||
MAX_PREVIOUS_TOKENS = 223 # repetition loops ("A B A B A B ...") compress far better than speech
|
||||
MAX_PREVIOUS_TOKENS = 223
|
||||
# A plain decode at or above this, though below MIN_MEAN_LOGPROB, may be rescued by the context
|
||||
# (choose_with_context). Measured 2026-11-19 on harsh copies of the user's speech: down to -0.8 no
|
||||
# more noise came out as text (VAD-cut noise 0/5, raw noise 16/108 as without); -0.9 let 3 more through.
|
||||
UNSURE_LOGPROB = -0.8
|
||||
|
||||
|
||||
def _letters(text: str) -> str:
|
||||
@@ -57,34 +62,72 @@ def _mentions(text: str, word: str) -> int:
|
||||
return _letters(text).count(w) if w else 0
|
||||
|
||||
|
||||
def _calls(text: str, hotwords: tuple[str, ...]) -> list[str]:
|
||||
"""The wake words in ``text``, longest first at each place, without overlaps ("김비서야" is one)."""
|
||||
s = _letters(text)
|
||||
words = sorted({_letters(w) for w in hotwords if _letters(w)}, key=len, reverse=True)
|
||||
found, i = [], 0
|
||||
while i < len(s):
|
||||
w = next((w for w in words if s.startswith(w, i)), None)
|
||||
if w:
|
||||
found.append(w)
|
||||
i += len(w)
|
||||
else:
|
||||
i += 1
|
||||
return found
|
||||
|
||||
|
||||
def keeps_wake_words(text: str, base: str, hotwords: tuple[str, ...]) -> bool:
|
||||
"""Whether ``text`` (a hinted or prompted decode) holds the wake words of ``base`` (the decode it is
|
||||
checked against): every hotword exactly as often, or one wake word more where ``base`` has a near
|
||||
miss of it. Near: the whole text is at most a third of that wake word's letters from ``base``,
|
||||
compared as Unicode NFKD letters (Hangul by its letters: "기사야" is two of six off "비서야")."""
|
||||
if all(_mentions(text, w) == _mentions(base, w) for w in hotwords):
|
||||
return True
|
||||
have, had = _calls(text, hotwords), _calls(base, hotwords)
|
||||
if len(have) != len(had) + 1 or any(_mentions(text, w) < _mentions(base, w) for w in hotwords):
|
||||
return False
|
||||
nfkd = lambda t: unicodedata.normalize("NFKD", _letters(t))
|
||||
return _edit_distance(nfkd(text), nfkd(base)) <= min(len(nfkd(w)) for w in have) // 3
|
||||
|
||||
|
||||
def choose_with_hint(hint_text: str, hint_lp: float, plain_text: str, plain_lp: float,
|
||||
hotwords: tuple[str, ...]) -> str:
|
||||
"""Pick between the decode that had the hotwords as a hint and the plain decode of the same audio.
|
||||
|
||||
The hint can make Whisper write a wake word that nobody said (on laughter, tacked onto a real
|
||||
sentence, or in place of a similar word), so the plain decode decides: no plain text means nothing
|
||||
was said, and the hint's text is used only when it stays close to the plain one and contains every
|
||||
hotword exactly as often. It may change other words, never how many wake words were heard.
|
||||
sentence, or in place of another word), so the plain decode decides: no plain text means nothing
|
||||
was said, and the hint's text is used only when it stays close to the plain one and keeps its wake
|
||||
words (``keeps_wake_words``): it may change other words, and turn a near miss of a wake word into it.
|
||||
"""
|
||||
if not keep_transcript(plain_text, plain_lp):
|
||||
return ""
|
||||
close = _edit_distance(_letters(hint_text), _letters(plain_text)) <= len(_letters(plain_text)) // 2
|
||||
if close and keep_transcript(hint_text, hint_lp) and all(
|
||||
_mentions(hint_text, w) == _mentions(plain_text, w) for w in hotwords):
|
||||
if close and keep_transcript(hint_text, hint_lp) and keeps_wake_words(hint_text, plain_text, hotwords):
|
||||
if len(_calls(hint_text, hotwords)) != len(_calls(plain_text, hotwords)):
|
||||
debug_log("hint turned a near miss into a wake word", "stt")
|
||||
return hint_text
|
||||
return plain_text
|
||||
|
||||
|
||||
def choose_with_context(heard: str, prompted: str, hotwords: tuple[str, ...]) -> str:
|
||||
def choose_with_context(heard: str, prompted: str, hotwords: tuple[str, ...],
|
||||
plain: tuple[str, float] | None = None) -> str:
|
||||
"""Pick between the decode without the conversation context (``heard``, already through the hint
|
||||
choice) and the one that had it as Whisper's previous-text prompt (``prompted``).
|
||||
choice) and the one that had it as Whisper's previous-text prompt (``prompted``, through the same
|
||||
choice, so it passed the gate itself).
|
||||
|
||||
The context fixes words of the topic the model misheard, but on noise or unsure audio it can write
|
||||
words of the prompt, so the decode without it decides, as for the hint: nothing heard stays
|
||||
nothing, and the prompted text is used only when it stays close to what was heard and holds every
|
||||
hotword exactly as often.
|
||||
words of the prompt, so the decode without it decides, as for the hint: the prompted text is used
|
||||
only when it stays close to what was heard and holds every hotword exactly as often. When nothing
|
||||
was heard, ``plain`` (the plain decode's text and mean log-probability) may still be just short of
|
||||
the gate (at least UNSURE_LOGPROB): then the prompted text is used if it is that close to it.
|
||||
"""
|
||||
if not heard or not prompted:
|
||||
if not heard:
|
||||
if not prompted or plain is None or plain[1] < UNSURE_LOGPROB \
|
||||
or compression_ratio(plain[0]) > MAX_COMPRESSION_RATIO:
|
||||
return ""
|
||||
return prompted if choose_with_context(plain[0], prompted, hotwords) == prompted else ""
|
||||
if not prompted:
|
||||
return heard
|
||||
h, p = _letters(heard), _letters(prompted)
|
||||
if _edit_distance(p, h) > len(h) // 2:
|
||||
@@ -130,13 +173,14 @@ class WhisperTranscriber:
|
||||
"""Clips arrive loudness-equalised by the session. ``contexts``: per clip, the recent
|
||||
conversation to prompt with ("" for none); see ``choose_with_context``."""
|
||||
enc, langs = self._encode(clips, opts)
|
||||
heard = self._choose(enc, langs, opts, None)
|
||||
plain = self._decode(enc, langs, opts.beam, None)
|
||||
heard = self._choose(enc, langs, opts, None, plain)
|
||||
prev = self._previous(langs, contexts)
|
||||
if prev is None:
|
||||
return heard
|
||||
prompted = self._choose(enc, langs, opts, prev)
|
||||
return [choose_with_context(h, p, opts.hotwords) if c else h
|
||||
for h, p, c in zip(heard, prompted, contexts)]
|
||||
prompted = self._choose(enc, langs, opts, prev, self._decode(enc, langs, opts.beam, None, prev))
|
||||
return [choose_with_context(h, p, opts.hotwords, pl) if c else h
|
||||
for h, p, pl, c in zip(heard, prompted, plain, contexts)]
|
||||
|
||||
def _previous(self, langs: list[str], contexts: list[str] | None) -> list[list[int]] | None:
|
||||
"""The contexts as previous-text tokens of one length for the whole batch: the decoder needs
|
||||
@@ -166,8 +210,8 @@ class WhisperTranscriber:
|
||||
langs = [r[0][0][2:-2] for r in m.model.detect_language(enc)]
|
||||
return enc, langs
|
||||
|
||||
def _choose(self, enc, langs: list[str], opts: DecodeOptions, prev: list[list[int]] | None) -> list[str]:
|
||||
plain = self._decode(enc, langs, opts.beam, None, prev)
|
||||
def _choose(self, enc, langs: list[str], opts: DecodeOptions, prev: list[list[int]] | None,
|
||||
plain: list[tuple[str, float]]) -> list[str]:
|
||||
if not opts.hotwords:
|
||||
return [text if keep_transcript(text, lp) else "" for text, lp in plain]
|
||||
hinted = self._decode(enc, langs, opts.beam, " ".join(opts.hotwords), prev)
|
||||
|
||||
@@ -145,11 +145,22 @@ text is empty:
|
||||
- Its compression ratio (UTF-8 bytes over zlib bytes) is at most 2.4, which catches repetition loops.
|
||||
- With hotwords: the clip is decoded once with them and once without, from the same encoder pass.
|
||||
The plain decode must pass the checks above, otherwise nothing was said. The hinted text is used
|
||||
only when it stays within half the plain text's letters of it and contains every hotword exactly
|
||||
as often as the plain one (ignoring case, spacing and punctuation, no fuzzy matching), so the hint
|
||||
can never add, drop or create a wake word: not from laughter, not after a real sentence, not from
|
||||
a one-letter wake word, and not by turning a similar word ("서비스", or the near miss "자비수")
|
||||
into it. Otherwise the plain text is used; matching near misses is left to call detection.
|
||||
only when it stays within half the plain text's letters of it and keeps the plain one's wake
|
||||
words (ignoring case, spacing and punctuation): every hotword exactly as often, or exactly one
|
||||
wake word more where the plain text has a near miss of it, that is when the whole hinted text is
|
||||
at most a third of that wake word's letters from the plain one, compared as Unicode NFKD letters
|
||||
(Hangul by its letters). So the hint never drops a wake word, and never adds one from laughter,
|
||||
after a real sentence, from a one-letter wake word or in place of a different word ("기구" heard
|
||||
for "디코" became "김비서" with the hint: five letters off). It does turn a near miss the plain
|
||||
decode wrote into the wake word the hinted decode heard: live 2026-11-19 "비서야" was decoded as
|
||||
"기사야" (two of six letters off, more than call detection allows), and the hinted decode of the
|
||||
same audio gave "비서야". Otherwise the plain text is used; other near misses are left to call
|
||||
detection. Measured on the user's 100 recordings and 108 noise clips (CPU int8, 2026-11-19): the
|
||||
hint added a wake word to 8 recordings and 15 noise clips; this rule takes 5 (all said: 자비스 or
|
||||
비서야 heard as 라비스, 아비스, 기사야, 기서야) and rejects the 3 others (two said, one "디코") and all
|
||||
15 noise clips. Of 15 synthetic sentences with words near the wake words, the hint added none
|
||||
where the word was heard as said (서비스, 기사, 이사야, 비상약, 미소야, 시사); two where the voice
|
||||
itself said "비사(야)" for "기사(야)" became "비서(야)".
|
||||
|
||||
`no_speech_prob` is not used: large-v3-turbo reports 0.0 for silence and noise alike.
|
||||
|
||||
@@ -171,6 +182,12 @@ decoded with the recent conversation as its previous-text prompt:
|
||||
was kept, it stays within half that text's letters of it, and it holds every hotword exactly as
|
||||
often; otherwise the text without context is used. On noise or unsure audio the prompt makes
|
||||
Whisper write words of the conversation; this rule keeps that out, as for the hint.
|
||||
- One rescue: when the decode without context was dropped by the gate but its mean log-probability
|
||||
is at least -0.8 (just short of -0.7), the prompted text (which passed the gate itself) is used if
|
||||
it is that close to it and keeps every hotword count. The unsure text itself is never used.
|
||||
Measured on harsh copies of the user's speech: a cheap headset 13.8% to 7.5% error, empty results
|
||||
fewer by 1-2 per 100 in most conditions, and no more noise with text (VAD-cut noise 0 of 5, noise
|
||||
decoded straight 16 of 108, as before); -0.9 let 3 more noise clips through.
|
||||
- Finals stay batched. The decoder needs the start token at the same position in every prompt of a
|
||||
batch, so each clip's context is cut from its end to the shortest one in the batch (a channel's
|
||||
clips share most of it); a clip without a context borrows another's and keeps its plain result.
|
||||
|
||||
102
tests/test_calculator_tool.py
Normal file
102
tests/test_calculator_tool.py
Normal file
@@ -0,0 +1,102 @@
|
||||
"""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
|
||||
@pytest.mark.parametrize("expression, expected", [
|
||||
("ceil(1.1*100)", "110"),
|
||||
("floor(0.3/0.1)", "3"),
|
||||
("0.1+0.2", "0.3"),
|
||||
("1.1*3 - 3.3", "0"),
|
||||
("10.5 % 0.1", "0"),
|
||||
("2.675*100 // 1", "267"),
|
||||
("0.5^-2", "4"),
|
||||
("ceil(1.0000000000000001)", "2"),
|
||||
("1e-400/1e-400", "1"),
|
||||
("1e400-1e400", "0"),
|
||||
])
|
||||
def test_decimals_are_exact_as_written(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", "1.5**100000", "2**-100000", "1e99999999", "1e-99999999*2"])
|
||||
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")
|
||||
@@ -56,16 +56,29 @@ def test_a_one_letter_wake_word_the_hint_adds_is_dropped():
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_hint_may_not_turn_a_similar_real_word_into_the_wake_word():
|
||||
assert choose_with_hint("자비스 신청해 줘", -0.1, "서비스 신청해 줘", -0.1, HINT) == "서비스 신청해 줘"
|
||||
def test_the_hint_may_not_turn_a_different_word_into_the_wake_word():
|
||||
# Live 2026-11-19: "디코 어디 갔어?" decoded as "기구 어디 갔어?", and with the hint as "김비서 어디 갔어?".
|
||||
secretary = ("비서", "비서야", "김비서")
|
||||
assert choose_with_hint("김비서 어디 갔어?", -0.49, "기구 어디 갔어?", -0.59, secretary) == "기구 어디 갔어?"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_near_miss_spelling_is_left_as_heard_rather_than_guessed():
|
||||
# "자비수" may be the wake word or another word; text alone cannot tell, so the plain decode stands
|
||||
# and fuzzy wake word matching is left to the call detection that reads it.
|
||||
plain = "자비수, 오늘 서울 날씨 어때?"
|
||||
assert choose_with_hint("자비스, 오늘 서울 날씨 어때?", -0.1, plain, -0.2, HINT) == plain
|
||||
def test_a_hinted_wake_word_replaces_a_near_miss_of_it():
|
||||
# Live 2026-11-19: "비서야 디코 화면공유 보여?" decoded as "기사야 ...", two letters off "비서야"
|
||||
# (more than call detection allows); decoded with the hint, the same audio gave "비서야".
|
||||
secretary = ("비서", "비서야", "김비서")
|
||||
hinted = "비서야 디코 화면군이 보여"
|
||||
assert choose_with_hint(hinted, -0.19, "기사야 디코 화면군이 보여.", -0.25, secretary) == hinted
|
||||
hinted = "자비스, 오늘 서울 날씨 어때?"
|
||||
assert choose_with_hint(hinted, -0.1, "자비수, 오늘 서울 날씨 어때?", -0.2, HINT) == hinted
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_near_miss_is_replaced_only_by_one_wake_word():
|
||||
assert choose_with_hint("자비스 자비스 날씨", -0.1, "자비수 자비수 날씨", -0.1, HINT) == "자비수 자비수 날씨"
|
||||
# Nor when the hint also changes much else: the budget is the whole text's difference.
|
||||
assert choose_with_hint("자비스 오늘 날씨 알려 줘", -0.1, "자비수 어제 날씨 알려 줘", -0.1, HINT) \
|
||||
== "자비수 어제 날씨 알려 줘"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@@ -132,3 +145,32 @@ def test_the_context_never_changes_how_many_wake_words_were_heard():
|
||||
@pytest.mark.unit
|
||||
def test_an_empty_prompted_decode_keeps_what_was_heard():
|
||||
assert choose_with_context("네.", "", HINT) == "네."
|
||||
|
||||
|
||||
# A plain decode just short of the gate (live 2026-11-19 on a headset copy: "니코 어디갔어" at -0.72 for
|
||||
# "디코 어디 갔어") is rescued by a confident prompted decode close to it; nothing else changes.
|
||||
from voice_worker.stt_whisper import UNSURE_LOGPROB # noqa: E402
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_nearly_sure_decode_is_rescued_by_a_confident_close_prompted_one():
|
||||
assert choose_with_context("", "디코 어디 갔어?", HINT, ("니코 어디갔어", MIN_MEAN_LOGPROB - 0.02)) \
|
||||
== "디코 어디 갔어?"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_an_unsure_decode_well_below_the_gate_is_not_rescued():
|
||||
assert choose_with_context("", "디코 어디 갔어?", HINT, ("니코 어디갔어", UNSURE_LOGPROB - 0.05)) == ""
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_noise_with_a_prompt_far_from_it_is_not_rescued():
|
||||
# The prompted decode wrote words of the conversation over laughter.
|
||||
assert choose_with_context("", "화면에 디스코드", HINT, ("감사합니다.", MIN_MEAN_LOGPROB - 0.05)) == ""
|
||||
assert choose_with_context("", "", HINT, ("감사합니다.", MIN_MEAN_LOGPROB - 0.05)) == ""
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_rescue_never_adds_a_wake_word():
|
||||
assert choose_with_context("", "자비스 지금 영상 재생되고 있어?", HINT,
|
||||
("라비스 지금 영상 재생되고 있어", MIN_MEAN_LOGPROB - 0.05)) == ""
|
||||
|
||||
Reference in New Issue
Block a user