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:
javis-bot
2026-11-11 22:26:47 +09:00
parent e885630e91
commit f892a1dce9
20 changed files with 1174 additions and 14 deletions

416
app/src/conversation.rs Normal file
View 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())]);
}
}

View File

@@ -114,9 +114,37 @@ request first, the answer stops (missed, `interrupted`) and the new request is a
running answer first, or does not come in time, the answer goes on and the new request waits. The
ranking is dropped when the running answer ends first.
## The conversation loop
`app/src/conversation.rs` runs between the core's events and everything else that reads them (every
event is passed on unchanged). It talks to the core through a small `Voice` interface (answer, cancel
one request, stop all, ask "addressed", ask "rank"), so the glue is tested with a fake.
- `SpeechStart` opens the speaker's utterance; `SpeakingStopped` marks it ending.
- `Final`: a request gets the next id, `ended_at` = arrival minus the final's `wait_ms`, and goes
through call detection. Ignore closes the utterance. Stop stops all speech, runs the policy's stop and
closes the utterance. Request goes to the policy. Ask sends `addressed` to the brain; a yes becomes the
request, a no (or a failed judgement) closes the utterance, and no answer within 5 s counts as no.
- Policy actions: `Answer` → `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;
`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).
- `SpeakEnd` of an answer's speech is that answer's done. The end of a speech the loop already
cancelled starts nothing.
- `Left` (the bot left the voice channel): the policy's stop, and pending "addressed" questions close
their utterances.
- A timer wakes the loop at the policy's next deadline or the earliest "addressed" timeout.
The brain's two judgements are `src/voice_worker/judges.py` (`voice_worker.spec.md`): one short call
each to the chat model, the heard text fenced as data. Eval: `evals/test_voice_judges.py`.
## 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).
interruption, ranking tie, ranking timeout, stop dropping the queue), and the conversation loop with a
fake voice side (answering and queueing, a busy drop recorded without text, voice stop, addressed yes,
no and timeout, interruption cancelling the right speech, a ranking deciding, end times from
`wait_ms`). `tests/worker_protocol.rs` checks an answer spoken under its id and both judgements against
the real Python worker with a fake brain.

View File

