feat(app): call detection and the four response policies
- calls.rs: wake words anywhere in the utterance with near matches by edit distance on NFKD-normalised letters (Hangul splits into its letters), call modes (wakeWord, addressed, everything), designated people with both switches, and a voice stop (wake word + stop word). - policy.rs: first, inOrder, latest and important as an event-driven state machine with the time passed in: ordering by end time, waiting for an earlier-ended utterance still being transcribed, queue limit, interruption, importance ranking only on a tie with a timeout, stop dropping the queue, and a reason for every missed request. - settings: new call and response sections, validated with the key. - conversation.spec.md documents the contract; registry and roadmap updated. Wiring into the Discord core and the brain comes next. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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<String>,
|
||||
/// Voice worker STT settings (voice_worker.spec.md); the worker validates them.
|
||||
pub stt: Map<String, Value>,
|
||||
@@ -68,6 +73,11 @@ pub struct Settings {
|
||||
pub voice: VoiceSettings,
|
||||
pub chat_channels: Vec<ChatChannelSettings>,
|
||||
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<Vec<String>>,
|
||||
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<String, Value>>, key: &str, path: &str, default:
|
||||
}
|
||||
}
|
||||
|
||||
fn get_ms(m: Option<&Map<String, Value>>, key: &str, path: &str, default: Duration, max: u64)
|
||||
-> Result<Duration, SettingsError> {
|
||||
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<String, Value>>, key: &str, path: &str) -> Result<Vec<u64>, SettingsError> {
|
||||
match m.and_then(|m| m.get(key)) {
|
||||
None => Ok(vec![]),
|
||||
Some(Value::Array(a)) => a
|
||||
.iter()
|
||||
.map(snowflake)
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.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<String>) -> Vec<String> {
|
||||
words.into_iter().map(|w| w.trim().to_owned()).filter(|w| !w.is_empty()).collect()
|
||||
}
|
||||
|
||||
fn parse_call(raw: &Map<String, Value>, wake_words: &[String], d: &CallSettings)
|
||||
-> Result<(CallSettings, Option<Vec<String>>), 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<String, Value>, d: &PolicySettings) -> Result<PolicySettings, SettingsError> {
|
||||
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<Settings, SettingsError> {
|
||||
_ => return err("voice.maxSpeakers must be an integer 1-10"),
|
||||
},
|
||||
};
|
||||
let wake_words: Vec<String> = 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<Settings, SettingsError> {
|
||||
},
|
||||
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();
|
||||
|
||||
Reference in New Issue
Block a user