diff --git a/CLAUDE.md b/CLAUDE.md index 2eac470..c6bcf6d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -31,6 +31,7 @@ Any code change must either adhere to our spec files perfectly or you should ask | `src/jarvis/memory/summariser.spec.md` | Diary summariser prompt contract, hygiene rules (deflection, attribution, topic separation), post-process scrub, and bulk-sweep clean button | Two-layer defence: prompt + deterministic scrub; corrupted summaries poison every downstream consumer | | `src/jarvis/memory/recall_gate.spec.md` | Deterministic skip-enrichment heuristic when the hot window covers a follow-up | Fail-open; language-agnostic via `\w{3,}` + `re.UNICODE`; planner intent always wins | | `src/voice_worker/voice_worker.spec.md` | v2 voice worker: multi-speaker streaming STT (shared Whisper, batched) and sentence TTS over a local WebSocket | Loopback only with an app token; no transcript text in logs; finals before partials; language-agnostic | +| `app/src/conversation.spec.md` | v2 call detection and response policies in the Rust app: wake words with near matches, call modes, designated people, voice stop, the four response policies with settling, interruption and missed requests | Pure types tested with fake times; language-agnostic matching on normalised letters; nothing dropped silently | | `app/src/discord_core.spec.md` | v2 Discord voice core in the Rust app: join/leave, per-speaker receive (own reorder window and Opus decoding after songbird decrypts) to the voice worker, sentence playback and stop, slash command, registered chat channels (read/send), voice worker process | Hears only the channel it is in and reads only registered channels; join notice on every join; chat is data and sent text never pings; no transcript or chat text in logs | The LLM contexts graph at `docs/llm_contexts.md` maps every LLM call in the app (model, gating, inputs, outputs, limits, flow). Keep it up-to-date at all times: any change that adds, removes, or alters an LLM context (model resolution, timeout, cap, prompt source, gating flag, data-flow edge) must update `docs/llm_contexts.md` in the same PR. diff --git a/app/Cargo.lock b/app/Cargo.lock index b1439c7..fa4fd92 100644 --- a/app/Cargo.lock +++ b/app/Cargo.lock @@ -1457,6 +1457,7 @@ dependencies = [ "symphonia", "tokio", "tokio-tungstenite 0.26.2", + "unicode-normalization", ] [[package]] @@ -3922,6 +3923,15 @@ version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-segmentation" version = "1.13.3" diff --git a/app/Cargo.toml b/app/Cargo.toml index 8b4264f..498231e 100644 --- a/app/Cargo.toml +++ b/app/Cargo.toml @@ -28,6 +28,7 @@ rand = "0.9" base64 = "0.22" async-trait = "0.1" opus2 = "0.4" +unicode-normalization = "0.1" [profile.release] lto = "thin" diff --git a/app/src/calls.rs b/app/src/calls.rs new file mode 100644 index 0000000..fdf7148 --- /dev/null +++ b/app/src/calls.rs @@ -0,0 +1,244 @@ +//! Call detection: does Jarvis answer this utterance? (`app/src/conversation.spec.md`). +//! +//! A pure function of the settings, the speaker and the text. Wake words and stop words are settings; +//! matching works on Unicode-normalised letters, so it behaves the same in any script. + +use std::collections::HashSet; + +use unicode_normalization::UnicodeNormalization; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CallMode { + /// Answer only when called by a wake word (default). + WakeWord, + /// Also answer what the brain judges to be said to Jarvis. + Addressed, + /// Answer every utterance. + Everything, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct CallSettings { + pub wake_words: Vec, + /// Share of a wake word's normalised letters a heard word may differ by (0-0.5). + pub similarity: f64, + pub mode: CallMode, + pub designated: HashSet, + pub designated_only: bool, + pub designated_no_wake_word: bool, + pub stop_words: Vec, +} + +impl Default for CallSettings { + fn default() -> Self { + Self { + wake_words: vec!["자비스".into()], + similarity: 0.2, + mode: CallMode::WakeWord, + designated: HashSet::new(), + designated_only: false, + designated_no_wake_word: false, + stop_words: ["멈춰", "그만", "정지", "stop"].map(String::from).to_vec(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Call { + Ignore, + /// Answer it. `direct`: called by a wake word. + Request { direct: bool }, + /// Ask the brain whether it was said to Jarvis (`call.mode` `addressed`). + Ask, + /// Stop the current answer and drop the waiting requests. + Stop, +} + +/// Most letters after a stop word that still count as the stop ("멈춰 줘", "그만해"). +const STOP_TAIL: usize = 3; + +/// NFKD, lower case, letters and digits only. +pub fn normalise(text: &str) -> Vec { + text.nfkd().flat_map(char::to_lowercase).filter(|c| c.is_alphanumeric()).collect() +} + +/// The stretch `[start, end)` of `text` closest to `word`, if within `max_edits` edits +/// (approximate substring matching: the match may start and end anywhere in `text`). +fn find(text: &[char], word: &[char], max_edits: usize) -> Option<(usize, usize)> { + if word.is_empty() || text.is_empty() { + return None; + } + let (n, m) = (text.len(), word.len()); + // d[i][j]: fewest edits turning word[..i] into a stretch of text ending at j; start[i][j] where it began. + let mut d = vec![vec![0usize; n + 1]; m + 1]; + let mut start = vec![vec![0usize; n + 1]; m + 1]; + for j in 0..=n { + start[0][j] = j; + } + for i in 1..=m { + d[i][0] = i; + start[i][0] = 0; + for j in 1..=n { + let sub = d[i - 1][j - 1] + usize::from(word[i - 1] != text[j - 1]); + let del = d[i - 1][j] + 1; // word letter missing from text + let ins = d[i][j - 1] + 1; // extra letter in text + let (best, from) = if sub <= del && sub <= ins { + (sub, start[i - 1][j - 1]) + } else if del <= ins { + (del, start[i - 1][j]) + } else { + (ins, start[i][j - 1]) + }; + d[i][j] = best; + start[i][j] = from; + } + } + (1..=n) + .filter(|&j| d[m][j] <= max_edits) + .min_by_key(|&j| (d[m][j], j)) + .map(|j| (start[m][j], j)) +} + +impl CallSettings { + fn allowed_edits(&self, word: &[char]) -> usize { + (self.similarity.clamp(0.0, 0.5) * word.len() as f64 + 1e-9).floor() as usize + } + + /// The text with the first heard wake word removed, if one is heard. + fn without_wake_word(&self, text: &[char]) -> Option> { + // The earliest heard wake word is the one used to address Jarvis. + let (s, e) = self + .wake_words + .iter() + .map(|w| normalise(w)) + .filter_map(|word| find(text, &word, self.allowed_edits(&word))) + .min()?; + Some(text[..s].iter().chain(&text[e..]).copied().collect()) + } + + fn is_stop(&self, rest: &[char]) -> bool { + self.stop_words.iter().map(|w| normalise(w)).any(|w| { + !w.is_empty() && rest.starts_with(&w) && rest.len() - w.len() <= STOP_TAIL + }) + } + + /// Decide what to do with one finished utterance. + pub fn judge(&self, speaker: u64, text: &str) -> Call { + let norm = normalise(text); + if norm.is_empty() { + return Call::Ignore; + } + let designated = self.designated.contains(&speaker); + if self.designated_only && !designated { + return Call::Ignore; + } + if let Some(rest) = self.without_wake_word(&norm) { + if self.is_stop(&rest) { + return Call::Stop; + } + return Call::Request { direct: true }; + } + if self.designated_no_wake_word && designated { + return Call::Request { direct: false }; + } + match self.mode { + CallMode::Everything => Call::Request { direct: false }, + CallMode::Addressed => Call::Ask, + CallMode::WakeWord => Call::Ignore, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const A: u64 = 1; + const B: u64 = 2; + + fn s() -> CallSettings { + CallSettings::default() + } + + #[test] + fn exact_and_near_wake_words_call_but_a_different_word_does_not() { + let c = s(); + assert_eq!(c.judge(A, "자비스, 오늘 날씨 어때?"), Call::Request { direct: true }); + assert_eq!(c.judge(A, "자비즈 날씨 알려 줘"), Call::Request { direct: true }); + assert_eq!(c.judge(A, "오늘 날씨 어때 자비스"), Call::Request { direct: true }); + assert_eq!(c.judge(A, "서비스 센터 몇 시에 열어?"), Call::Ignore); + assert_eq!(c.judge(A, "오늘 날씨 어때?"), Call::Ignore); + } + + #[test] + fn latin_wake_words_ignore_case_spacing_and_accents() { + let c = CallSettings { wake_words: vec!["Jarvis".into()], ..s() }; + assert_eq!(c.judge(A, "hey JARVIS, what's up"), Call::Request { direct: true }); + assert_eq!(c.judge(A, "Jervis, lights on"), Call::Request { direct: true }); + assert_eq!(c.judge(A, "Jär vis?"), Call::Request { direct: true }); + assert_eq!(c.judge(A, "the service is down"), Call::Ignore); + } + + #[test] + fn similarity_zero_needs_the_exact_word() { + let c = CallSettings { similarity: 0.0, ..s() }; + assert_eq!(c.judge(A, "자비즈 날씨"), Call::Ignore); + assert_eq!(c.judge(A, "자비스 날씨"), Call::Request { direct: true }); + } + + #[test] + fn stop_needs_the_wake_word_and_little_else() { + let c = s(); + assert_eq!(c.judge(A, "자비스, 멈춰!"), Call::Stop); + assert_eq!(c.judge(A, "자비스 그만해"), Call::Stop); + assert_eq!(c.judge(A, "자비스 멈춰 줘"), Call::Stop); + assert_eq!(c.judge(A, "멈춰"), Call::Ignore); + assert_eq!(c.judge(A, "자비스 그만 얘기하고 날씨 알려 줘"), Call::Request { direct: true }); + } + + #[test] + fn empty_and_punctuation_only_text_is_ignored() { + let c = CallSettings { mode: CallMode::Everything, ..s() }; + assert_eq!(c.judge(A, ""), Call::Ignore); + assert_eq!(c.judge(A, " ... ?! "), Call::Ignore); + } + + #[test] + fn modes_decide_utterances_without_a_wake_word() { + let every = CallSettings { mode: CallMode::Everything, ..s() }; + assert_eq!(every.judge(A, "날씨 어때"), Call::Request { direct: false }); + let addressed = CallSettings { mode: CallMode::Addressed, ..s() }; + assert_eq!(addressed.judge(A, "날씨 어때"), Call::Ask); + assert_eq!(addressed.judge(A, "자비스 날씨 어때"), Call::Request { direct: true }); + } + + #[test] + fn designated_switches_combine_as_the_design_table_says() { + let base = CallSettings { designated: [A].into(), ..s() }; + // only on, no-wake off: designated people answered only when called. + let c = CallSettings { designated_only: true, ..base.clone() }; + assert_eq!(c.judge(A, "자비스 날씨"), Call::Request { direct: true }); + assert_eq!(c.judge(A, "날씨"), Call::Ignore); + assert_eq!(c.judge(B, "자비스 날씨"), Call::Ignore); + assert_eq!(c.judge(B, "자비스 멈춰"), Call::Ignore); + // only on, no-wake on: designated people only, without a wake word. + let c = CallSettings { designated_only: true, designated_no_wake_word: true, ..base.clone() }; + assert_eq!(c.judge(A, "날씨"), Call::Request { direct: false }); + assert_eq!(c.judge(B, "자비스 날씨"), Call::Ignore); + // only off, no-wake on: anyone by wake word, designated people without. + let c = CallSettings { designated_no_wake_word: true, ..base.clone() }; + assert_eq!(c.judge(A, "날씨"), Call::Request { direct: false }); + assert_eq!(c.judge(B, "날씨"), Call::Ignore); + assert_eq!(c.judge(B, "자비스 날씨"), Call::Request { direct: true }); + // both off (default): anyone, by wake word only. + assert_eq!(base.judge(A, "날씨"), Call::Ignore); + assert_eq!(base.judge(B, "자비스 날씨"), Call::Request { direct: true }); + } + + #[test] + fn several_wake_words_all_count() { + let c = CallSettings { wake_words: vec!["자비스".into(), "javis".into()], ..s() }; + assert_eq!(c.judge(A, "javis 날씨"), Call::Request { direct: true }); + assert_eq!(c.judge(A, "javis stop"), Call::Stop); + } +} diff --git a/app/src/conversation.spec.md b/app/src/conversation.spec.md new file mode 100644 index 0000000..ac8a809 --- /dev/null +++ b/app/src/conversation.spec.md @@ -0,0 +1,109 @@ +# Conversation spec: call detection and response policies (v2 M4) + +The part of the app that decides which finished utterances (and, later, chat messages) Jarvis answers +and in what order, and when an answer that is being spoken stops. It sits between the Discord voice +core (`discord_core.spec.md`), which reports what was heard and plays speech, and the voice worker's +brain (`src/voice_worker/voice_worker.spec.md`, `reply`), which writes the answer. The user-facing +design is `docs/v2/conversation.md`; this spec is the contract the code follows. + +## Principles + +- **Plain types, tested without Discord.** Call detection (`app/src/calls.rs`) is a pure function of + the settings, the speaker and the text. The response policy (`app/src/policy.rs`) is a state machine + driven by events with the time passed in, so every rule is tested with fake times. +- **Language-agnostic.** Nothing matches a language's words in code. Wake words and stop words are + settings; matching works on Unicode-normalised letters, so it behaves the same in any script. +- **No text in logs.** Logs carry speaker IDs, decisions, reasons, counts and timings, never what was + said. +- **Nothing is dropped silently.** Every request the policy does not answer, and every answer it stops, + is reported as missed with a reason (the dashboard's "놓친 요청" list, M5). + +## Call detection + +Settings (`settings.json`, section `call`; wake words stay in `voice.wakeWords`): + +| Key | Default | Meaning | +|---|---|---| +| `voice.wakeWords` | `["자비스"]` | Wake words for voice (also the STT hint). | +| `call.chatWakeWords` | `null` | Wake words for chat; `null` uses `voice.wakeWords`. | +| `call.similarity` | `0.2` | How far a heard word may be from a wake word, as a share of the wake word's normalised letters (0-0.5). `0` needs an exact match. | +| `call.mode` | `"wakeWord"` | `wakeWord`: answer only when called by a wake word. `addressed`: also answer what is judged to be said to Jarvis. `everything`: answer every utterance. | +| `call.designated` | `[]` | Discord user IDs of the designated people. | +| `call.designatedOnly` | `false` | Answer only designated people. | +| `call.designatedNoWakeWord` | `false` | Answer designated people without a wake word. | +| `call.stopWords` | `["멈춰", "그만", "정지", "stop"]` | Said together with a wake word, they stop Jarvis in any policy. | + +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 +away from "자비스" (of six) while "서비스" is two away. + +A wake word is heard when some stretch of the normalised text is at most +`floor(similarity × letters of the wake word)` edits (insert, delete, substitute) from it. With the +default 0.2, "자비스" (six letters) allows one edit. A wake word anywhere in the utterance counts. + +Decision for one utterance (`judge(speaker, text)`), in order: + +1. Empty text (after normalisation): ignore. +2. `designatedOnly` and the speaker is not designated: ignore. +3. A wake word is heard and the rest of the text, with that stretch removed, starts with a stop word + and has at most 3 more letters ("멈춰", "멈춰 줘", "그만해"): **stop**. +4. A wake word is heard: **request**, `direct` (called by name). +5. `designatedNoWakeWord` and the speaker is designated: **request**, not direct. +6. `call.mode` `everything`: **request**, not direct. `addressed`: **ask** (the brain judges whether it + was said to Jarvis; a yes becomes a request, not direct). `wakeWord`: ignore. + +The text sent to the brain is the utterance as heard; the brain treats the wake word as address. + +## Response policy + +Settings (section `response`): + +| Key | Default | Meaning | +|---|---|---| +| `response.policy` | `"first"` | `first` (처음 대화만), `inOrder` (들어온 순서대로), `latest` (마지막 대화만), `important` (제일 중요한 대화만). | +| `response.queueMax` | `5` | `inOrder`: most waiting requests; past it the oldest is dropped. 1-20. | +| `response.collectMs` | `700` | `important`: how long candidates are collected before choosing. 0-3000. | +| `response.settleMs` | `800` | Longest wait for an earlier-ended utterance that is still being transcribed. 0-3000. | +| `response.priorities` | `{}` | `important`: user ID → priority (higher first, default 0). | + +Terms: + +- A **request** has an id, the speaker, the text, whether it was `direct`, and `ended_at`: when the + utterance ended (the final's arrival minus its `wait_ms`). +- An **answer** runs from the moment the policy starts it until it is done (its speech ended, failed or + was stopped). There is at most one answer at a time: Jarvis has one voice. +- An utterance is **open** from its `speech_start` until its final. An open utterance whose speaker + has stopped speaking (`speaking_end` sent) is **ending**: its final may still turn out to be a call. + +Rules shared by every policy: + +- **Ordering by end time.** Requests are compared by `ended_at`, not by when their final arrived, so a + long utterance is not pushed back by its transcription time. +- **Settling.** When a request could start now but some other utterance is ending and stopped earlier + than the request's `ended_at` (in `important`: any ending utterance, since it competes on score), the + policy waits for that final, at most `settleMs` from the first waiting request's arrival. A final that + is not a call ends the wait for it. `latest` does not settle: an earlier utterance would lose anyway. +- **Stop.** A stop decision stops the current answer and drops every waiting request, in every policy. + The stopped answer and the dropped requests are missed (`stopped`). +- An answer that is already done is never started again. + +Per policy: + +| Policy | No answer running | A new request while an answer runs | +|---|---|---| +| `first` | Answer the request that ended first (after settling). | Missed (`busy`). | +| `inOrder` | Answer the earliest-ended waiting request. | Queued by `ended_at`. Past `queueMax`, the earliest-ended waiting one is missed (`queue_full`). | +| `latest` | Answer the latest-ended waiting request; the others are missed (`replaced`). | The current answer stops (missed, `interrupted`) and the new request is answered. A request that ended before the current one is missed (`replaced`). | +| `important` | Collect for `collectMs` from the first request, then answer the best; the other candidates are missed (`lower_score`). | Kept as a candidate. If it beats the current answer, the current answer stops (missed, `interrupted`) and the best candidate is answered at once; otherwise, when the current answer ends, the best of the candidates collected meanwhile is answered and the rest are missed (`lower_score`). | + +`important` ranks by (1) priority, (2) `direct`, then (3) the brain's importance ranking, asked for only +when two or more candidates tie on (1) and (2). While the ranking is pending nothing new starts; if it +does not come within 1.5 s, or fails, the earliest-ended of the tied candidates wins. A candidate +beats the running answer only on (1) or (2); the ranking is not asked for an interruption. + +## Tests + +`cargo test` covers call detection (exact and near wake words in Hangul and Latin, a different word +two letters away, wake word anywhere, stop with and without a wake word, designated combinations, +modes) and every policy rule above with fake times (settling, ordering by end time, busy, queue limit, +interruption, ranking tie, ranking timeout, stop dropping the queue). diff --git a/app/src/discord_core.spec.md b/app/src/discord_core.spec.md index c7d530e..a5e86aa 100644 --- a/app/src/discord_core.spec.md +++ b/app/src/discord_core.spec.md @@ -65,13 +65,16 @@ strings (numbers would lose precision). | `voice.maxSpeakers` | `10` | Most people transcribed at once, 1-10. | | `voice.listenToBots` | `false` | Also transcribe other bots (music bots are ignored by default). | | `voice.joinNotice` | "자비스가 이 음성 채널에 들어왔습니다. 이 채널의 대화는 자비스가 받아 적습니다." | Posted in the voice channel's chat on every join. Must not be empty. | -| `voice.wakeWords` | `["자비스"]` | Sent to the worker as STT `hotwords`. | +| `voice.wakeWords` | `["자비스"]` | Sent to the worker as STT `hotwords`, and the voice wake words of call detection. | | `voice.stt` | `{}` | Other worker STT settings (`partials`, `end_silence_ms`, `final_beam`, `language`, ...); the worker validates them. | | `chatChannels` | `[]` | `{id, name, description, read (true), send (true), edit (true), react (true), delete (false), pin (false)}` per channel. | | `voiceWorker.python` | `python3` (`python.exe` on Windows) | Python of the worker venv. | | `voiceWorker.cwd` | the repo's `src/` (development builds) | Folder holding the `voice_worker` package. | | `voiceWorker.args` | `[]` | Extra worker arguments, e.g. `["--melo-python", ""]`. | +The `call` and `response` sections (call detection and response policies, M4) are in +`conversation.spec.md`. + ## Voice worker process The app starts `python -m voice_worker --host 127.0.0.1 --port ` in `voiceWorker.cwd` diff --git a/app/src/lib.rs b/app/src/lib.rs index da9f40d..d6b2d1a 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -1,10 +1,12 @@ //! Jarvis v2 app core (see `app/src/discord_core.spec.md`). pub mod log; +pub mod calls; pub mod chat; pub mod discord; pub mod frames; pub mod playback; +pub mod policy; pub mod receive; pub mod services; pub mod settings; diff --git a/app/src/policy.rs b/app/src/policy.rs new file mode 100644 index 0000000..6415a0d --- /dev/null +++ b/app/src/policy.rs @@ -0,0 +1,552 @@ +//! Response policy: which call Jarvis answers, in what order, and when an answer stops +//! (`app/src/conversation.spec.md`). +//! +//! A state machine driven by events with the time passed in. It never plays or asks anything itself: +//! every call returns the actions for the caller to carry out. + +use std::collections::{HashMap, HashSet}; +use std::time::{Duration, Instant}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PolicyKind { + /// 처음 대화만: new requests are dropped while an answer runs (default). + First, + /// 들어온 순서대로: answered one after another in end-time order. + InOrder, + /// 마지막 대화만: the newest request replaces everything else, even a running answer. + Latest, + /// 제일 중요한 대화만: candidates are collected and the best one is answered. + Important, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct PolicySettings { + pub kind: PolicyKind, + pub queue_max: usize, + pub collect: Duration, + pub settle: Duration, + pub priorities: HashMap, + /// How long the brain's importance ranking is waited for. + pub rank_timeout: Duration, +} + +impl Default for PolicySettings { + fn default() -> Self { + Self { + kind: PolicyKind::First, + queue_max: 5, + collect: Duration::from_millis(700), + settle: Duration::from_millis(800), + priorities: HashMap::new(), + rank_timeout: Duration::from_millis(1500), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Request { + pub id: u64, + pub speaker: u64, + pub text: String, + /// Called by a wake word. + pub direct: bool, + /// When the utterance ended. + pub ended_at: Instant, + /// When its final arrived. + pub arrived_at: Instant, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MissReason { + /// `first`: an answer was running or another caller finished first. + Busy, + /// `inOrder`: the queue was full. + QueueFull, + /// `latest`: a newer request took its place. + Replaced, + /// The answer was stopped for a newer or more important request. + Interrupted, + /// `important`: another candidate was chosen. + LowerScore, + /// A stop command. + Stopped, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Action { + /// Start answering this request. + Answer(Request), + /// Stop the running answer with this id (its speech and its reply). + StopAnswer(u64), + /// Not answered, or stopped: for the "놓친 요청" list. + Missed(Request, MissReason), + /// Ask the brain to rank these tied candidates by importance; answer with `ranked`. + Rank(Vec), +} + +#[derive(Debug, Default)] +struct Open { + /// When the speaker stopped sending audio, if they have. + stopped_at: Option, +} + +pub struct Policy { + s: PolicySettings, + current: Option, + waiting: Vec, + open: HashMap, + /// `important`: no choice before this. + collect_until: Option, + /// `important`: the tied candidates being ranked and when to give up waiting. + ranking: Option<(HashSet, Instant)>, +} + +impl Policy { + pub fn new(s: PolicySettings) -> Self { + Self { s, current: None, waiting: vec![], open: HashMap::new(), collect_until: None, ranking: None } + } + + pub fn settings(&self) -> &PolicySettings { + &self.s + } + + /// The id of the running answer. + pub fn current(&self) -> Option { + self.current.as_ref().map(|r| r.id) + } + + pub fn waiting(&self) -> usize { + self.waiting.len() + } + + /// An utterance started (`speech_start`). + pub fn utterance_open(&mut self, speaker: u64) { + self.open.insert(speaker, Open::default()); + } + + /// The speaker stopped sending audio; their final is still to come. + pub fn speaking_stopped(&mut self, speaker: u64, at: Instant) { + if let Some(o) = self.open.get_mut(&speaker) { + o.stopped_at.get_or_insert(at); + } + } + + /// The speaker's final arrived and was not a call (or the speaker left). + pub fn utterance_closed(&mut self, speaker: u64, now: Instant) -> Vec { + self.open.remove(&speaker); + self.choose(now, None) + } + + fn score(&self, r: &Request) -> (i64, bool) { + (self.s.priorities.get(&r.speaker).copied().unwrap_or(0), r.direct) + } + + /// The speaker's final was a call. + pub fn request(&mut self, req: Request, now: Instant) -> Vec { + self.open.remove(&req.speaker); + let mut out = vec![]; + if let Some(cur) = self.current.clone() { + match self.s.kind { + PolicyKind::First => out.push(Action::Missed(req, MissReason::Busy)), + PolicyKind::InOrder => self.enqueue(req, &mut out), + PolicyKind::Latest => { + if req.ended_at > cur.ended_at { + self.interrupt(&mut out); + for r in self.waiting.drain(..) { + out.push(Action::Missed(r, MissReason::Replaced)); + } + self.waiting.push(req); + } else { + out.push(Action::Missed(req, MissReason::Replaced)); + } + } + PolicyKind::Important => { + let beats = self.score(&req) > self.score(&cur); + self.waiting.push(req); + if beats { + self.interrupt(&mut out); + self.collect_until = None; + } + } + } + } else { + if self.s.kind == PolicyKind::Important && self.waiting.is_empty() && self.ranking.is_none() { + self.collect_until = Some(now + self.s.collect); + } + self.enqueue(req, &mut out); + } + out.extend(self.choose(now, None)); + out + } + + fn enqueue(&mut self, req: Request, out: &mut Vec) { + let at = self.waiting.partition_point(|r| r.ended_at <= req.ended_at); + self.waiting.insert(at, req); + if self.s.kind == PolicyKind::InOrder { + while self.waiting.len() > self.s.queue_max.max(1) { + out.push(Action::Missed(self.waiting.remove(0), MissReason::QueueFull)); + } + } + } + + fn interrupt(&mut self, out: &mut Vec) { + if let Some(cur) = self.current.take() { + out.push(Action::StopAnswer(cur.id)); + out.push(Action::Missed(cur, MissReason::Interrupted)); + } + } + + /// A stop command: stop the answer and drop everything waiting. + pub fn stop(&mut self) -> Vec { + let mut out = vec![]; + if let Some(cur) = self.current.take() { + out.push(Action::StopAnswer(cur.id)); + out.push(Action::Missed(cur, MissReason::Stopped)); + } + for r in self.waiting.drain(..) { + out.push(Action::Missed(r, MissReason::Stopped)); + } + self.collect_until = None; + self.ranking = None; + out + } + + /// The answer's speech ended, failed or was stopped. + pub fn answer_done(&mut self, id: u64, now: Instant) -> Vec { + if self.current.as_ref().map(|r| r.id) != Some(id) { + return vec![]; + } + self.current = None; + self.choose(now, None) + } + + /// The brain's ranking of the tied candidates, best first. + pub fn ranked(&mut self, order: &[u64], now: Instant) -> Vec { + let Some((tied, _)) = self.ranking.take() else { return vec![] }; + let winner = order.iter().copied().find(|id| tied.contains(id)); + self.choose(now, Some(winner)) + } + + /// Timers: settling, collecting and the ranking timeout. + pub fn tick(&mut self, now: Instant) -> Vec { + if let Some((_, deadline)) = &self.ranking { + if now >= *deadline { + self.ranking = None; + return self.choose(now, Some(None)); + } + } + self.choose(now, None) + } + + /// When `tick` should run next. + pub fn next_deadline(&self) -> Option { + if let Some((_, t)) = &self.ranking { + return Some(*t); + } + let mut d: Vec = vec![]; + if self.current.is_none() && !self.waiting.is_empty() { + if let Some(t) = self.collect_until { + d.push(t); + } + if let Some(first) = self.waiting.iter().map(|r| r.arrived_at).min() { + d.push(first + self.s.settle); + } + } + d.into_iter().min() + } + + /// Wait for an ending utterance that may still be a call that should come first. + fn blocked(&self, now: Instant) -> bool { + let ending: Vec = self.open.values().filter_map(|o| o.stopped_at).collect(); + if ending.is_empty() { + return false; + } + let Some(first_arrival) = self.waiting.iter().map(|r| r.arrived_at).min() else { return false }; + if now >= first_arrival + self.s.settle { + return false; + } + match self.s.kind { + PolicyKind::Latest => false, + PolicyKind::First | PolicyKind::InOrder => { + let head = self.waiting[0].ended_at; + ending.iter().any(|t| *t < head) + } + PolicyKind::Important => true, + } + } + + /// Start the next answer if the policy allows one now. `rank`: `Some(winner)` once a ranking + /// finished or gave up. + fn choose(&mut self, now: Instant, rank: Option>) -> Vec { + let mut out = vec![]; + if self.current.is_some() || self.waiting.is_empty() || (self.ranking.is_some() && rank.is_none()) { + return out; + } + if rank.is_none() { + if let Some(t) = self.collect_until { + if now < t { + return out; + } + } + if self.blocked(now) { + return out; + } + } + let winner = match self.s.kind { + PolicyKind::First | PolicyKind::InOrder => 0, + PolicyKind::Latest => self.waiting.len() - 1, + PolicyKind::Important => { + let best = self.waiting.iter().map(|r| self.score(r)).max().expect("not empty"); + let tied: Vec = (0..self.waiting.len()).filter(|&i| self.score(&self.waiting[i]) == best).collect(); + match rank { + Some(Some(id)) if tied.iter().any(|&i| self.waiting[i].id == id) => { + tied.into_iter().find(|&i| self.waiting[i].id == id).expect("present") + } + // A ranking that failed, timed out, or named nobody still tied: the earliest-ended. + Some(_) => tied[0], + None if tied.len() >= 2 => { + let cands: Vec = tied.iter().map(|&i| self.waiting[i].clone()).collect(); + self.ranking = Some((cands.iter().map(|r| r.id).collect(), now + self.s.rank_timeout)); + out.push(Action::Rank(cands)); + return out; + } + None => tied[0], + } + } + }; + let chosen = self.waiting.remove(winner); + let others = match self.s.kind { + PolicyKind::InOrder => vec![], + PolicyKind::First => std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::Busy)).collect(), + PolicyKind::Latest => std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::Replaced)).collect(), + PolicyKind::Important => { + std::mem::take(&mut self.waiting).into_iter().map(|r| (r, MissReason::LowerScore)).collect() + } + }; + for (r, why) in others { + out.push(Action::Missed(r, why)); + } + self.collect_until = None; + self.current = Some(chosen.clone()); + out.push(Action::Answer(chosen)); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const A: u64 = 1; + const B: u64 = 2; + const C: u64 = 3; + + struct T { + p: Policy, + t0: Instant, + next_id: u64, + } + + impl T { + fn new(kind: PolicyKind) -> Self { + Self::with(PolicySettings { kind, ..PolicySettings::default() }) + } + fn with(s: PolicySettings) -> Self { + Self { p: Policy::new(s), t0: Instant::now(), next_id: 0 } + } + fn at(&self, ms: u64) -> Instant { + self.t0 + Duration::from_millis(ms) + } + /// A call from `speaker` that ended at `ended` ms and arrived at `arrived` ms. + fn call(&mut self, speaker: u64, direct: bool, ended: u64, arrived: u64) -> (u64, Vec) { + self.next_id += 1; + let r = Request { id: self.next_id, speaker, text: String::new(), direct, ended_at: self.at(ended), + arrived_at: self.at(arrived) }; + let now = self.at(arrived); + (self.next_id, self.p.request(r, now)) + } + } + + fn answered(a: &[Action]) -> Vec { + a.iter().filter_map(|x| if let Action::Answer(r) = x { Some(r.id) } else { None }).collect() + } + fn missed(a: &[Action]) -> Vec<(u64, MissReason)> { + a.iter().filter_map(|x| if let Action::Missed(r, w) = x { Some((r.id, *w)) } else { None }).collect() + } + fn stopped(a: &[Action]) -> Vec { + a.iter().filter_map(|x| if let Action::StopAnswer(id) = x { Some(*id) } else { None }).collect() + } + + #[test] + fn first_answers_at_once_and_drops_what_comes_while_busy() { + let mut t = T::new(PolicyKind::First); + let (a, out) = t.call(A, true, 0, 200); + assert_eq!(answered(&out), vec![a]); + let (b, out) = t.call(B, true, 300, 500); + assert_eq!(missed(&out), vec![(b, MissReason::Busy)]); + assert!(t.p.answer_done(a, t.at(2000)).is_empty()); + let (c, out) = t.call(C, true, 2100, 2300); + assert_eq!(answered(&out), vec![c]); + } + + #[test] + fn first_waits_for_an_earlier_ended_utterance_and_answers_it_if_it_is_a_call() { + let mut t = T::new(PolicyKind::First); + // B stopped talking at 100 ms but is still being transcribed; A ended at 150 ms. + t.p.utterance_open(B); + t.p.speaking_stopped(B, t.at(100)); + let (a, out) = t.call(A, true, 150, 300); + assert!(answered(&out).is_empty(), "waits for B"); + let (b, out) = t.call(B, true, 100, 500); + assert_eq!(answered(&out), vec![b], "B finished speaking first"); + assert_eq!(missed(&out), vec![(a, MissReason::Busy)]); + } + + #[test] + fn settling_ends_when_the_earlier_utterance_is_not_a_call_or_takes_too_long() { + let mut t = T::new(PolicyKind::First); + t.p.utterance_open(B); + t.p.speaking_stopped(B, t.at(100)); + let (a, _) = t.call(A, true, 150, 300); + assert_eq!(answered(&t.p.utterance_closed(B, t.at(400))), vec![a]); + + let mut t = T::new(PolicyKind::First); + t.p.utterance_open(B); + t.p.speaking_stopped(B, t.at(100)); + let (a, _) = t.call(A, true, 150, 300); + assert_eq!(t.p.next_deadline(), Some(t.at(300 + 800))); + assert!(answered(&t.p.tick(t.at(1000))).is_empty()); + assert_eq!(answered(&t.p.tick(t.at(1100))), vec![a]); + } + + #[test] + fn an_utterance_still_being_spoken_or_ended_later_does_not_hold_up_the_answer() { + let mut t = T::new(PolicyKind::First); + t.p.utterance_open(B); // still talking + t.p.utterance_open(C); + t.p.speaking_stopped(C, t.at(400)); // ended after A + let (a, out) = t.call(A, true, 150, 300); + assert_eq!(answered(&out), vec![a]); + } + + #[test] + fn in_order_follows_end_times_not_arrival_and_drops_the_oldest_when_full() { + let mut t = T::with(PolicySettings { kind: PolicyKind::InOrder, queue_max: 2, ..PolicySettings::default() }); + let (a, out) = t.call(A, true, 0, 100); + assert_eq!(answered(&out), vec![a]); + let (c, _) = t.call(C, true, 900, 1000); // ended later, arrived first + let (b, _) = t.call(B, true, 600, 1500); // long utterance: ended earlier, arrived later + assert_eq!(answered(&t.p.answer_done(a, t.at(2000))), vec![b]); + assert_eq!(answered(&t.p.answer_done(b, t.at(3000))), vec![c]); + + let (_, out) = t.call(A, true, 3100, 3200); + assert!(answered(&out).is_empty()); + let (e, _) = t.call(B, true, 3300, 3400); + let (_f, out) = t.call(C, true, 3500, 3600); + assert_eq!(t.p.waiting(), 2); + assert_eq!(missed(&out).len(), 1, "third waiting request pushes the oldest out"); + assert_eq!(answered(&t.p.answer_done(c, t.at(4000))), vec![e]); + } + + #[test] + fn latest_interrupts_for_a_newer_request_and_drops_older_ones() { + let mut t = T::new(PolicyKind::Latest); + let (a, _) = t.call(A, true, 0, 100); + let (b, out) = t.call(B, true, 500, 700); + assert_eq!(stopped(&out), vec![a]); + assert_eq!(missed(&out), vec![(a, MissReason::Interrupted)]); + assert_eq!(answered(&out), vec![b]); + // A late final from before B's end is not newer. + let (c, out) = t.call(C, true, 400, 900); + assert_eq!(missed(&out), vec![(c, MissReason::Replaced)]); + assert!(stopped(&out).is_empty()); + // The stopped answer's late "done" changes nothing. + assert!(t.p.answer_done(a, t.at(1000)).is_empty()); + assert_eq!(t.p.current(), Some(b)); + } + + #[test] + fn latest_answers_the_newest_of_several_waiting() { + let mut t = T::new(PolicyKind::Latest); + t.p.utterance_open(C); + let (a, out) = t.call(A, true, 0, 100); + assert_eq!(answered(&out), vec![a], "latest never settles"); + let (b, _) = t.call(B, true, 200, 300); + assert_eq!(t.p.current(), Some(b)); + } + + #[test] + fn important_collects_then_answers_the_best_by_priority_then_wake_word() { + let mut s = PolicySettings { kind: PolicyKind::Important, ..PolicySettings::default() }; + s.priorities.insert(C, 5); + let mut t = T::with(s); + let (a, out) = t.call(A, true, 0, 100); + assert!(answered(&out).is_empty(), "collecting for 700 ms"); + let (b, _) = t.call(B, false, 100, 200); + let (c, _) = t.call(C, false, 200, 300); + assert_eq!(t.p.next_deadline(), Some(t.at(800))); + let out = t.p.tick(t.at(800)); + assert_eq!(answered(&out), vec![c], "priority wins over the wake word"); + let mut m = missed(&out); + m.sort_by_key(|(id, _)| *id); + assert_eq!(m, vec![(a, MissReason::LowerScore), (b, MissReason::LowerScore)]); + } + + #[test] + fn important_asks_for_a_ranking_only_on_a_tie_and_falls_back_on_timeout() { + let mut t = T::new(PolicyKind::Important); + let (a, _) = t.call(A, true, 0, 100); + let (b, _) = t.call(B, true, 50, 200); + let out = t.p.tick(t.at(800)); + let ranks: Vec> = out.iter().filter_map(|x| if let Action::Rank(c) = x { + Some(c.iter().map(|r| r.id).collect()) } else { None }).collect(); + assert_eq!(ranks, vec![vec![a, b]]); + assert!(answered(&out).is_empty()); + assert_eq!(answered(&t.p.ranked(&[b, a], t.at(900))), vec![b]); + + let mut t = T::new(PolicyKind::Important); + let (a, _) = t.call(A, true, 0, 100); + let (_b, _) = t.call(B, true, 50, 200); + t.p.tick(t.at(800)); + assert_eq!(t.p.next_deadline(), Some(t.at(800 + 1500))); + assert_eq!(answered(&t.p.tick(t.at(2300))), vec![a], "timeout: earliest-ended wins"); + assert!(t.p.ranked(&[2], t.at(2400)).is_empty(), "a late ranking is ignored"); + + // One candidate: no ranking, no extra delay beyond collecting. + let mut t = T::new(PolicyKind::Important); + let (a, _) = t.call(A, true, 0, 100); + assert_eq!(answered(&t.p.tick(t.at(800))), vec![a]); + } + + #[test] + fn important_interrupts_only_for_a_higher_score_and_otherwise_answers_after() { + let mut s = PolicySettings { kind: PolicyKind::Important, collect: Duration::ZERO, ..PolicySettings::default() }; + s.priorities.insert(C, 1); + let mut t = T::with(s); + let (a, out) = t.call(A, false, 0, 100); + assert_eq!(answered(&out), vec![a]); + let (b, out) = t.call(B, false, 200, 300); + assert!(stopped(&out).is_empty(), "same score: keep going"); + assert_eq!(answered(&t.p.answer_done(a, t.at(1000))), vec![b]); + let (c, out) = t.call(C, false, 1100, 1200); + assert_eq!(stopped(&out), vec![b]); + assert_eq!(missed(&out), vec![(b, MissReason::Interrupted)]); + assert_eq!(answered(&out), vec![c]); + } + + #[test] + fn stop_ends_the_answer_and_drops_the_queue_in_every_policy() { + for kind in [PolicyKind::First, PolicyKind::InOrder, PolicyKind::Latest, PolicyKind::Important] { + let mut t = T::with(PolicySettings { kind, collect: Duration::ZERO, ..PolicySettings::default() }); + let _ = t.call(A, true, 0, 100); + let _ = t.call(B, true, 50, 200); + let running = t.p.current().expect("an answer runs"); + let out = t.p.stop(); + assert_eq!(stopped(&out), vec![running], "{kind:?}"); + assert!(missed(&out).iter().any(|(id, _)| *id == running), "{kind:?}"); + assert!(missed(&out).iter().all(|(_, w)| *w == MissReason::Stopped), "{kind:?}"); + assert_eq!(t.p.current(), None); + assert_eq!(t.p.waiting(), 0); + } + } +} diff --git a/app/src/settings.rs b/app/src/settings.rs index afdbb13..18154fc 100644 --- a/app/src/settings.rs +++ b/app/src/settings.rs @@ -5,7 +5,12 @@ //! are ignored. use serde_json::{Map, Value}; +use std::collections::HashMap; use std::path::{Path, PathBuf}; +use std::time::Duration; + +use crate::calls::{CallMode, CallSettings}; +use crate::policy::{PolicyKind, PolicySettings}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct ChatChannelSettings { @@ -46,7 +51,7 @@ pub struct VoiceSettings { pub listen_to_bots: bool, /// Posted in the voice channel's chat on every join (privacy.md). pub join_notice: String, - /// Wake words; passed to the STT as a hint now, used for call detection from M4. + /// Wake words: the STT hint and the voice wake words of call detection (`conversation.spec.md`). pub wake_words: Vec, /// Voice worker STT settings (voice_worker.spec.md); the worker validates them. pub stt: Map, @@ -68,6 +73,11 @@ pub struct Settings { pub voice: VoiceSettings, pub chat_channels: Vec, pub voice_worker: WorkerSettings, + /// Call detection for voice (`conversation.spec.md`); its wake words are `voice.wakeWords`. + pub call: CallSettings, + /// Wake words for chat; `None` uses `voice.wakeWords`. + pub chat_wake_words: Option>, + pub response: PolicySettings, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -106,6 +116,9 @@ impl Default for Settings { cwd: Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("src"), args: vec![], }, + call: CallSettings::default(), + chat_wake_words: None, + response: PolicySettings::default(), } } } @@ -169,6 +182,107 @@ fn get_str_list(m: Option<&Map>, key: &str, path: &str, default: } } +fn get_ms(m: Option<&Map>, key: &str, path: &str, default: Duration, max: u64) + -> Result { + match m.and_then(|m| m.get(key)) { + None => Ok(default), + Some(v) => match v.as_u64() { + Some(n) if n <= max => Ok(Duration::from_millis(n)), + _ => err(format!("{path}.{key} must be an integer 0-{max} (milliseconds)")), + }, + } +} + +fn snowflake_list(m: Option<&Map>, key: &str, path: &str) -> Result, SettingsError> { + match m.and_then(|m| m.get(key)) { + None => Ok(vec![]), + Some(Value::Array(a)) => a + .iter() + .map(snowflake) + .collect::>>() + .ok_or_else(|| SettingsError(format!("{path}.{key} must be a list of Discord user IDs"))), + Some(_) => err(format!("{path}.{key} must be a list of Discord user IDs")), + } +} + +fn clean_words(words: Vec) -> Vec { + words.into_iter().map(|w| w.trim().to_owned()).filter(|w| !w.is_empty()).collect() +} + +fn parse_call(raw: &Map, wake_words: &[String], d: &CallSettings) + -> Result<(CallSettings, Option>), SettingsError> { + let call = section(raw, "call")?; + let similarity = match call.and_then(|m| m.get("similarity")) { + None => d.similarity, + Some(v) => match v.as_f64() { + Some(x) if (0.0..=0.5).contains(&x) => x, + _ => return err("call.similarity must be a number 0-0.5"), + }, + }; + let mode = match get_str(call, "mode", "call", "wakeWord")?.as_str() { + "wakeWord" => CallMode::WakeWord, + "addressed" => CallMode::Addressed, + "everything" => CallMode::Everything, + _ => return err("call.mode must be wakeWord, addressed or everything"), + }; + let chat_wake_words = match call.and_then(|m| m.get("chatWakeWords")) { + None | Some(Value::Null) => None, + Some(_) => Some(clean_words(get_str_list(call, "chatWakeWords", "call", &[])?)), + }; + let stop_words = clean_words(get_str_list(call, "stopWords", "call", &d.stop_words)?); + Ok(( + CallSettings { + wake_words: wake_words.to_vec(), + similarity, + mode, + designated: snowflake_list(call, "designated", "call")?.into_iter().collect(), + designated_only: get_bool(call, "designatedOnly", "call", d.designated_only)?, + designated_no_wake_word: get_bool(call, "designatedNoWakeWord", "call", d.designated_no_wake_word)?, + stop_words, + }, + chat_wake_words, + )) +} + +fn parse_response(raw: &Map, d: &PolicySettings) -> Result { + let r = section(raw, "response")?; + let kind = match get_str(r, "policy", "response", "first")?.as_str() { + "first" => PolicyKind::First, + "inOrder" => PolicyKind::InOrder, + "latest" => PolicyKind::Latest, + "important" => PolicyKind::Important, + _ => return err("response.policy must be first, inOrder, latest or important"), + }; + let queue_max = match r.and_then(|m| m.get("queueMax")) { + None => d.queue_max, + Some(v) => match v.as_u64() { + Some(n @ 1..=20) => n as usize, + _ => return err("response.queueMax must be an integer 1-20"), + }, + }; + let mut priorities = HashMap::new(); + match r.and_then(|m| m.get("priorities")) { + None => {} + Some(Value::Object(p)) => { + for (k, v) in p { + let id = snowflake(&Value::String(k.clone())) + .ok_or_else(|| SettingsError("response.priorities keys must be Discord user IDs".into()))?; + let n = v.as_i64().ok_or_else(|| SettingsError("response.priorities values must be integers".into()))?; + priorities.insert(id, n); + } + } + Some(_) => return err("response.priorities must be an object of user ID to priority"), + } + Ok(PolicySettings { + kind, + queue_max, + collect: get_ms(r, "collectMs", "response", d.collect, 3000)?, + settle: get_ms(r, "settleMs", "response", d.settle, 3000)?, + priorities, + rank_timeout: d.rank_timeout, + }) +} + /// Discord's rule for command names: 1-32 lowercase letters, digits, `-` or `_`. fn valid_command_name(s: &str) -> bool { let n = s.chars().count(); @@ -196,11 +310,9 @@ pub fn parse_settings(raw: &Value) -> Result { _ => return err("voice.maxSpeakers must be an integer 1-10"), }, }; - let wake_words: Vec = get_str_list(voice, "wakeWords", "voice", &d.voice.wake_words)? - .into_iter() - .map(|w| w.trim().to_owned()) - .filter(|w| !w.is_empty()) - .collect(); + let wake_words = clean_words(get_str_list(voice, "wakeWords", "voice", &d.voice.wake_words)?); + let (call, chat_wake_words) = parse_call(raw, &wake_words, &d.call)?; + let response = parse_response(raw, &d.response)?; let join_notice = get_str(voice, "joinNotice", "voice", &d.voice.join_notice)?.trim().to_owned(); if join_notice.is_empty() { return err("voice.joinNotice must not be empty: people must be told they are transcribed"); @@ -265,6 +377,9 @@ pub fn parse_settings(raw: &Value) -> Result { }, args: get_str_list(worker, "args", "voiceWorker", &d.voice_worker.args)?, }, + call, + chat_wake_words, + response, }) } @@ -347,6 +462,43 @@ mod tests { } } + #[test] + fn call_and_response_sections_are_read_and_checked() { + let s = parse_settings(&json!({ + "voice": {"wakeWords": ["자비스", "javis"]}, + "call": {"similarity": 0.3, "mode": "addressed", "designated": [ID], "designatedOnly": true, + "designatedNoWakeWord": true, "stopWords": ["멈춰", " "], "chatWakeWords": ["봇"]}, + "response": {"policy": "important", "queueMax": 3, "collectMs": 500, "settleMs": 0, + "priorities": {ID: 2}} + })).unwrap(); + assert_eq!(s.call.wake_words, vec!["자비스", "javis"]); + assert_eq!(s.call.similarity, 0.3); + assert_eq!(s.call.mode, CallMode::Addressed); + assert!(s.call.designated.contains(&IDN)); + assert!(s.call.designated_only && s.call.designated_no_wake_word); + assert_eq!(s.call.stop_words, vec!["멈춰"]); + assert_eq!(s.chat_wake_words, Some(vec!["봇".to_string()])); + assert_eq!(s.response.kind, PolicyKind::Important); + assert_eq!(s.response.queue_max, 3); + assert_eq!(s.response.collect, Duration::from_millis(500)); + assert_eq!(s.response.settle, Duration::ZERO); + assert_eq!(s.response.priorities.get(&IDN), Some(&2)); + + let cases = [ + (json!({"call": {"similarity": 0.9}}), "call.similarity"), + (json!({"call": {"mode": "sometimes"}}), "call.mode"), + (json!({"call": {"designated": ["1"]}}), "call.designated"), + (json!({"response": {"policy": "random"}}), "response.policy"), + (json!({"response": {"queueMax": 0}}), "response.queueMax"), + (json!({"response": {"collectMs": 5000}}), "response.collectMs"), + (json!({"response": {"priorities": {"x": 1}}}), "response.priorities"), + ]; + for (raw, key) in cases { + let e = parse_settings(&raw).unwrap_err(); + assert!(e.0.contains(key), "{raw} -> {e}"); + } + } + #[test] fn null_ids_clear_them() { let s = parse_settings(&json!({"discord": {"guildId": null, "voiceChannelId": null}})).unwrap(); diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 6e95631..a9d2199 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -8,7 +8,7 @@ | M1 | 음성 워커 | 화자별 스트리밍 STT(공용 모델, 배치), 문장 단위 TTS를 WebSocket으로 제공. 녹음 파일 10개 동시 입력 테스트 통과. 구현과 테스트 완료(2026-11-11): `src/voice_worker/`, 스펙은 [voice_worker.spec.md](../../src/voice_worker/voice_worker.spec.md). 이 서버의 RTX 5050에서 10명이 겹쳐 말하는 실시간 입력(48kHz 스테레오, M0 한국어 샘플 8개를 10명에게 나눠 줌, 절반은 디스코드 speaking 종료, 절반은 무음으로 끝남)을 넣어 10명 모두 최종 전사를 받았고 문자 오류율은 평균 4%, 최대 19%("일곱 시"를 "7시"로 적은 것), 말 끝 판정부터 최종 전사 전송까지 중앙값 0.64초, 최대 1.56초였습니다. TTS는 첫 문장 소리가 0.2초에 나왔고, 그 소리를 다시 넣으면 같은 문장으로 받아 적혔습니다. 샘플이 MeloTTS 합성 음성이라 실제 사람 녹음과 게임PC 수치는 아직 없습니다 | | M2 | 디스코드 음성 코어 이전 | v1 봇 기능을 새 앱 안으로 이전. 입장/퇴장, 화자별 수신, 재생, 정지 명령 동작. 채팅 채널 연결(읽기·보내기). 구현과 테스트 완료(2026-11-11): `app/`(Rust, serenity + songbird), 스펙은 [discord_core.spec.md](../../app/src/discord_core.spec.md). 처음 Electron + TypeScript로 만든 것을 사용자 요청으로 Rust로 다시 씀. 앱이 음성 워커를 띄우고(실행마다 새 토큰, 죽으면 다시 시작) 연결이 끊기면 다시 붙습니다. 음성 채널에 들어갈 때마다 전사 고지를 채널 채팅에 올립니다. songbird 0.6.1의 DAVE 수신 해독이 조각 3분의 1가량을 깨뜨려서(20ms마다 음이 바뀌는 시험 신호로 확인, 보내기는 정상) 받은 패킷의 순서 맞추기와 Opus 해독은 앱이 직접 합니다. 실제 디스코드에서 봇 두 개로 확인(이 서버의 RTX 5050): 다른 봇이 채널에 튼 녹음 문장 5개를 모두 받아 적었고(문자 오류율 3개 0%, "기록해"를 "비록해"로 적은 1개 5%, "일곱 시"를 "7시"로 적은 1개 12.5%), 말이 끝난 뒤 최종 전사까지 0.71~0.90초였습니다. 자비스가 말한 문장을 상대 봇이 받아 다시 전사하니 오류율 3.4%였고, 정지 명령 뒤 0.08초 만에 소리가 끊겼습니다. 채팅 채널은 새 글 받기, 최근 글 읽기, 보내기(2,000자 넘으면 나눔, 아무도 호출하지 않음)가 됩니다. 사람이 직접 말한 소리와 게임PC(Windows) 빌드는 아직 확인하지 않았고, 음성으로 "자비스, 멈춰"는 호출 판정이 필요해 M4에서 합니다 | | M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 전체 기간에서 관련도 순으로 찾고, 기록 10만 개에서 검색 48~143ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 3단계 완료(2026-11-11): 앱이 음성 워커에 음성 채널 입장·퇴장, 사람 출입, 등록한 채팅 채널의 글·수정·삭제를 알리고, 워커가 최종 전사를 저장함. 워커는 `--history`로 저장소를, `--brain`으로 두뇌를 켜고, `reply` 요청에 묻는 사람의 범위로 찾은 기록을 넣어 답하고(`reply_text`) 음성이면 바로 말함. 실제 디스코드 시험(봇 두 개)에서 전사 8개가 이름과 함께 저장되고, 채팅 수정은 반영, 삭제한 글은 빠지고, 자비스가 나간 뒤 출입 기록이 모두 닫힘. 워커와 실제 두뇌(이 서버 Ollama `/v1`, qwen2.5:7b, 맥락 8천 토큰)로 다른 사람이 채팅에 남긴 약속을 4번 물어 4번 모두 맞게 답함. Ollama의 `/v1`은 맥락을 2,048토큰으로 고정해 지시문을 자르므로, Ollama로 시험할 때는 `num_ctx`를 넣은 모델 이름을 씀(Strata는 시작할 때 맥락을 정해 해당 없음). v2 두뇌는 한 사람용인 v1 장기 기억(프로필·일기·그래프)을 넣지 않고, 답하는 동안 원문이 로그에 찍히지 않게 함. 언제 `reply`를 보낼지(호출 판정)와 음성 답 재생 연결은 M4. 4단계 완료(2026-11-11): 채팅 채널 도구 `chatChannels`(목록·읽기·검색·보내기·수정·반응·삭제·고정, 스펙 [chat_channels.spec.md](../../src/jarvis/tools/builtin/chat_channels.spec.md)). 읽기·검색은 대화 기록 저장소에서, 나머지는 앱이 채널별 허용 설정을 확인하고 디스코드에서 실행. 삭제는 다음 메시지에서 사용자가 동의해야 실행하고, 채널 글은 명령이 아닌 자료로 표시. 실제 디스코드에서 수정(자기 글만)·반응·삭제·고정을 확인(음성 채널의 채팅은 디스코드가 고정을 막아 오류로 돌아옴). 평가(qwen2.5:7b) 3번에 12번 중 10번 통과, 글 속 명령을 따르지 않기와 같은 턴에 지우지 않기는 12번 모두 지킴. 식단 기록은 사람별로 나눔(v1 데이터는 그대로). 기존 테스트·평가 확인(2026-11-11): 단위 테스트는 2,215개 통과, 10개 실패이고, 실패 10개는 이 서버에 PortAudio가 없어 마이크 코드(음성 듣기·받아쓰기)가 꺼진 탓임. 갱신되지 않았던 테스트 4개(한국어 한 문장 날씨 3, 잡담 빠른 경로를 지나는 캐시 1)와 설치된 PyQt6를 가짜로 바꿔 다른 화면 테스트를 깨뜨리던 테스트 1곳을 고침. 평가(evals, qwen2.5:7b)는 145개 통과, 56개 실패, 60개 건너뜀. 실패 중 54개는 M3 이전 커밋(beaacb3)에서도 실패하거나, 3번씩 다시 돌린 통과 횟수가 양쪽이 같아 M3 때문에 생긴 실패는 없음. 나머지 2개는 새 채팅 도구 평가의 알려진 실패(12번 중 2번). 원래 실패하는 평가는 이 서버에 없는 모델(gpt-oss:20b, nomic-embed-text)을 쓰거나 qwen2.5:7b가 웹 검색·날씨 도구를 부르지 않는 경우가 대부분임. 실제로 쓸 모델로 평가 확인(2026-11-11): 게임PC의 Strata(Qwen3.6-35B-A3B UD-Q4_K_XL, 맥락 32K, 평소 배치)에 SSH 터널로 붙어 이 서버에서 평가 전체를 돌림. 193개 통과, 12개 실패, 60개 건너뜀(의도 판정·도구 선택 평가는 gemma4 단계에서만 돌고, gemma4는 이 서버 Ollama에 없음), 8분 13초. 실패 12개를 3번씩 다시 돌리니 5개는 3번 모두 실패(알려진 위치를 날씨 도구 인자로 넣지 않음 2, 파리·런던 비교에서 날씨 도구를 한 번만 부름 1, 지식 그래프 갈래 분류 1, 맥락에 있는 위치를 기억 검색 질문에 다시 넣음 1)했고, 날씨 한 번 부르기 평가는 엔진의 정해진 날씨 경로(`_maybe_deterministic_weather`)가 평가가 바꿔 둔 도구 실행기를 거치지 않고 실제 날씨를 받아 한국어로 바로 답해 3번 모두 실패함(모델과 상관없음). 나머지 6개는 3번 중 1~3번 통과함. qwen2.5:7b에서 없던 실패는 기억 검색 질문 1개(3번 모두)와 날씨 다시 시도 2개(다시 돌리면 6번 중 4번 통과)임 실패 고침(2026-11-11): 엔진의 정해진 한국어 날씨 경로를 뺌(평가의 도구 실행기를 거치지 않았고, 사용자가 말한 위치를 쓰지 못함, 큰 모델은 도구 결과를 한국어 한 문장으로 그대로 답함). 날씨 도구와 대화 지시문은 사용자가 대화나 기억에서 말한 위치를 넣고, 자동으로 잡힌 위치는 옮겨 적지 않게 함. "구, 시, 나라" 이름이 안 찾아지면 넓은 지역으로 다시 찾음. 계획 단계에 현재 시간·위치 줄을 주어, 위치를 모를 때만 기억에서 사용자 위치를 먼저 찾게 함. 같은 도구 반복 제한이 이전 답변의 호출까지 세어 사용자가 다시 해 달라고 해도 막던 버그를 고침. 기억 검색어 지시문에서 평가와 같은 문장의 예시를 바꾸고 현재 맥락 블록을 예시 뒤로 옮김(위치를 모를 때는 여전히 묻는지 보는 평가 추가, qwen2.5:7b는 바꾸기 전에도 묻지 않음). 평가 전체 202개 통과, 4개 실패, 9분 3초. 이 전체 실행의 날씨 실패 1개는 장소를 말하지 않은 "what's the weather this week"에 자동으로 잡힌 위치(`Hackney, England, UK`)를 인자로 옮겨 적은 것으로, 그 뒤 날씨 도구와 지시문을 사용자가 말한 위치만 넣도록 좁혀 고침. 고친 뒤 날씨 평가 12개를 따로 3번 돌려 36번 중 34번 통과(이 평가는 3번 모두 통과, 실패 2번은 날씨 한 번 부르기 평가가 파리 날씨 답에 도시 이름을 다시 말하지 않은 것). 전체 실행의 나머지 실패는 지식 그래프 갈래 분류 1개(모델이 "사용자가 물었다"를 사용자 사실로 하나 더 남김, 지시문을 두 번 고쳐도 같아 되돌림, v2는 v1 장기 기억을 쓰지 않음)와 다시 돌리면 통과하는 2개(유명인 두 턴 대화, 최근 일기 반영) | -| M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트 | +| M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트. 1단계 완료(2026-11-11): 앱의 호출 판정 `app/src/calls.rs`와 응답 정책 `app/src/policy.rs`(스펙 [conversation.spec.md](../../app/src/conversation.spec.md)), 설정 `call`·`response`. 비슷한 발음은 유니코드 NFKD로 한글을 자모로 나눠 편집 거리로 판단(기본 0.2: "자비즈"는 호출, "서비스"는 아님). 정책은 말이 끝난 시각 순서, 먼저 끝난 말의 전사 대기(최대 0.8초), 끼어들기, 놓친 요청 사유를 가짜 시각으로 시험함. 디스코드·두뇌 연결은 2단계 | | M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드) | | M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인 | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. |