@@ -57,11 +57,17 @@ pub enum CoreEvent {
Joined { guild_id: u64, channel_id: u64 },
Left { guild_id: u64, channel_id: u64, reason: String },
SpeechStart(Heard),
/// The speaker stopped sending audio (their final is still to come).
SpeakingStopped(u64),
Partial(Heard, String),
Final(HeardFinal),
SpeakStart(String),
SpeakEnd(PlaybackEnd),
Chat(ChatMessage),
/// The brain's answer to `addressed()`.
Addressed { id: String, addressed: bool },
/// The brain's answer to `rank()`: candidate ids, most important first (empty: failed).
Ranked { id: String, order: Vec<String> },
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -390,6 +396,31 @@ impl DiscordCore {
Some(id)
}
/// Have the brain answer `user` and speak it as one request in the queue. The request id (its
/// `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.
pub fn answer(&self, user: u64, text: &str) -> Option<String> {
self.voice_channel_id()?;
let id = with_playback(&self.inner, |p| p.adopt());
self.inner.worker.reply(&id, user, text, true);
Some(id)
}
/// Stop one request (an answer or a `say`); the rest of the queue goes on.
pub fn cancel(&self, id: &str) {
with_playback(&self.inner, |p| p.cancel(id));
}
/// Ask the brain whether `text` was said to Jarvis; the answer comes as `CoreEvent::Addressed`.
pub fn ask_addressed(&self, id: &str, user: u64, text: &str) -> bool {
self.inner.worker.addressed(id, user, text)
}
/// Ask the brain to rank candidates `(id, user, text)`; the answer comes as `CoreEvent::Ranked`.
pub fn ask_rank(&self, id: &str, candidates: &[(String, u64, String)]) -> bool {
self.inner.worker.rank(id, candidates)
}
/// More text for a request started with `say(.., true)`.
pub fn continue_text(&self, id: &str, text: &str, more: bool) {
with_playback(&self.inner, |p| p.continue_text(id, text, more));
@@ -622,6 +653,15 @@ async fn worker_task(core: std::sync::Weak<Inner>, mut rx: mpsc::UnboundedReceiv
WorkerEvent::Final(m) => on_final(&inner, m),
WorkerEvent::TtsAudio { id, seq, pcm } => with_playback(&inner, |p| p.audio(&id, seq, pcm)),
WorkerEvent::TtsDone(d) => with_playback(&inner, |p| p.done(&d)),
WorkerEvent::ReplyText { id, text, failed } => {
debug_log!("voice", "reply {id} chars={} failed={failed}", text.chars().count());
}
WorkerEvent::Addressed { id, addressed } => {
let _ = inner.events.send(CoreEvent::Addressed { id, addressed });
}
WorkerEvent::Ranked { id, order } => {
let _ = inner.events.send(CoreEvent::Ranked { id, order });
}
WorkerEvent::Ready(_) => {
report_chat_channels(&inner);
report_voice_state(&inner);
@@ -803,6 +843,7 @@ async fn speaking_end_timer(core: std::sync::Weak<Inner>, rx: Arc<Mutex<RxState>
}
if gate.end(user) {
inner.worker.speaking_end(&id);
let _ = inner.events.send(CoreEvent::SpeakingStopped(user));
}
}
}

View File

@@ -18,8 +18,8 @@ worker side of the link is `src/voice_worker/voice_worker.spec.md`.
- **No text in logs.** Logs carry ids, sizes, counts and timings, never what anyone said or wrote, or
what the bot says. Debug logs (`debug_log!`, on with `JARVIS_DEBUG=1`) go at joins and leaves,
command use, finals, speech requests and stops, chat events and sends, and worker connection changes.
- **Language-agnostic.** Nothing in the core matches words. Wake words are only passed to the STT as a
hint until call detection (M4) uses them.
- **Language-agnostic.** Nothing in the core matches words. Wake words go to the STT as a hint; call
detection (`conversation.spec.md`) is the only place they are matched.
- **Testable without Discord.** The pieces with rules (receive window, playback queue, speaker limit,
chat access and splitting, settings, worker link, worker process) are plain types tested with fakes;
the Discord glue is tested on real Discord by an opt-in live test.
@@ -138,17 +138,25 @@ and the late "left" update cancelled the new join (seen on real Discord).
- When a person leaves the channel (gateway voice state or songbird's client disconnect), the bot
sends `speaker_leave`, so their utterance finishes and the worker frees their place.
- **Events** for the layers above: `SpeechStart`, `Partial` and `Final` with the speaker's ID and
server display name; `SpeakStart` and `SpeakEnd`; `Joined` and `Left` (with a reason: `command`,
`moved`, `disconnected`, `shutdown`).
server display name; `SpeakingStopped` with the speaker's ID when their `speaking_end` is sent;
`SpeakStart` and `SpeakEnd`; `Joined` and `Left` (with a reason: `command`, `moved`, `disconnected`,
`shutdown`); `Addressed` and `Ranked` with the brain's answers to `ask_addressed` and `ask_rank`.
- **Speaking**: `say(text, more)` queues a TTS request and returns its id (`None` when not in a voice
channel); `continue_text(id, text, more)` adds text to an open request. Each sentence the worker
sends becomes one clip (a 48 kHz stereo WAV played through songbird without resampling); clips play
in sentence order as soon as they arrive, and requests play first come, first served. A sentence that
failed is skipped and the rest still play. `SpeakEnd` reports how many sentences played and whether
the request was cancelled or failed.
- **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, 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
`ask_rank(id, candidates)` pass the conversation's questions to the brain.
- **Stop** (slash command `stop`, or `stop()`): the current clip stops at the next 20 ms mix, every
queued request is dropped, and unfinished requests are cancelled at the worker; each ends with
`cancelled: true`. Stopping by voice ("자비스, 멈춰") needs call detection and comes in M4.
`cancelled: true`. Stopping by voice ("자비스, 멈춰") is call detection's stop (`conversation.spec.md`),
which does the same.
- **Leave** (slash command `leave`, or `leave()`): stop speaking, send `speaker_leave` for everyone
heard, and disconnect. When songbird's driver gives up the connection (kicked, channel deleted, long
network loss) the session ends with `disconnected`. A driver disconnect without a reason is one the

View File

@@ -3,6 +3,7 @@
pub mod log;
pub mod calls;
pub mod chat;
pub mod conversation;
pub mod discord;
pub mod frames;
pub mod playback;

View File

@@ -22,7 +22,7 @@ async fn main() {
loop {
tokio::select! {
ev = services.events.recv() => match ev {
// The brain (M3) consumes these; for now only their shape is logged, never the text.
// The conversation loop answers what is heard; here only the shape is logged, never the text.
Some(CoreEvent::Final(f)) => debug_log!("app", "heard {} utt={} chars={}", f.heard.speaker_id, f.heard.utt, f.text.chars().count()),
Some(_) => {}
None => break,

View File

@@ -81,6 +81,44 @@ impl<B: TtsBackend, S: ClipSink> Playback<B, S> {
id
}
/// Queue a request whose speech the worker makes from the brain's answer (`reply` with `speak`),
/// under the returned id. Nothing is sent here.
pub fn adopt(&mut self) -> String {
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 });
crate::debug_log!("play", "answer id={id} queued={}", self.queue.len());
id
}
/// End a request that will get no audio (the brain gave no answer).
pub fn fail(&mut self, id: &str) {
if let Some(r) = self.queue.iter_mut().find(|r| r.id == id && !r.done) {
r.done = true;
r.failed = true;
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) {
let Some(pos) = self.queue.iter().position(|r| r.id == id) else { return };
let r = self.queue.remove(pos).expect("found");
if !r.done {
self.backend.tts_cancel(&r.id);
}
if pos == 0 && self.playing {
self.playing = false;
self.sink.stop();
}
crate::debug_log!("play", "cancel id={} played={}", r.id, r.played);
self.events.push(PlaybackEvent::End(PlaybackEnd { id: r.id, played: r.played, cancelled: true,
failed: false }));
self.pump();
}
/// More text for an open request (an LLM answer that is still streaming).
pub fn continue_text(&mut self, id: &str, text: &str, more: bool) {
if self.queue.iter().any(|r| r.id == id && !r.done) {
@@ -302,6 +340,53 @@ mod tests {
assert_eq!(sent, vec![("첫 문장.".into(), true), (" 둘째 문장.".into(), false)]);
}
#[test]
fn an_adopted_answer_plays_the_brains_audio_without_sending_text() {
let (mut p, f) = setup();
let id = p.adopt();
assert!(f.0.borrow().sent.is_empty(), "the brain speaks it under this id");
p.audio(&id, 0, b("a0"));
p.done(&done(&id, false));
p.clip_ended();
assert_eq!(f.0.borrow().played, vec!["a0"]);
assert_eq!(p.take_events(), vec![PlaybackEvent::Start(id.clone()), end(&id, 1, false, false)]);
assert_ne!(p.adopt(), id, "ids never repeat");
}
#[test]
fn an_answer_with_no_text_fails_and_the_next_request_plays() {
let (mut p, f) = setup();
let id = p.adopt();
let c = p.say("b", false);
p.audio(&c, 0, b("b0"));
assert!(f.0.borrow().played.is_empty());
p.fail(&id);
assert_eq!(f.0.borrow().played, vec!["b0"]);
assert_eq!(p.take_events()[0], end(&id, 0, false, true));
}
#[test]
fn cancel_stops_one_request_and_leaves_the_others() {
let (mut p, f) = setup();
let a = p.say("a", true);
let c = p.say("b", false);
p.audio(&a, 0, b("a0"));
p.audio(&c, 0, b("b0"));
p.take_events();
p.cancel(&a);
assert_eq!(f.0.borrow().stops, 1);
assert_eq!(f.0.borrow().cancelled, vec![a.clone()]);
assert_eq!(f.0.borrow().played, vec!["a0", "b0"], "the next request plays at once");
assert_eq!(p.take_events(), vec![end(&a, 1, true, false), PlaybackEvent::Start(c.clone())]);
// A queued request that has not started is cancelled without touching the clip.
let d = p.say("d", false);
p.cancel(&d);
assert_eq!(f.0.borrow().stops, 1);
assert_eq!(p.take_events(), vec![end(&d, 0, true, false)]);
p.cancel("nope");
assert!(p.take_events().is_empty());
}
#[test]
fn a_request_the_worker_never_accepted_fails_without_blocking_the_next() {
let (mut p, f) = setup();

View File

@@ -6,6 +6,7 @@ use std::path::Path;
use serde_json::Value;
use tokio::sync::mpsc;
use crate::conversation::{self, Conversation};
use crate::discord::{CoreEvent, DiscordCore};
use crate::settings::load_settings;
use crate::worker_client::{WorkerClient, WorkerClientOptions};
@@ -54,7 +55,11 @@ pub async fn start_services(data_dir: &Path) -> Result<Services, Box<dyn std::er
}
});
let (core, events) = DiscordCore::new(settings, token, worker.clone(), worker_events);
let (calls, response) = (settings.call.clone(), settings.response.clone());
let (core, core_events) = DiscordCore::new(settings, token, worker.clone(), worker_events);
// Call detection and the response policy answer what is heard; every event still reaches `events`.
let (out, events) = mpsc::unbounded_channel();
tokio::spawn(conversation::run(Conversation::new(core.clone(), calls, response), core_events, out));
if let Err(e) = core.start().await {
worker.close();
worker_process.stop().await;

View File

@@ -129,6 +129,12 @@ pub enum WorkerEvent {
TtsAudio { id: String, seq: u32, pcm: Vec<u8> },
TtsDone(TtsDone),
ChatAction(ChatAction),
/// The brain's answer to `reply` (empty and `failed` when it gave none).
ReplyText { id: String, text: String, failed: bool },
/// Was the utterance said to Jarvis? (a failed judgement is a no)
Addressed { id: String, addressed: bool },
/// Candidate ids, most important first (empty when the ranking failed).
Ranked { id: String, order: Vec<String> },
Error(WorkerError),
}
@@ -301,6 +307,43 @@ impl WorkerClient {
"message_id": message.to_string()}));
}
// --- brain (voice_worker.spec.md "History and brain", conversation.spec.md) -------------------
/// Ask the brain to answer `user`. With `speak` the answer is spoken under `id` (its audio and
/// `tts_done` come like a TTS request's); it ends as failed when it cannot be sent, the brain gives
/// no answer, or the worker refuses it.
pub fn reply(&self, id: &str, user: u64, text: &str, speak: bool) -> bool {
if speak {
self.inner.state.lock().unwrap().open_tts.insert(id.to_owned());
}
let sent = self.send_json(json!({"type": "reply", "id": id, "user": user.to_string(), "text": text,
"via": "voice", "speak": speak}));
if !sent && speak {
self.end_failed(id);
}
sent
}
fn end_failed(&self, id: &str) {
if self.inner.state.lock().unwrap().open_tts.remove(id) {
let _ = self.inner.events.send(WorkerEvent::TtsDone(TtsDone { id: id.into(), chunks: 0, cancelled: false,
failed: true }));
}
}
/// Ask whether `text` was said to Jarvis (call mode `addressed`).
pub fn addressed(&self, id: &str, user: u64, text: &str) -> bool {
self.send_json(json!({"type": "addressed", "id": id, "user": user.to_string(), "text": text}))
}
/// Ask the brain to rank tied candidates `(id, user, text)` by importance.
pub fn rank(&self, id: &str, candidates: &[(String, u64, String)]) -> bool {
let list: Vec<Value> = candidates.iter()
.map(|(cid, user, text)| json!({"id": cid, "user": user.to_string(), "text": text}))
.collect();
self.send_json(json!({"type": "rank", "id": id, "candidates": list}))
}
/// Change STT settings now and for every later connection.
pub fn configure(&self, changes: Map<String, Value>) {
self.inner.state.lock().unwrap().stt.extend(changes.clone());
@@ -458,13 +501,36 @@ fn on_text(inner: &Inner, t: &str) {
"partial" => serde_json::from_value(v).ok().map(WorkerEvent::Partial),
"final" => serde_json::from_value(v).ok().map(WorkerEvent::Final),
"chat_action" => serde_json::from_value(v).ok().map(WorkerEvent::ChatAction),
"reply_text" => {
let id = v["id"].as_str().unwrap_or_default().to_owned();
let failed = v["failed"].as_bool().unwrap_or(true);
let text = v["text"].as_str().unwrap_or_default().to_owned();
// No answer means nothing will be spoken: end the speech the app is waiting for.
if failed && inner.state.lock().unwrap().open_tts.remove(&id) {
let _ = inner.events.send(WorkerEvent::ReplyText { id: id.clone(), text, failed });
let _ = inner.events.send(WorkerEvent::TtsDone(TtsDone { id, chunks: 0, cancelled: false, failed: true }));
return;
}
Some(WorkerEvent::ReplyText { id, text, failed })
}
"addressed_result" => Some(WorkerEvent::Addressed {
id: v["id"].as_str().unwrap_or_default().to_owned(),
addressed: v["addressed"].as_bool().unwrap_or(false) && !v["failed"].as_bool().unwrap_or(false),
}),
"rank_result" => Some(WorkerEvent::Ranked {
id: v["id"].as_str().unwrap_or_default().to_owned(),
order: if v["failed"].as_bool().unwrap_or(false) { vec![] } else {
v["order"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_owned)).collect())
.unwrap_or_default()
},
}),
"tts_done" => serde_json::from_value::<TtsDone>(v).ok().and_then(|d| {
inner.state.lock().unwrap().open_tts.remove(&d.id).then_some(WorkerEvent::TtsDone(d))
}),
"error" => serde_json::from_value::<WorkerError>(v).ok().map(|e| {
debug_log!("worker", "voice worker error {}", e.code);
// A request the worker refused outright never gets a tts_done.
if e.code == "tts_unavailable" {
if e.code == "tts_unavailable" || e.code == "brain_unavailable" {
if let Some(id) = &e.id {
if inner.state.lock().unwrap().open_tts.remove(id) {
let _ = inner.events.send(WorkerEvent::Error(e.clone()));