feat: answer calls in the voice channel through the response policy
- conversation.rs: the loop between the core's events and the rest. Finals go through call detection and the response policy; answers are asked of the brain and spoken from the app's queue, an interruption cancels only that answer, a voice stop silences everything, and missed requests are kept without text (last 100). Tested with a fake voice side. - Core: answer(user, text) adopts a playback request the worker speaks under the same id, cancel(id) stops one request, ask_addressed and ask_rank pass the conversation's questions; new SpeakingStopped, Addressed and Ranked events. - Worker client: reply, addressed and rank messages and their results; a reply with no answer, refused or not sent ends its speech as failed. - Voice worker: addressed and rank messages on their own threads, beside a running reply; a spoken reply cancelled while the brain is answering is not spoken. judges.py holds the two short LLM judgements with the heard text fenced as data; eval evals/test_voice_judges.py. - Specs (conversation, discord core, voice worker), docs/llm_contexts.md and the roadmap updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
416
app/src/conversation.rs
Normal file
416
app/src/conversation.rs
Normal file
@@ -0,0 +1,416 @@
|
||||
//! The conversation loop (`app/src/conversation.spec.md`): finished utterances go through call
|
||||
//! detection and the response policy, and the policy's actions become brain answers, stops and
|
||||
//! missed-request records.
|
||||
//!
|
||||
//! `Conversation` holds no Discord or worker types: it talks to the voice side through `Voice`, so the
|
||||
//! glue is tested with a fake. `run` drives it from the core's events with a timer for the policy.
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::calls::{Call, CallSettings};
|
||||
use crate::discord::{CoreEvent, DiscordCore};
|
||||
use crate::policy::{Action, MissReason, Policy, PolicySettings, Request};
|
||||
use crate::debug_log;
|
||||
|
||||
/// How long the brain's "was it said to Jarvis?" answer is waited for; no answer counts as no.
|
||||
pub const ADDRESSED_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
/// Missed requests kept for the dashboard (M5).
|
||||
pub const MISSED_KEPT: usize = 100;
|
||||
|
||||
/// What the conversation needs from the voice side.
|
||||
pub trait Voice {
|
||||
/// Have the brain answer and speak it; the speech request id, or None when it cannot.
|
||||
fn answer(&self, user: u64, text: &str) -> Option<String>;
|
||||
/// Stop one speech request.
|
||||
fn cancel(&self, id: &str);
|
||||
/// Stop all speech at once.
|
||||
fn stop_all(&self);
|
||||
fn ask_addressed(&self, id: &str, user: u64, text: &str) -> bool;
|
||||
fn ask_rank(&self, id: &str, candidates: &[(String, u64, String)]) -> bool;
|
||||
}
|
||||
|
||||
impl Voice for DiscordCore {
|
||||
fn answer(&self, user: u64, text: &str) -> Option<String> {
|
||||
DiscordCore::answer(self, user, text)
|
||||
}
|
||||
fn cancel(&self, id: &str) {
|
||||
DiscordCore::cancel(self, id)
|
||||
}
|
||||
fn stop_all(&self) {
|
||||
DiscordCore::stop(self);
|
||||
}
|
||||
fn ask_addressed(&self, id: &str, user: u64, text: &str) -> bool {
|
||||
DiscordCore::ask_addressed(self, id, user, text)
|
||||
}
|
||||
fn ask_rank(&self, id: &str, candidates: &[(String, u64, String)]) -> bool {
|
||||
DiscordCore::ask_rank(self, id, candidates)
|
||||
}
|
||||
}
|
||||
|
||||
/// A request that was not answered, or an answer that was stopped. No text: only who, why and when.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Missed {
|
||||
pub speaker: u64,
|
||||
pub reason: MissReason,
|
||||
pub at: Instant,
|
||||
pub chars: usize,
|
||||
}
|
||||
|
||||
pub struct Conversation<V: Voice> {
|
||||
voice: V,
|
||||
calls: CallSettings,
|
||||
policy: Policy,
|
||||
next_id: u64,
|
||||
/// Policy request id -> speech request id, and back.
|
||||
answers: HashMap<u64, String>,
|
||||
by_speech: HashMap<String, u64>,
|
||||
/// Ask id -> the request it becomes on a yes, and when it was asked.
|
||||
asks: HashMap<String, (Request, Instant)>,
|
||||
missed: VecDeque<Missed>,
|
||||
}
|
||||
|
||||
impl<V: Voice> Conversation<V> {
|
||||
pub fn new(voice: V, calls: CallSettings, policy: PolicySettings) -> Self {
|
||||
Self { voice, calls, policy: Policy::new(policy), next_id: 0, answers: HashMap::new(),
|
||||
by_speech: HashMap::new(), asks: HashMap::new(), missed: VecDeque::new() }
|
||||
}
|
||||
|
||||
pub fn missed(&self) -> impl Iterator<Item = &Missed> {
|
||||
self.missed.iter()
|
||||
}
|
||||
|
||||
pub fn on_event(&mut self, ev: &CoreEvent, now: Instant) {
|
||||
match ev {
|
||||
CoreEvent::SpeechStart(h) => self.policy.utterance_open(h.speaker_id),
|
||||
CoreEvent::SpeakingStopped(user) => self.policy.speaking_stopped(*user, now),
|
||||
CoreEvent::Final(f) => {
|
||||
let speaker = f.heard.speaker_id;
|
||||
self.next_id += 1;
|
||||
let req = Request { id: self.next_id, speaker, text: f.text.clone(), direct: false,
|
||||
ended_at: now.checked_sub(Duration::from_millis(f.wait_ms)).unwrap_or(now), arrived_at: now };
|
||||
let call = self.calls.judge(speaker, &f.text);
|
||||
debug_log!("conversation", "final speaker={speaker} req={} call={call:?}", req.id);
|
||||
match call {
|
||||
Call::Ignore => {
|
||||
let a = self.policy.utterance_closed(speaker, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
Call::Stop => {
|
||||
self.voice.stop_all();
|
||||
let a = self.policy.stop();
|
||||
self.apply(a, now);
|
||||
let a = self.policy.utterance_closed(speaker, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
Call::Request { direct } => {
|
||||
let a = self.policy.request(Request { direct, ..req }, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
Call::Ask => {
|
||||
let id = format!("q{}", req.id);
|
||||
if self.voice.ask_addressed(&id, speaker, &f.text) {
|
||||
self.asks.insert(id, (req, now));
|
||||
} else {
|
||||
let a = self.policy.utterance_closed(speaker, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
CoreEvent::Addressed { id, addressed } => {
|
||||
if let Some((req, _)) = self.asks.remove(id) {
|
||||
debug_log!("conversation", "addressed req={} yes={addressed}", req.id);
|
||||
let a = if *addressed {
|
||||
self.policy.request(req, now)
|
||||
} else {
|
||||
self.policy.utterance_closed(req.speaker, now)
|
||||
};
|
||||
self.apply(a, now);
|
||||
}
|
||||
}
|
||||
CoreEvent::Ranked { id, order } => {
|
||||
let (Some(rank_id), order) = (id.strip_prefix('k').and_then(|n| n.parse().ok()),
|
||||
order.iter().filter_map(|o| o.parse().ok()).collect::<Vec<u64>>()) else { return };
|
||||
let a = self.policy.ranked(rank_id, &order, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
CoreEvent::SpeakEnd(e) => {
|
||||
if let Some(pid) = self.by_speech.remove(&e.id) {
|
||||
self.answers.remove(&pid);
|
||||
debug_log!("conversation", "answer req={pid} done played={} cancelled={} failed={}",
|
||||
e.played, e.cancelled, e.failed);
|
||||
let a = self.policy.answer_done(pid, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
}
|
||||
CoreEvent::Left { .. } => {
|
||||
// Nothing can be said outside a voice channel: drop what was going on.
|
||||
let a = self.policy.stop();
|
||||
self.apply(a, now);
|
||||
for (_, (req, _)) in self.asks.drain().collect::<Vec<_>>() {
|
||||
let a = self.policy.utterance_closed(req.speaker, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Timers: the policy's and unanswered "was it said to Jarvis?" questions.
|
||||
pub fn tick(&mut self, now: Instant) {
|
||||
let late: Vec<String> = self.asks.iter()
|
||||
.filter(|(_, (_, at))| now >= *at + ADDRESSED_TIMEOUT).map(|(id, _)| id.clone()).collect();
|
||||
for id in late {
|
||||
if let Some((req, _)) = self.asks.remove(&id) {
|
||||
debug_log!("conversation", "addressed req={} timed out", req.id);
|
||||
let a = self.policy.utterance_closed(req.speaker, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
}
|
||||
let a = self.policy.tick(now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
|
||||
pub fn next_deadline(&self) -> Option<Instant> {
|
||||
let asks = self.asks.values().map(|(_, at)| *at + ADDRESSED_TIMEOUT).min();
|
||||
match (self.policy.next_deadline(), asks) {
|
||||
(Some(a), Some(b)) => Some(a.min(b)),
|
||||
(a, b) => a.or(b),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(&mut self, actions: Vec<Action>, now: Instant) {
|
||||
for action in actions {
|
||||
match action {
|
||||
Action::Answer(r) => match self.voice.answer(r.speaker, &r.text) {
|
||||
Some(sid) => {
|
||||
debug_log!("conversation", "answer req={} speaker={} speech={sid}", r.id, r.speaker);
|
||||
self.by_speech.insert(sid.clone(), r.id);
|
||||
self.answers.insert(r.id, sid);
|
||||
}
|
||||
None => {
|
||||
let a = self.policy.answer_done(r.id, now);
|
||||
self.apply(a, now);
|
||||
}
|
||||
},
|
||||
Action::StopAnswer(pid) => {
|
||||
if let Some(sid) = self.answers.remove(&pid) {
|
||||
self.by_speech.remove(&sid);
|
||||
self.voice.cancel(&sid);
|
||||
}
|
||||
}
|
||||
Action::Missed(r, reason) => {
|
||||
debug_log!("conversation", "missed req={} speaker={} reason={reason:?}", r.id, r.speaker);
|
||||
if self.missed.len() == MISSED_KEPT {
|
||||
self.missed.pop_front();
|
||||
}
|
||||
self.missed.push_back(Missed { speaker: r.speaker, reason, at: now, chars: r.text.chars().count() });
|
||||
}
|
||||
Action::Rank { id, candidates } => {
|
||||
let c: Vec<(String, u64, String)> =
|
||||
candidates.iter().map(|r| (r.id.to_string(), r.speaker, r.text.clone())).collect();
|
||||
debug_log!("conversation", "rank k{id} candidates={}", c.len());
|
||||
// Not sent: the policy's ranking timeout picks the earliest-ended.
|
||||
self.voice.ask_rank(&format!("k{id}"), &c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drive a conversation from the core's events, passing every event on to `out`.
|
||||
pub async fn run<V: Voice>(mut conv: Conversation<V>, mut events: mpsc::UnboundedReceiver<CoreEvent>,
|
||||
out: mpsc::UnboundedSender<CoreEvent>) {
|
||||
loop {
|
||||
let deadline = conv.next_deadline();
|
||||
tokio::select! {
|
||||
ev = events.recv() => match ev {
|
||||
Some(ev) => {
|
||||
conv.on_event(&ev, Instant::now());
|
||||
let _ = out.send(ev);
|
||||
}
|
||||
None => return,
|
||||
},
|
||||
_ = async {
|
||||
match deadline {
|
||||
Some(d) => tokio::time::sleep_until(d.into()).await,
|
||||
None => std::future::pending::<()>().await,
|
||||
}
|
||||
} => conv.tick(Instant::now()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::discord::{Heard, HeardFinal};
|
||||
use crate::playback::PlaybackEnd;
|
||||
use crate::policy::PolicyKind;
|
||||
use crate::calls::CallMode;
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
enum Did {
|
||||
Answer(u64, String),
|
||||
Cancel(String),
|
||||
StopAll,
|
||||
Addressed(String, u64),
|
||||
Rank(String, Vec<String>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct Fake {
|
||||
did: Rc<RefCell<Vec<Did>>>,
|
||||
n: Rc<RefCell<u32>>,
|
||||
}
|
||||
impl Voice for Fake {
|
||||
fn answer(&self, user: u64, text: &str) -> Option<String> {
|
||||
*self.n.borrow_mut() += 1;
|
||||
self.did.borrow_mut().push(Did::Answer(user, text.into()));
|
||||
Some(format!("s{}", self.n.borrow()))
|
||||
}
|
||||
fn cancel(&self, id: &str) {
|
||||
self.did.borrow_mut().push(Did::Cancel(id.into()));
|
||||
}
|
||||
fn stop_all(&self) {
|
||||
self.did.borrow_mut().push(Did::StopAll);
|
||||
}
|
||||
fn ask_addressed(&self, id: &str, user: u64, _text: &str) -> bool {
|
||||
self.did.borrow_mut().push(Did::Addressed(id.into(), user));
|
||||
true
|
||||
}
|
||||
fn ask_rank(&self, id: &str, c: &[(String, u64, String)]) -> bool {
|
||||
self.did.borrow_mut().push(Did::Rank(id.into(), c.iter().map(|x| x.0.clone()).collect()));
|
||||
true
|
||||
}
|
||||
}
|
||||
impl Fake {
|
||||
fn take(&self) -> Vec<Did> {
|
||||
std::mem::take(&mut self.did.borrow_mut())
|
||||
}
|
||||
}
|
||||
|
||||
const A: u64 = 11;
|
||||
const B: u64 = 22;
|
||||
|
||||
fn conv(kind: PolicyKind, mode: CallMode) -> (Conversation<Fake>, Fake, Instant) {
|
||||
let f = Fake::default();
|
||||
let calls = CallSettings { mode, ..CallSettings::default() };
|
||||
let policy = PolicySettings { kind, collect: Duration::ZERO, ..PolicySettings::default() };
|
||||
(Conversation::new(f.clone(), calls, policy), f, Instant::now())
|
||||
}
|
||||
fn fin(speaker: u64, text: &str, wait_ms: u64) -> CoreEvent {
|
||||
CoreEvent::Final(HeardFinal { heard: Heard { speaker_id: speaker, speaker_name: "x".into(), utt: 1 },
|
||||
text: text.into(), end_reason: "silence".into(), audio_ms: 1000, wait_ms, stt_ms: 100 })
|
||||
}
|
||||
fn end(id: &str, cancelled: bool) -> CoreEvent {
|
||||
CoreEvent::SpeakEnd(PlaybackEnd { id: id.into(), played: 1, cancelled, failed: false })
|
||||
}
|
||||
fn ms(t: Instant, n: u64) -> Instant {
|
||||
t + Duration::from_millis(n)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_is_answered_and_the_next_one_waits_for_its_speech_to_end() {
|
||||
let (mut c, f, t) = conv(PolicyKind::InOrder, CallMode::WakeWord);
|
||||
c.on_event(&fin(A, "자비스 날씨 어때", 100), ms(t, 0));
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "자비스 날씨 어때".into())]);
|
||||
c.on_event(&fin(B, "오늘 뭐 먹지", 100), ms(t, 100)); // not a call
|
||||
c.on_event(&fin(B, "자비스 불 꺼 줘", 100), ms(t, 200));
|
||||
assert!(f.take().is_empty(), "queued behind the answer");
|
||||
c.on_event(&end("s1", false), ms(t, 3000));
|
||||
assert_eq!(f.take(), vec![Did::Answer(B, "자비스 불 꺼 줘".into())]);
|
||||
assert_eq!(c.missed().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_drops_a_call_while_busy_and_records_it_without_text() {
|
||||
let (mut c, f, t) = conv(PolicyKind::First, CallMode::WakeWord);
|
||||
c.on_event(&fin(A, "자비스 날씨", 100), ms(t, 0));
|
||||
c.on_event(&fin(B, "자비스 안녕", 100), ms(t, 100));
|
||||
assert_eq!(f.take().len(), 1);
|
||||
let m: Vec<_> = c.missed().cloned().collect();
|
||||
assert_eq!(m, vec![Missed { speaker: B, reason: MissReason::Busy, at: ms(t, 100), chars: "자비스 안녕".chars().count() }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_voice_stop_silences_everything_and_drops_the_queue() {
|
||||
let (mut c, f, t) = conv(PolicyKind::InOrder, CallMode::WakeWord);
|
||||
c.on_event(&fin(A, "자비스 날씨", 100), ms(t, 0));
|
||||
c.on_event(&fin(B, "자비스 안녕", 100), ms(t, 100));
|
||||
f.take();
|
||||
c.on_event(&fin(B, "자비스 멈춰", 100), ms(t, 200));
|
||||
let did = f.take();
|
||||
assert_eq!(did[0], Did::StopAll);
|
||||
assert!(!did.iter().any(|d| matches!(d, Did::Answer(..))));
|
||||
// The stopped speech's end starts nothing.
|
||||
c.on_event(&end("s1", true), ms(t, 300));
|
||||
assert!(f.take().iter().all(|d| !matches!(d, Did::Answer(..))));
|
||||
assert_eq!(c.missed().filter(|m| m.reason == MissReason::Stopped).count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn addressed_mode_asks_the_brain_and_answers_only_a_yes() {
|
||||
let (mut c, f, t) = conv(PolicyKind::InOrder, CallMode::Addressed);
|
||||
c.on_event(&fin(A, "불 좀 꺼 줄래", 100), ms(t, 0));
|
||||
let Did::Addressed(q, user) = f.take().remove(0) else { panic!() };
|
||||
assert_eq!(user, A);
|
||||
c.on_event(&CoreEvent::Addressed { id: q, addressed: true }, ms(t, 300));
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "불 좀 꺼 줄래".into())]);
|
||||
c.on_event(&end("s1", false), ms(t, 2000));
|
||||
|
||||
c.on_event(&fin(B, "너 어제 그거 봤어?", 100), ms(t, 2100));
|
||||
let Did::Addressed(q, _) = f.take().remove(0) else { panic!() };
|
||||
c.on_event(&CoreEvent::Addressed { id: q, addressed: false }, ms(t, 2300));
|
||||
assert!(f.take().is_empty());
|
||||
|
||||
// No answer at all counts as no once the timeout passes.
|
||||
c.on_event(&fin(B, "음", 100), ms(t, 3000));
|
||||
f.take();
|
||||
assert_eq!(c.next_deadline(), Some(ms(t, 3000) + ADDRESSED_TIMEOUT));
|
||||
c.tick(ms(t, 3000) + ADDRESSED_TIMEOUT);
|
||||
assert!(f.take().is_empty());
|
||||
assert_eq!(c.next_deadline(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latest_cancels_the_running_answer_for_a_newer_call() {
|
||||
let (mut c, f, t) = conv(PolicyKind::Latest, CallMode::WakeWord);
|
||||
c.on_event(&fin(A, "자비스 날씨", 100), ms(t, 0));
|
||||
c.on_event(&fin(B, "자비스 뉴스", 100), ms(t, 500));
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "자비스 날씨".into()), Did::Cancel("s1".into()),
|
||||
Did::Answer(B, "자비스 뉴스".into())]);
|
||||
// The cancelled speech's end does not end the new answer.
|
||||
c.on_event(&end("s1", true), ms(t, 600));
|
||||
c.on_event(&fin(A, "자비스 하나 더", 100), ms(t, 700));
|
||||
assert_eq!(f.take(), vec![Did::Cancel("s2".into()), Did::Answer(A, "자비스 하나 더".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tie_in_important_is_ranked_by_the_brain() {
|
||||
let (mut c, f, t) = conv(PolicyKind::Important, CallMode::WakeWord);
|
||||
c.on_event(&fin(A, "자비스 날씨", 100), ms(t, 0));
|
||||
f.take();
|
||||
c.on_event(&fin(B, "자비스 불 꺼", 100), ms(t, 200));
|
||||
let Did::Rank(k, ids) = f.take().remove(0) else { panic!() };
|
||||
assert_eq!(ids, vec!["1", "2"]);
|
||||
c.on_event(&CoreEvent::Ranked { id: k, order: vec!["2".into(), "1".into()] }, ms(t, 400));
|
||||
assert_eq!(f.take(), vec![Did::Cancel("s1".into()), Did::Answer(B, "자비스 불 꺼".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn end_times_come_from_the_finals_wait() {
|
||||
let (mut c, f, t) = conv(PolicyKind::InOrder, CallMode::WakeWord);
|
||||
c.on_event(&fin(A, "자비스 하나", 0), ms(t, 0));
|
||||
c.on_event(&fin(B, "자비스 둘", 0), ms(t, 1000));
|
||||
c.on_event(&fin(A, "자비스 셋", 900), ms(t, 1500)); // ended at 600, before 둘
|
||||
f.take();
|
||||
c.on_event(&end("s1", false), ms(t, 2000));
|
||||
assert_eq!(f.take(), vec![Did::Answer(A, "자비스 셋".into())]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user