Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(cli): the window routes what the dial hears, and the router reads questions

0xdiego2583aecb4d272d
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index 7bea73388..3c72131b5 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -14,16 +14,19 @@ import { join } from 'node:path'
import { AuthSessionManager, readAuthSession } from '../lib/authSession.js'
import { registry, projectDisplayName, type RegisteredSession } from '../lib/registry.js'
import { fetchRelease, loadImage, shouldOffer } from './fwPush.js'
-import { routeVoiceTask, type RouterAgent } from '../lib/voiceRouter.js'
+import { routeVoiceTask, type RouterAgent, type RouterContinuity } from '../lib/voiceRouter.js'
import { env } from '../config/env.js'
import type { CableAgent, CableHost, CableMachine, CableMachineSource, RouteDecision } from './cableSession.js'
+import type { WindowRoute } from './windowRoute.js'
import { FleetError, type FleetMachine, type MachineFleet } from './machineFleet.js'
/** One completed turn's recap, as the mirror keeps them. */
export interface RecentTurn {
recap?: string
text?: string
+ /** What the USER asked on that turn. The topic lives here; the recap holds the answer. */
+ ask?: string
}
export interface CableHostWiring {
@@ -49,6 +52,8 @@ export interface CableHostWiring {
opened?: (machineId: string, agentId: string) => void
/** A finger on the dial's glass, in pieces, while it is down. */
scrolled?: (phase: 'down' | 'move' | 'up', dy: number, velocity: number) => void
+ /** Offer a spoken task to the desktop window's palette. Omitted when there is no window plumbing. */
+ routeInWindow?: (text: string, cmd?: string) => Promise<WindowRoute>
log: (line: string) => void
}
@@ -92,6 +97,10 @@ function chipsFromProfile(profile: string | null | undefined): { model?: string;
}
export class DaemonCableHost implements CableHost {
+ /** The last turn this daemon delivered, for [lastRouted]. In memory only: a conversation that spans a
+ * daemon restart is not one the five-minute window would have carried anyway. */
+ private lastTurn?: { agentId: string; at: number }
+
/**
* The machine whose agents are on the dial right now. Defaults to — and falls back to — the local one:
* it is the only machine that is certainly reachable, so it is the honest thing to land on.
@@ -526,12 +535,32 @@ export class DaemonCableHost implements CableHost {
return { ok: false, machine, reason: 'the last request to it did not come back' }
}
this.fleet!.sendTurn(machineId, agentId, text)
+ this.spokeTo(agentId)
return { ok: true }
}
this.wiring.sendTurn(agentId, text)
+ this.spokeTo(agentId)
return { ok: true }
}
+ /**
+ * Remember who this person is talking to.
+ *
+ * Recorded HERE because every path that actually delivers a turn passes through sendTurn — the
+ * window's palette, the dial naming a tile, and the router's own fallback — so there is one fact and
+ * one place it is written. Recorded only on a delivery that was accepted: a turn refused because its
+ * machine went deaf is not a conversation anybody is in the middle of.
+ */
+ private spokeTo(agentId: string): void {
+ if (agentId) this.lastTurn = { agentId, at: Date.now() }
+ }
+
+ /** Who the last delivered turn went to, and how long ago — the router's continuity signal. */
+ lastRouted(): RouterContinuity | undefined {
+ if (!this.lastTurn) return undefined
+ return { agentId: this.lastTurn.agentId, agoMs: Date.now() - this.lastTurn.at }
+ }
+
stopTurn(agentId: string): void {
if (!this.isLocalAgent(agentId)) { this.fleet!.stopTurn(this.machineOf(agentId), agentId); return }
this.wiring.stopTurn(agentId)
@@ -587,11 +616,13 @@ export class DaemonCableHost implements CableHost {
}
/** The last few turns, newest first, in the shape the dial's tile draws: a headline and a body. */
- async recentSummaries(agentId: string): Promise<Array<{ recap: string; text: string }>> {
+ async recentSummaries(agentId: string): Promise<Array<{ recap: string; text: string; ask: string }>> {
const raw = this.isLocalAgent(agentId)
? this.wiring.recent(agentId, 3)
: await this.fleet!.recentSummaries(this.machineOf(agentId), agentId)
- return raw.map((r) => ({ recap: r?.recap ?? '', text: r?.text ?? '' })).filter((s) => s.recap || s.text)
+ return raw
+ .map((r) => ({ recap: r?.recap ?? '', text: r?.text ?? '', ask: r?.ask ?? '' }))
+ .filter((s) => s.recap || s.text || s.ask)
}
async listModels(agentId: string): Promise<string[]> {
@@ -624,6 +655,24 @@ export class DaemonCableHost implements CableHost {
* machine is ALREADY running when the score cannot separate the top two. No key, no relay, no network —
* which is the whole reason voice on the cable does not inherit the hosted path's failure modes.
*/
+ /**
+ * Give the window first refusal on a spoken task.
+ *
+ * A pass-through by design: everything interesting — whether a window is even attached, the two-phase
+ * wait, the deadlines — belongs to the router in windowRoute.ts, which is testable without a socket.
+ * This exists so the session can ask through the same host it asks everything else through.
+ */
+ async routeInWindow(text: string, cmd?: string): Promise<WindowRoute> {
+ if (!this.wiring.routeInWindow) return { t: 'unavailable' }
+ try {
+ return await this.wiring.routeInWindow(text, cmd)
+ } catch (err) {
+ // Never let a broken window path swallow a sentence a person spoke: fall back to routing here.
+ this.wiring.log(`cable: the window route failed (${(err as Error).message}) — routing here`)
+ return { t: 'unavailable' }
+ }
+ }
+
async route(transcript: string, agents: CableAgent[]): Promise<RouteDecision> {
// Each agent's recaps come from ITS OWN machine — recentSummaries routes by agentId. Scored against
// the wrong machine's history, a spoken turn is routed by what some other computer's agents were last
@@ -636,12 +685,16 @@ export class DaemonCableHost implements CableHost {
engine: a.engine,
machine: a.machine,
+ // THE QUESTION, not the answer. A recap summarises what the agent replied — "1945." is a correct
+ // recap and a useless routing signal, and the next question about the same conversation matches
+ // nothing in it. The ask carries the topic, so it wins when there is one; the recap stands in for
+ // turns recorded before this was stored, and for agents on other machines.
recentSummary: (await this.recentSummaries(a.id))
- .map((r) => r.recap || r.text || '')
+ .map((r) => r.ask || r.recap || r.text || '')
.filter(Boolean)
.join(' · '),
})))
- const decision = await routeVoiceTask(transcript, candidates)
+ const decision = await routeVoiceTask(transcript, candidates, undefined, undefined, this.lastRouted())
return { agentId: decision.agentId, confidence: decision.confidence, reason: decision.reason }
}
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.ts
index c32838bb0..7457f9310 100644
--- a/cli/src/cable/cableSession.spec.ts
+++ b/cli/src/cable/cableSession.spec.ts
@@ -618,6 +618,98 @@ describe('cable session', () => {
await session.stop()
})
+ it('lets the window route a spoken task, and does NOT send it a second time', async () => {
+ // The window DELIVERS what its palette picks. Sending here as well is one sentence arriving twice.
+ const route = vi.fn()
+ const routeInWindow = vi.fn(async () => ({ t: 'sent' as const, agentId: 'a2' }))
+ const host = makeHost({ route, routeInWindow })
+ const { session, port } = await connect(host)
+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })
+ await settle()
+ port.sent.length = 0
+
+ port.say({ t: 'voice.begin', lang: 'en' })
+ port.pcm(Buffer.alloc(3200, 7))
+ port.say({ t: 'voice.end' })
+ await vi.waitFor(() => expect(port.types()).toContain('voice.transcript'))
+
+ expect(routeInWindow).toHaveBeenCalledWith('fix the login screen', undefined)
+ expect(host.sendTurn).not.toHaveBeenCalled()
+ expect(route).not.toHaveBeenCalled()
+ // The dial is still told where the words went, so it lands on that tile and drops the overlay.
+ expect(port.sent.at(-1)).toMatchObject({ t: 'voice.transcript', agentId: 'a2', agentName: 'Device firmware voice' })
+ await session.stop()
+ })
+
+ it('carries the command word to the window, so /goal stays a goal', async () => {
+ const routeInWindow = vi.fn(async () => ({ t: 'sent' as const, agentId: 'a1' }))
+ const host = makeHost({ routeInWindow })
+ const { session, port } = await connect(host)
+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })
+ await settle()
+
+ port.say({ t: 'voice.begin', lang: 'en', cmd: 'goal' })
+ port.pcm(Buffer.alloc(3200, 7))
+ port.say({ t: 'voice.end' })
+ await vi.waitFor(() => expect(routeInWindow).toHaveBeenCalled())
+
+ expect(routeInWindow).toHaveBeenCalledWith('fix the login screen', 'goal')
+ await session.stop()
+ })
+
+ it('sends nothing when a person closes the palette, and says so', async () => {
+ const route = vi.fn()
+ const host = makeHost({ route, routeInWindow: async () => ({ t: 'cancelled' as const }) })
+ const { session, port } = await connect(host)
+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })
+ await settle()
+ port.sent.length = 0
+
+ port.say({ t: 'voice.begin', lang: 'en' })
+ port.pcm(Buffer.alloc(3200, 7))
+ port.say({ t: 'voice.end' })
+ await vi.waitFor(() => expect(port.types()).toContain('voice.error'))
+
+ // Cancelling must not fall through to routing here — that would deliver what the person just refused.
+ expect(host.sendTurn).not.toHaveBeenCalled()
+ expect(route).not.toHaveBeenCalled()
+ await session.stop()
+ })
+
+ it('will not race a pick that is still coming when the window goes quiet', async () => {
+ const route = vi.fn()
+ const host = makeHost({ route, routeInWindow: async () => ({ t: 'abandoned' as const }) })
+ const { session, port } = await connect(host)
+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })
+ await settle()
+ port.sent.length = 0
+
+ port.say({ t: 'voice.begin', lang: 'en' })
+ port.pcm(Buffer.alloc(3200, 7))
+ port.say({ t: 'voice.end' })
+ await vi.waitFor(() => expect(port.types()).toContain('voice.error'))
+
+ expect(host.sendTurn).not.toHaveBeenCalled()
+ expect(route).not.toHaveBeenCalled()
+ await session.stop()
+ })
+
+ it('routes here when no window is listening', async () => {
+ const host = makeHost({ routeInWindow: async () => ({ t: 'unavailable' as const }) })
+ const { session, port } = await connect(host)
+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })
+ await settle()
+
+ port.say({ t: 'voice.begin', lang: 'en' })
+ port.pcm(Buffer.alloc(3200, 7))
+ port.say({ t: 'voice.end' })
+ await vi.waitFor(() => expect(host.sendTurn).toHaveBeenCalled())
+
+ // The dial keeps working with the window shut — this is the whole reason the old router stays.
+ expect(host.sendTurn).toHaveBeenCalledWith('a1', 'fix the login screen')
+ await session.stop()
+ })
+
it('sends a voice turn straight to the agent the dial named', async () => {
const route = vi.fn()
const host = makeHost({ route })
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index 618ff9a11..5351df7a5 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -153,6 +153,9 @@ export interface CableMachine {
/** Why the list is as short as it is. The dial renders this, instead of drawing an empty wheel. */
export type CableMachineSource = 'backend' | 'local' | 'signed-out'
+export type { WindowRoute } from './windowRoute.js'
+import type { WindowRoute } from './windowRoute.js'
+
export interface RouteDecision {
agentId: string
confidence: number
@@ -213,6 +216,16 @@ export interface CableHost {
transcribe(pcm: Buffer, sampleRate: number, lang: string): Promise<string>
/** Which agent the words belong to. Scored locally first; only a genuine tie should cost a network call. */
route(transcript: string, agents: CableAgent[]): Promise<RouteDecision>
+ /**
+ * Offer the words to the desktop window FIRST, and let its palette decide.
+ *
+ * The window's ⌘B router is the one that gets looked after — fifteen candidates in rail order, recaps
+ * cut to sixty characters, a twenty-second budget, and a picker when it is not sure. [route] is the
+ * same idea a version behind, so this is asked first and that is the fallback rather than the default.
+ *
+ * Optional: a host with no window to ask simply omits it, and voice behaves exactly as it always has.
+ */
+ routeInWindow?(text: string, cmd?: string): Promise<WindowRoute>
/** The runtime model/effort catalog for one agent, as opaque profile ids the dial groups and shows. */
listModels(agentId: string): Promise<string[]>
/** One agent's last turn summaries, newest first — what a reattached dial needs to redraw its tiles. */
@@ -882,6 +895,42 @@ export class CableSession {
let agentName = ''
const agents = await this.host.listAgents()
if (!agentId) {
+ // NOBODY NAMED, SO THE WINDOW DECIDES. It opens its palette with these words already in the field
+ // and runs the route a typed task would have run — the same fifteen candidates, the same trimmed
+ // recaps, the same threshold, and the same picker when the answer is not good enough to act on.
+ //
+ // The window DELIVERS what it picks, so there is nothing left to send here: a `sent` outcome is
+ // already on its way to an agent, and calling sendTurn on it would deliver the sentence twice.
+ const inWindow = this.host.routeInWindow
+ ? await this.host.routeInWindow(transcript, turn.cmd)
+ : ({ t: 'unavailable' } as const)
+ if (inWindow.t === 'sent') {
+ this.host.log(`cable: the window routed the spoken task → ${inWindow.agentId.slice(0, 8)}`)
+ await this.send({
+ t: 'voice.transcript',
+ routeId: '',
+ text: transcript,
+ agentId: inWindow.agentId,
+ // Only a name the DIAL's own list knows: it draws this, and an agent the window reached on a
+ // machine the carousel has not been told about yet has no tile here to put a name on. The ring
+ // that follows the window's focus brings both along a moment later.
+ agentName: agents.find((a) => a.id === inWindow.agentId)?.name ?? '',
+ needsConfirm: false,
+ })
+ return
+ }
+ if (inWindow.t === 'cancelled') {
+ // A person closed the palette. Nothing was sent and nothing should be — but the dial is still
+ // showing the sending overlay, so it has to be told, or it sits there until its own watchdog.
+ await this.send({ t: 'voice.error', message: 'Cancelled in the window' })
+ return
+ }
+ if (inWindow.t === 'abandoned') {
+ // It took the words and went quiet. Routing here now would race a pick that may still be coming,
+ // and two turns from one sentence is worse than none — so say where the words went instead.
+ await this.send({ t: 'voice.error', message: 'Still waiting on the window' })
+ return
+ }
try {
const decision = await this.host.route(transcript, agents)
agentId = decision.agentId
diff --git a/cli/src/cable/windowRoute.spec.ts b/cli/src/cable/windowRoute.spec.ts
new file mode 100644
index 000000000..5f7149fb5
--- /dev/null
+++ b/cli/src/cable/windowRoute.spec.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from 'vitest'
+import { ANSWER_MS, TAKEN_MS, createWindowRouter } from './windowRoute.js'
+
+/** A hand-wound clock: every armed timer is kept so a test can fire exactly the one it means. */
+function harness(opts: { hasWindow?: boolean } = {}) {
+ const timers: Array<{ fn: () => void; ms: number; cancelled: boolean }> = []
+ const sent: Array<{ voiceId: string; text: string; cmd: string }> = []
+ const logs: string[] = []
+ const router = createWindowRouter({
+ hasWindow: () => opts.hasWindow !== false,
+ send: (voiceId, text, cmd) => sent.push({ voiceId, text, cmd }),
+ log: (line) => logs.push(line),
+ setTimer: (fn, ms) => {
+ const entry = { fn, ms, cancelled: false }
+ timers.push(entry)
+ return { cancel: () => { entry.cancelled = true } }
+ },
+ })
+ /** Fire the newest timer still armed — the only one the module ever intends to be live. */
+ const fireLive = () => {
+ const live = [...timers].reverse().find((t) => !t.cancelled)
+ if (!live) throw new Error('no live timer')
+ live.fn()
+ }
+ const liveMs = () => [...timers].reverse().find((t) => !t.cancelled)?.ms
+ return { router, sent, logs, timers, fireLive, liveMs }
+}
+
+describe('createWindowRouter', () => {
+ it('does not even ask when no window is attached', async () => {
+ const h = harness({ hasWindow: false })
+ await expect(h.router.ask('fix the webhook')).resolves.toEqual({ t: 'unavailable' })
+ expect(h.sent).toEqual([])
+ expect(h.router.pending()).toBe(0)
+ })
+
+ it('sends the task, with the command word alongside it', async () => {
+ const h = harness()
+ void h.router.ask('tidy the tests', 'goal')
+ expect(h.sent).toHaveLength(1)
+ expect(h.sent[0].text).toBe('tidy the tests')
+ expect(h.sent[0].cmd).toBe('goal')
+ expect(h.sent[0].voiceId).not.toBe('')
+ })
+
+ it('falls back when nobody acks — an old window build must behave like no window at all', async () => {
+ const h = harness()
+ const answer = h.router.ask('fix the webhook')
+ expect(h.liveMs()).toBe(TAKEN_MS)
+ h.fireLive()
+ await expect(answer).resolves.toEqual({ t: 'unavailable' })
+ expect(h.router.pending()).toBe(0)
+ })
+
+ it('gives a window that acked the LONG deadline, not the short one', async () => {
+ const h = harness()
+ const answer = h.router.ask('fix the webhook')
+ const voiceId = h.sent[0].voiceId
+ h.router.reply(voiceId, { t: 'taken' })
+ // The short timer is gone and the live deadline is now the human-sized one.
+ expect(h.liveMs()).toBe(ANSWER_MS)
+ h.fireLive()
+ // ABANDONED, never `unavailable`: routing here now would race the pick the person is still making.
+ await expect(answer).resolves.toEqual({ t: 'abandoned' })
+ })
+
+ it('carries back the agent the window sent to', async () => {
+ const h = harness()
+ const answer = h.router.ask('fix the webhook')
+ h.router.reply(h.sent[0].voiceId, { t: 'taken' })
+ h.router.reply(h.sent[0].voiceId, { t: 'sent', agentId: 'agent-7' })
+ await expect(answer).resolves.toEqual({ t: 'sent', agentId: 'agent-7' })
+ expect(h.router.pending()).toBe(0)
+ })
+
+ it('treats a closed palette as cancelled, and sends nothing', async () => {
+ const h = harness()
+ const answer = h.router.ask('fix the webhook')
+ h.router.reply(h.sent[0].voiceId, { t: 'taken' })
+ h.router.reply(h.sent[0].voiceId, { t: 'cancelled' })
+ await expect(answer).resolves.toEqual({ t: 'cancelled' })
+ })
+
+ it('reads a `sent` with no agent as a cancel rather than delivering to nobody', async () => {
+ const h = harness()
+ const answer = h.router.ask('fix the webhook')
+ h.router.reply(h.sent[0].voiceId, { t: 'sent', agentId: '' })
+ await expect(answer).resolves.toEqual({ t: 'cancelled' })
+ })
+
+ it('can answer without acking first — the ack is a deadline, not a gate', async () => {
+ const h = harness()
+ const answer = h.router.ask('fix the webhook')
+ h.router.reply(h.sent[0].voiceId, { t: 'sent', agentId: 'agent-2' })
+ await expect(answer).resolves.toEqual({ t: 'sent', agentId: 'agent-2' })
+ })
+
+ it('ignores a reply that arrives after the request is settled', async () => {
+ const h = harness()
+ const answer = h.router.ask('fix the webhook')
+ const voiceId = h.sent[0].voiceId
+ h.router.reply(voiceId, { t: 'sent', agentId: 'agent-2' })
+ await answer
+ expect(() => h.router.reply(voiceId, { t: 'sent', agentId: 'agent-9' })).not.toThrow()
+ expect(h.router.pending()).toBe(0)
+ })
+
+ it('ignores a reply for an id it never issued', () => {
+ const h = harness()
+ expect(() => h.router.reply('nope', { t: 'taken' })).not.toThrow()
+ })
+
+ it('lets the second window ack without pushing the deadline out again', async () => {
+ const h = harness()
+ const answer = h.router.ask('fix the webhook')
+ const voiceId = h.sent[0].voiceId
+ h.router.reply(voiceId, { t: 'taken' })
+ const armed = h.timers.filter((t) => !t.cancelled).length
+ h.router.reply(voiceId, { t: 'taken' }) // a second window, opening its own palette
+ expect(h.timers.filter((t) => !t.cancelled).length).toBe(armed)
+ // …and the first real answer still settles it exactly once.
+ h.router.reply(voiceId, { t: 'sent', agentId: 'agent-1' })
+ h.router.reply(voiceId, { t: 'cancelled' })
+ await expect(answer).resolves.toEqual({ t: 'sent', agentId: 'agent-1' })
+ })
+
+ it('keeps two spoken tasks apart', async () => {
+ const h = harness()
+ const first = h.router.ask('one')
+ const second = h.router.ask('two')
+ expect(h.router.pending()).toBe(2)
+ h.router.reply(h.sent[1].voiceId, { t: 'sent', agentId: 'b' })
+ h.router.reply(h.sent[0].voiceId, { t: 'sent', agentId: 'a' })
+ await expect(first).resolves.toEqual({ t: 'sent', agentId: 'a' })
+ await expect(second).resolves.toEqual({ t: 'sent', agentId: 'b' })
+ })
+})
diff --git a/cli/src/cable/windowRoute.ts b/cli/src/cable/windowRoute.ts
new file mode 100644
index 000000000..0d4349488
--- /dev/null
+++ b/cli/src/cable/windowRoute.ts
@@ -0,0 +1,168 @@
+/**
+ * Hand a spoken task to the desktop window and wait for what it decided.
+ *
+ * WHY THIS EXISTS AT ALL. The dial used to pick the agent itself, with a copy of the router that never
+ * got the fixes the window's ⌘B palette did: it weighed the whole agent list instead of the first
+ * fifteen, spent every recap at full length instead of sixty characters, ran on a 12-second budget
+ * instead of twenty — and, worst of the four, it always sent. An unsure route on the dial was still a
+ * route, delivered to whichever agent scored highest, with nothing on the screen to say the machine had
+ * guessed. The window can hold the same answer up and ask. So it decides now, and the dial is a
+ * microphone with a screen.
+ *
+ * TWO FRAMES BACK, NOT ONE, and that is the whole design here. A single answer cannot separate "no
+ * window is listening" from "the window is listening and a person is still reading the options" — and
+ * those need opposite handling: the first must fall back to routing here, the second must NOT, because
+ * falling back sends the turn to one agent while the person is about to send it to another. So the
+ * window acks `taken` the moment its palette owns the words, and answers `sent`/`cancelled` when it is
+ * done. No ack inside [TAKEN_MS] means nobody is there — including an older window build that has never
+ * heard of any of this, which is exactly the rollout case that has to keep working.
+ */
+
+/** What the window did with the words. */
+export type WindowRoute =
+ /** It delivered them. The turn is ALREADY on its way — do not send it again here. */
+ | { t: 'sent'; agentId: string }
+ /** A person closed the palette without choosing. Nothing was sent, and nothing should be. */
+ | { t: 'cancelled' }
+ /** Nobody took it: no window, or one too old to understand. Route here instead. */
+ | { t: 'unavailable' }
+ /** It took the words and never came back. Say so; do NOT route here, or the pick still coming lands second. */
+ | { t: 'abandoned' }
+
+/** What the window says back, in the order it says it. */
+export type WindowVoiceReply =
+ | { t: 'taken' }
+ | { t: 'sent'; agentId: string }
+ | { t: 'cancelled' }
+
+/**
+ * How long a window has to say it took the task.
+ *
+ * Short on purpose: this is the delay a person waits through, holding a dial they just spoke into, ONLY
+ * when the answer is going to be "nobody is home" — the palette acks as soon as it is built. Long enough
+ * to survive a busy frame on the window's isolate, short enough that the fallback still feels immediate.
+ */
+export const TAKEN_MS = 2_000
+
+/**
+ * How long the window then has to decide.
+ *
+ * SIXTY SECONDS BECAUSE THAT IS THE DIAL'S OWN NUMBER — `VOICE_ROUTE_WAIT_MS` in the firmware, after
+ * which it drops the sending overlay on its own. Waiting past it would leave this side hoping for an
+ * answer the dial has already given up on, and the person looking at a screen that moved on. It is also
+ * far past the 20s the classifier can spend, so everything but a human reading the options fits inside.
+ */
+export const ANSWER_MS = 60_000
+
+export interface WindowRouterWiring {
+ /** True while a desktop window on this computer is attached over loopback. */
+ hasWindow: () => boolean
+ /** Push the request to every attached window. */
+ send: (voiceId: string, text: string, cmd: string) => void
+ log: (line: string) => void
+ /** Injected so tests do not spend real seconds. */
+ now?: () => number
+ setTimer?: (fn: () => void, ms: number) => { cancel: () => void }
+}
+
+export interface WindowRouter {
+ /** Ask the window to route (and send) these words. Never rejects — a failure is one of the outcomes. */
+ ask: (text: string, cmd?: string) => Promise<WindowRoute>
+ /** A window answered. Unknown ids are ignored: a late reply to a request already settled is not an error. */
+ reply: (voiceId: string, reply: WindowVoiceReply) => void
+ /** Open requests, for tests and for the shutdown path. */
+ pending: () => number
+}
+
+interface Waiter {
+ taken: boolean
+ settle: (route: WindowRoute) => void
+ timer: { cancel: () => void }
+}
+
+function defaultTimer(fn: () => void, ms: number): { cancel: () => void } {
+ const handle = setTimeout(fn, ms)
+ // Never hold the process open for a window that is not going to answer.
+ handle.unref?.()
+ return { cancel: () => clearTimeout(handle) }
+}
+
+let seq = 0
+
+export function createWindowRouter(wiring: WindowRouterWiring): WindowRouter {
+ const setTimer = wiring.setTimer ?? defaultTimer
+ const waiters = new Map<string, Waiter>()
+
+ const finish = (voiceId: string, route: WindowRoute): void => {
+ const waiter = waiters.get(voiceId)
+ if (!waiter) return
+ waiters.delete(voiceId)
+ waiter.timer.cancel()
+ waiter.settle(route)
+ }
+
+ return {
+ ask: (text, cmd) => {
+ // Asked BEFORE anything is allocated: with no window there is nothing to wait for, and the caller
+ // routes it itself in the same tick the dial finished uploading.
+ if (!wiring.hasWindow()) {
+ wiring.log('cable: no window attached — routing the spoken task here')
+ return Promise.resolve<WindowRoute>({ t: 'unavailable' })
+ }
+ const voiceId = `v${Date.now().toString(36)}${(seq++).toString(36)}`
+ return new Promise<WindowRoute>((resolve) => {
+ const waiter: Waiter = {
+ taken: false,
+ settle: resolve,
+ // ONE timer, re-armed on the ack rather than two running at once: the deadline that matters
+ // changes when the window speaks up, and a stale second timer is how a settled request gets
+ // settled again.
+ timer: setTimer(() => {
+ const held = waiters.get(voiceId)
+ if (!held) return
+ waiters.delete(voiceId)
+ if (held.taken) {
+ wiring.log(`cable: the window took the spoken task and never answered (${ANSWER_MS / 1000}s)`)
+ held.settle({ t: 'abandoned' })
+ } else {
+ wiring.log('cable: no window answered in time — routing the spoken task here')
+ held.settle({ t: 'unavailable' })
+ }
+ }, TAKEN_MS),
+ }
+ waiters.set(voiceId, waiter)
+ wiring.send(voiceId, text, cmd ?? '')
+ })
+ },
+
+ reply: (voiceId, reply) => {
+ const waiter = waiters.get(voiceId)
+ if (!waiter) return
+ if (reply.t === 'taken') {
+ // FIRST ONE WINS. Every attached window opens a palette, and only the one the person actually
+ // used will answer; the rest are told to stand down when this one does. Re-acking here would
+ // keep pushing the deadline out for as long as windows keep arriving.
+ if (waiter.taken) return
+ waiter.taken = true
+ waiter.timer.cancel()
+ waiter.timer = setTimer(() => {
+ const held = waiters.get(voiceId)
+ if (!held) return
+ waiters.delete(voiceId)
+ wiring.log(`cable: the window took the spoken task and never answered (${ANSWER_MS / 1000}s)`)
+ held.settle({ t: 'abandoned' })
+ }, ANSWER_MS)
+ wiring.log('cable: the window took the spoken task')
+ return
+ }
+ if (reply.t === 'sent') {
+ if (!reply.agentId) { finish(voiceId, { t: 'cancelled' }); return }
+ finish(voiceId, { t: 'sent', agentId: reply.agentId })
+ return
+ }
+ finish(voiceId, { t: 'cancelled' })
+ },
+
+ pending: () => waiters.size,
+ }
+}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 178c7df88..08c130c91 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -95,6 +95,7 @@ import { AutonomousDeviceService } from './lib/autonomous-device/service.js'
import { autonomousDeviceLocalRequest } from './lib/autonomous-device/localApi.js'
import { runAutonomousDeviceCommand } from './lib/autonomous-device/command.js'
import { attachLocalWsServer, LOCAL_WS_PATH, LOCAL_WS_PROTOCOL_VERSION } from './localWsServer.js'
+import { createWindowRouter } from './cable/windowRoute.js'
import { RemoteRelayPool } from './lib/remoteRelay.js'
import { TERMINAL_BINARY_VERSION } from './lib/terminalBinary.js'
import { foldTranscript, lastTurnTextFromRawLines, lineToEvents, newTurnState, type LiveEvent, type TurnState } from './lib/normalize.js'
@@ -2818,6 +2819,22 @@ async function runForeground(session: AuthSession): Promise<void> {
relayIdentityStore.getIdentity(),
new MachinePeerStore(),
)
+ // Spoken tasks go to the WINDOW to be routed, not to the copy of the router in this process.
+ //
+ // Built here because both ends need it: the local socket hands it the window's replies, and the cable
+ // host (built much further down) asks through it. See cable/windowRoute.ts for the two-phase wait and
+ // why "no window" and "a person is still choosing" must not be the same answer.
+ const windowRouter = createWindowRouter({
+ hasWindow: () => backend.hasLocalClient(),
+ send: (voiceId, text, cmd) => {
+ // sendLocal, never send: this asks the window in front of the dial to open a palette. Fanning it
+ // out to the web audience would pop one open on a computer nobody is sitting at.
+ backend.sendLocal({ type: 'voice_route_request', payload: { voiceId, text, ...(cmd ? { cmd } : {}) } })
+ console.log(`[route] voice → the window · ${Buffer.byteLength(text, 'utf8')} bytes${cmd ? ` · /${cmd}` : ''}`)
+ },
+ log: (line) => console.log(`[cable] ${line}`),
+ })
+
const localWsServer = attachLocalWsServer(hookServer, {
// The window and the dial are one desk: opening an agent in the app brings the dial to it, switching
// the dial's machine first when the app moved to another one.
@@ -2905,22 +2922,45 @@ async function runForeground(session: AuthSession): Promise<void> {
// list of ten into a 12-second timeout while eight had answered in nine — the agents cost little,
// their recent work cost a lot. Sixty characters still separates "webhook retry fix" from
// "round 3 standings", which is all the router is being asked to tell apart.
+ // THE QUESTION FIRST, and the recap only when there is no question on record.
+ //
+ // A recap describes what the AGENT REPLIED. Measured on this desk: "which year did the second
+ // world war end" recapped to "1945." — correct, and carrying not one word the next question
+ // about the same conversation could match. The router was being handed answers and asked to
+ // recognise topics. The ask is the topic, costs the same sixty characters, and needs no extra
+ // room in a prompt that already times out often enough to matter.
recentSummary: (await host.recentSummaries(agent.id))
- .map((turn) => (turn.recap || turn.text || '').replace(/\s+/g, ' ').trim().slice(0, ROUTE_RECAP_CHARS))
+ .map((turn) => (turn.ask || turn.recap || turn.text || '').replace(/\s+/g, ' ').trim().slice(0, ROUTE_RECAP_CHARS))
.filter(Boolean)
.join(' · '),
})))
// 20s, not the shared 12s: this path answers a person watching a spinner in their own window, and
// it is under nobody else's deadline — the app's rpc waits longer still. The dial and the web keep
// the default; overshooting a deadline they DO have would turn a late answer into no answer.
- const decision = await routeVoiceTask(text, candidates, undefined, ROUTE_CLASSIFY_APP_MS)
+ // …and WHO THIS PERSON WAS JUST TALKING TO. Nothing else in the prompt can supply it: a follow-up
+ // question names no agent and often shares no words with the first one, and the recap of the turn
+ // it follows may not even exist yet — the answer is still being written while the next question
+ // is being asked.
+ const decision = await routeVoiceTask(text, candidates, undefined, ROUTE_CLASSIFY_APP_MS, host.lastRouted?.())
const named = (id: string) => candidates.find((agent) => agent.id === id)
// The runners-up in the ROUTER's order when it gave one, and the list's own order when it did not.
// A picker that has to ask "which agent" is showing a ranking either way; this decides whose.
const ranking = (decision.scores ?? []).filter((score) => score.agentId !== decision.agentId)
- const others = ranking.length
- ? ranking.map((score) => named(score.agentId)).filter((agent): agent is RouterAgent => !!agent).slice(0, 2)
- : candidates.filter((agent) => agent.id !== decision.agentId).slice(0, 2)
+ // EVERY AGENT THAT WAS WEIGHED, not the best two.
+ //
+ // The picker used to offer three rows — the pick and two runners-up — on the theory that a person
+ // who has to be asked wants the shortlist. They do not: when the router is unsure the right agent
+ // is often the one it ranked fourth, and a shortlist that cannot show it turns a question into a
+ // dead end, with no way out but Esc and typing the task again somewhere else.
+ //
+ // Ranked first where the router said something, then everything else it looked at in rail order,
+ // so the list stays the one the person is reading on screen. Nothing is dropped: the cap that
+ // matters is ROUTE_MAX_CANDIDATES above, and `weighed` already says what it did.
+ const rankedOthers = ranking
+ .map((score) => named(score.agentId))
+ .filter((agent): agent is RouterAgent => !!agent)
+ const listed = new Set([decision.agentId, ...rankedOthers.map((agent) => agent.id)])
+ const others = [...rankedOthers, ...candidates.filter((agent) => !listed.has(agent.id))]
const fitOf = (id: string) => id === decision.agentId
? decision.confidence
: ranking.find((score) => score.agentId === id)?.confidence ?? 0
@@ -2975,6 +3015,7 @@ async function runForeground(session: AuthSession): Promise<void> {
+ (sent.ok ? '' : ` · REFUSED: ${sent.reason}${sent.machine ? ` (${sent.machine})` : ''}`))
return sent
},
+ onVoiceRouteReply: (voiceId, reply) => windowRouter.reply(voiceId, reply),
machineId: backend.machineId,
backend,
relayPool,
@@ -3982,6 +4023,8 @@ async function runForeground(session: AuthSession): Promise<void> {
focused: (machineId, agentId, edge) =>
backend.sendLocal({ type: 'dial_focus', payload: { machineId, agentId, ...(edge ? { edge } : {}) } }),
scrolled: (phase, dy, velocity) => backend.sendLocal({ type: 'dial_scroll', payload: { phase, dy, velocity } }),
+ // Words spoken on the overview belong to whichever agent the window's palette picks.
+ routeInWindow: (text, cmd) => windowRouter.ask(text, cmd),
log: (line) => console.log(`[cable] ${line}`),
}, fleet)
cableHostRef = cableHost
diff --git a/cli/src/lib/commander.spec.ts b/cli/src/lib/commander.spec.ts
index bc38b32e2..d6c6a9bf0 100644
--- a/cli/src/lib/commander.spec.ts
+++ b/cli/src/lib/commander.spec.ts
@@ -19,6 +19,34 @@ describe('CommanderMirror recap events', () => {
rmSync(dataDir, { recursive: true, force: true })
})
+ it('keeps what the user ASKED, not only what the agent answered', async () => {
+ // The router reads these to decide where a spoken follow-up belongs, and a recap answers the wrong
+ // question for that: measured on this desk, "Chiến tranh thế giới thứ hai kết thúc vào năm nào?"
+ // recapped to "1945." — a correct summary of the reply carrying not one word of the subject. Ask
+ // about the FIRST world war a minute later and nothing connects the two.
+ const mirror = new CommanderMirror({
+ send: () => {},
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => '1945.',
+ dataDir,
+ })
+
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'Chiến tranh thế giới thứ hai kết thúc vào năm nào?' } },
+ { type: 'text_delta', payload: { content: 'The war ended in 1945.' } },
+ { type: 'turn_ended', payload: {} },
+ ] as LiveEvent[], 'session-ask')
+
+ await vi.runAllTimersAsync()
+ await Promise.resolve()
+
+ const turn = mirror.recent('session-ask', 3)[0]
+ expect(turn.ask).toBe('Chiến tranh thế giới thứ hai kết thúc vào năm nào?')
+ // The recap is still exactly what it was — this adds a field, it does not change one.
+ expect(turn.recap).toBe('1945.')
+ })
+
it('fans a TodoWrite out to the device as a todo list, whatever engine produced it', () => {
// The device renders the checklist from `todos:[{c,s}]` folded onto a processing frame — nothing else
// carries it. Every engine reaches this through the SAME shape (`input.todos[{content,status}]`), which
diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.ts
index d7adf9b24..124b64c77 100644
--- a/cli/src/lib/commander.ts
+++ b/cli/src/lib/commander.ts
@@ -209,6 +209,10 @@ const RECENT_TURNS = 3
*/
const FULL_TEXT_MAX_BYTES = 8192
+/** How much of the user's own words is kept per turn. Long enough for the topic, short enough that three
+ * of them per agent still fit a router prompt that already carries fifteen agents. */
+const ASK_MAX_CHARS = 200
+
/**
* Truncate to a byte budget without splitting a character.
*
@@ -247,15 +251,30 @@ export class CommanderMirror {
* aloud in another room.
*/
private fullTexts = new Map<string, string[]>()
+ /**
+ * What the USER ASKED on each of those turns, newest first and index-aligned with `history`.
+ *
+ * A fourth file, for the same reason as the third: the others keep their shape and a rollback simply
+ * never looks here.
+ *
+ * It exists because a recap answers the wrong question for routing. Recaps summarise what the AGENT
+ * REPLIED — a turn that asked "which year did the second world war end" is recapped, correctly and
+ * uselessly, as "1945." Ask the same agent about the FIRST world war a minute later and nothing in
+ * that recap connects the two, so the router cannot see a conversation it is plainly in the middle
+ * of. The question carries the topic; the answer usually does not.
+ */
+ private asks = new Map<string, string[]>()
private file: string
private historyFile: string
private fullTextFile: string
+ private askFile: string
private saveTimer: NodeJS.Timeout | null = null
constructor(private opts: CommanderMirrorOpts) {
this.file = join(opts.dataDir, 'summaries.json')
this.historyFile = join(opts.dataDir, 'summaries-history.json')
this.fullTextFile = join(opts.dataDir, 'summaries-fulltext.json')
+ this.askFile = join(opts.dataDir, 'summaries-asks.json')
this.load()
}
@@ -594,6 +613,9 @@ export class CommanderMirror {
// Recorded in the SAME branch as the summary, so the two arrays cannot drift out of step —
// a turn that produced no summary produces no row in either.
this.rememberFullText(sessionId, text)
+ // Recorded in the SAME branch as the summary and the full text, so all three arrays stay
+ // index-aligned: a turn either contributes a row to each or to none.
+ this.rememberAsk(sessionId, userMessage)
this.saveSoon()
const { recap, body } = splitSummary(summary)
this.trace(sessionId, `${sid} done in ${ms}ms · recap="${recap}" · bodyLen=${body.length}`)
@@ -666,7 +688,7 @@ export class CommanderMirror {
* Falls back to the single latest summary when the history is empty, so the recaps already on disk from
* before this existed are usable on the first run rather than after three more turns.
*/
- recent(sessionId: string, n = 2): Array<{ kind: string; text: string; recap?: string; fullText?: string }> {
+ recent(sessionId: string, n = 2): Array<{ kind: string; text: string; recap?: string; fullText?: string; ask?: string }> {
const want = Math.max(1, n)
const stored = this.history.get(sessionId) ?? []
const latest = this.summaries.get(sessionId)
@@ -674,16 +696,17 @@ export class CommanderMirror {
const usingHistory = stored.length > 0
const all = usingHistory ? stored : latest ? [latest] : []
const fulls = this.fullTexts.get(sessionId) ?? []
+ const asks = this.asks.get(sessionId) ?? []
return all
.slice(0, want)
// PAIRED BEFORE FILTERING, not after. The filter below drops empty summaries, and dropping them
// from one array while reading the other by position is how a turn ends up carrying the previous
// turn's answer — wrong in the one way nobody would think to check.
- .map((summary, at) => ({ summary, full: fulls[usingHistory ? at : 0] }))
+ .map((summary, at) => ({ summary, full: fulls[usingHistory ? at : 0], ask: asks[usingHistory ? at : 0] }))
.filter(({ summary }) => summary && summary.trim())
- .map(({ summary, full }) => {
+ .map(({ summary, full, ask }) => {
const { recap, body } = splitSummary(summary)
- return { kind: 'summary', text: body || recap, recap, ...(full ? { fullText: full } : {}) }
+ return { kind: 'summary', text: body || recap, recap, ...(full ? { fullText: full } : {}), ...(ask ? { ask } : {}) }
})
}
@@ -692,6 +715,12 @@ export class CommanderMirror {
return this.fullTexts.get(sessionId)?.[0]
}
+ /** The user's own words for a turn, clipped — the topic signal the recap cannot carry. */
+ private rememberAsk(sessionId: string, ask: string): void {
+ const kept = [(ask || '').replace(/\s+/g, ' ').trim().slice(0, ASK_MAX_CHARS), ...(this.asks.get(sessionId) ?? [])].slice(0, RECENT_TURNS)
+ this.asks.set(sessionId, kept)
+ }
+
/** Keep the last few turns for this session, newest first. */
private remember(sessionId: string, summary: string): void {
const kept = [summary, ...(this.history.get(sessionId) ?? [])].slice(0, RECENT_TURNS)
@@ -779,6 +808,12 @@ export class CommanderMirror {
if (Array.isArray(v)) this.fullTexts.set(k, v.filter((x): x is string => typeof x === 'string').slice(0, RECENT_TURNS).map(t => clipBytes(t, FULL_TEXT_MAX_BYTES)))
}
} catch { /* no full answers yet — recap simply omits the field */ }
+ try {
+ const obj = JSON.parse(readFileSync(this.askFile, 'utf-8')) as Record<string, unknown>
+ for (const [k, v] of Object.entries(obj)) {
+ if (Array.isArray(v)) this.asks.set(k, v.filter((x): x is string => typeof x === 'string').slice(0, RECENT_TURNS).map((t) => t.slice(0, ASK_MAX_CHARS)))
+ }
+ } catch { /* no questions stored yet — the router falls back to recaps alone */ }
}
private saveSoon(): void {
@@ -792,6 +827,7 @@ export class CommanderMirror {
writeFileSync(this.file, JSON.stringify(Object.fromEntries(this.summaries), null, 2))
writeFileSync(this.historyFile, JSON.stringify(Object.fromEntries(this.history), null, 2))
writeFileSync(this.fullTextFile, JSON.stringify(Object.fromEntries(this.fullTexts), null, 2))
+ writeFileSync(this.askFile, JSON.stringify(Object.fromEntries(this.asks), null, 2))
} catch (err) {
console.error('[commander] save summaries failed:', err)
}
diff --git a/cli/src/lib/voiceRouter.spec.ts b/cli/src/lib/voiceRouter.spec.ts
index 8efa76c39..4331b41e3 100644
--- a/cli/src/lib/voiceRouter.spec.ts
+++ b/cli/src/lib/voiceRouter.spec.ts
@@ -24,7 +24,7 @@ vi.mock('./openrouter.js', () => ({
}))
// Import AFTER the mock is registered.
-const { buildRouterPrompt, parseRouteOutput, routeVoiceTask, pickAgentHeuristic, chooseRouterEngine, routerModelFor } = await import('./voiceRouter.js')
+const { buildRouterPrompt, parseRouteOutput, routeVoiceTask, pickAgentHeuristic, chooseRouterEngine, routerModelFor, ROUTE_SCORED_ROWS, CONTINUITY_WINDOW_MS } = await import('./voiceRouter.js')
type RouterAgent = import('./voiceRouter.js').RouterAgent
const AGENTS: RouterAgent[] = [
@@ -92,6 +92,131 @@ describe('parseRouteOutput', () => {
})
})
+describe('the second world war, then the first', () => {
+ // The exact sequence from the desk, 2026-09-09: WW2 was routed to the history agent, and 19 seconds
+ // later "…thứ nhất…" was routed to an agent about the World Cup with 0.4 confidence. Three separate
+ // defects lined up, and each one is pinned below.
+ const HISTORY = '562d0376'
+ const WORLDCUP = '58998f92'
+ const WW1 = 'Chiến tranh thế giới thứ nhất kết thúc vào năm nào?'
+
+ /** As the agents looked at that moment: names are previous questions, recaps are bare answers. */
+ const DESK: RouterAgent[] = [
+ { id: WORLDCUP, name: 'Worldcup dc to chuc may lan roi', recentSummary: 'World Cup được tổ chức mấy lần rồi', engine: 'claude' },
+ { id: HISTORY, name: 'Thomas Edison vs Nikola Tesla', recentSummary: 'Chiến tranh thế giới thứ hai kết thúc vào năm nào?', engine: 'claude' },
+ { id: 'dbae0db4', name: 'Ai sang tác bài thơ Bình ngô đại cáo', recentSummary: 'ai sáng tác bài thơ đó', engine: 'claude' },
+ ]
+
+ it('follows the conversation when the recap is only the answer', () => {
+ // What the router used to see for the history agent was the RECAP of that turn — the model answered
+ // "1945.", so that is what the recap said, and it shares nothing with the next question.
+ const answersOnly = DESK.map((agent) =>
+ agent.id === HISTORY ? { ...agent, recentSummary: '1945.' } : agent)
+ expect(pickAgentHeuristic(WW1, answersOnly).agentId).not.toBe(HISTORY) // the bug, preserved
+
+ // With the QUESTION on record instead, the same matcher lands on the history agent.
+ expect(pickAgentHeuristic(WW1, DESK).agentId).toBe(HISTORY)
+ })
+
+ it('does not let function words decide it', () => {
+ // "thế giới" and "năm" appear in both the question and the World Cup agent's history. They are the
+ // most common words in the sentence and they carried the whole ranking.
+ const stripped = DESK.map((agent) =>
+ agent.id === HISTORY ? { ...agent, recentSummary: '1945.' } : agent)
+ const decision = pickAgentHeuristic(WW1, stripped)
+ // Nothing genuinely matches now, so it must not claim a match — 0.2 is "closest agent", not a hit.
+ expect(decision.confidence).toBe(0.2)
+ expect(decision.reason).toContain('closest agent')
+ })
+
+ it('carries a follow-up back to the agent just spoken to, even with nothing else to go on', () => {
+ // A follow-up that shares no content words at all with anything on the desk.
+ const bare = 'còn cái thứ nhất thì sao'
+ expect(pickAgentHeuristic(bare, DESK, { agentId: HISTORY, agoMs: 19_000 }).agentId).toBe(HISTORY)
+ // …and lets go once the conversation has plainly ended.
+ const stale = pickAgentHeuristic(bare, DESK, { agentId: HISTORY, agoMs: 45 * 60_000 })
+ expect(stale.agentId).not.toBe(HISTORY)
+ })
+
+ it('does not let continuity beat an agent the words actually name', () => {
+ const named = pickAgentHeuristic('worldcup tổ chức mấy lần', DESK, { agentId: HISTORY, agoMs: 5_000 })
+ expect(named.agentId).toBe(WORLDCUP)
+ })
+
+ it('tells the model what it was just talking to, and stops when the window closes', () => {
+ const fresh = buildRouterPrompt(WW1, DESK, { agentId: HISTORY, agoMs: 19_000 })
+ expect(fresh).toContain(`id=${HISTORY} 19s ago`)
+ const stale = buildRouterPrompt(WW1, DESK, { agentId: HISTORY, agoMs: CONTINUITY_WINDOW_MS + 1 })
+ expect(stale).not.toContain('Continuity:')
+ })
+
+ it('stops teaching the model that agent names are job titles', () => {
+ // Every agent on this desk is named after the first thing it was asked. The old prompt insisted
+ // names were roles like "Frontend"/"Auth", which describes nobody here.
+ const prompt = buildRouterPrompt(WW1, DESK)
+ expect(prompt).toContain('it is not always a role')
+ expect(prompt).toContain('recently asked')
+ })
+})
+
+describe('a bar on every row', () => {
+ // The picker offers every agent that was weighed. A row with no number on it reads as one the router
+ // rejected, so "we only scored the top three" is a bug you can see from across the room.
+ const SIX: RouterAgent[] = [
+ { id: '1', name: 'Frontend', recentSummary: 'dark mode', engine: 'claude' },
+ { id: '2', name: 'Auth', recentSummary: 'JWT refresh', engine: 'claude' },
+ { id: '3', name: 'DevOps', engine: 'claude' },
+ { id: '4', name: 'Billing', engine: 'claude' },
+ { id: '5', name: 'Search', engine: 'claude' },
+ { id: '6', name: 'Mobile', engine: 'claude' },
+ ]
+
+ it('scores five rows in all — the pick and four — however many the model sends', () => {
+ const alternates = ['2', '3', '4', '5', '6'].map((id, i) => `{"agentId":"${id}","confidence":${0.5 - i * 0.05}}`)
+ const decision = parseRouteOutput(
+ `{"agentId":"1","confidence":0.6,"reason":"x","alternates":[${alternates.join(',')}]}`,
+ SIX,
+ )
+ // Four alternates beside the pick. The sixth agent still appears in the picker — it simply carries
+ // no bar, which says "not ranked", not "rejected".
+ expect(decision.scores?.map((score) => score.agentId)).toEqual(['2', '3', '4', '5'])
+ })
+
+ it('still drops what it should — unknown ids, repeats of the pick, and junk numbers', () => {
+ const decision = parseRouteOutput(
+ '{"agentId":"1","confidence":0.6,"reason":"x","alternates":['
+ + '{"agentId":"2","confidence":0.5},'
+ + '{"agentId":"99","confidence":0.4},' // not on this machine
+ + '{"agentId":"1","confidence":0.9},' // the pick again
+ + '{"agentId":"2","confidence":0.3},' // a repeat
+ + '{"agentId":"3","confidence":"nope"}' // not a number
+ + ']}',
+ SIX,
+ )
+ expect(decision.scores).toEqual([{ agentId: '2', confidence: 0.5 }])
+ })
+
+ it('draws the same number of bars when the name matcher stands in', () => {
+ const decision = pickAgentHeuristic('sua dark mode', SIX)
+ // The picker must not change shape depending on which half of the router answered — and every score
+ // stays under the winner, which is what the cap at 0.4 protects: these draw a bar, they never cross
+ // a dispatch threshold.
+ expect(decision.scores).toHaveLength(ROUTE_SCORED_ROWS - 1)
+ for (const score of decision.scores ?? []) {
+ expect(score.confidence).toBeGreaterThan(0)
+ expect(score.confidence).toBeLessThan(decision.confidence)
+ }
+ })
+
+ it('asks the model for exactly as many as the picker will draw', () => {
+ const prompt = buildRouterPrompt('fix the login screen', SIX)
+ expect(prompt).toContain(`up to ${ROUTE_SCORED_ROWS - 1}`)
+ // The three caps drifted apart once — the prompt asked for two while the name matcher scored three —
+ // and the only symptom was bars missing from a list nobody thought to count.
+ expect(prompt).not.toContain('up to 2')
+ })
+})
+
describe('buildRouterPrompt', () => {
it('includes the transcript, each agent name, and the recent summary (or a placeholder)', () => {
const p = buildRouterPrompt('sửa lỗi đăng nhập', AGENTS)
@@ -230,12 +355,29 @@ describe('routeVoiceTask through an OpenRouter gateway', () => {
expect(runRouterOneShot).toHaveBeenCalledOnce()
})
- it('leaves a machine with no gateway agent entirely alone', async () => {
+ it('takes the direct call on ANY machine that has a key, not just a gateway one', async () => {
+ // Widened deliberately. The engine path spawns a whole agent runtime to answer a twenty-word
+ // classification — about 15s here against a 20s ceiling, and a third of them never come back. A
+ // machine holding a key should not pay that just because none of its agents runs on the gateway.
+ resolveOpenRouterKey.mockResolvedValue('sk-or-v1-test')
+ openRouterComplete.mockResolvedValue('{"agentId":"2","confidence":0.9,"reason":"auth"}')
+
+ const d = await routeVoiceTask('login broken', AGENTS)
+
+ expect(d.agentId).toBe('2')
+ expect(openRouterComplete).toHaveBeenCalledOnce()
+ expect(runRouterOneShot).not.toHaveBeenCalled()
+ })
+
+ it('still spawns the engine when there is no key to call with', async () => {
+ // The common case, and the one that must not change: no credential, so nothing to call directly.
+ resolveOpenRouterKey.mockResolvedValue(null)
routerImpl = async () => ({ text: '{"agentId":"2","confidence":0.9,"reason":"auth"}', sessionId: null })
- await routeVoiceTask('login broken', AGENTS)
+ const d = await routeVoiceTask('login broken', AGENTS)
- expect(resolveOpenRouterKey).not.toHaveBeenCalled()
+ expect(d.agentId).toBe('2')
+ expect(openRouterComplete).not.toHaveBeenCalled()
expect(runRouterOneShot).toHaveBeenCalledOnce()
})
})
diff --git a/cli/src/lib/voiceRouter.ts b/cli/src/lib/voiceRouter.ts
index 9c385e2db..90691faf7 100644
--- a/cli/src/lib/voiceRouter.ts
+++ b/cli/src/lib/voiceRouter.ts
@@ -130,21 +130,53 @@ export function shutdownVoiceRouter(): void {
}
// Diacritic/case-insensitive tokens (Vietnamese-aware) for the heuristic fallback matcher.
+/**
+ * Words that carry no topic, in the two languages this router actually sees.
+ *
+ * Written after watching the fallback pick "Worldcup dc to chuc may lan roi" for "Chiến tranh thế giới
+ * thứ nhất kết thúc vào năm nào?" — on this desk, with a real dial. Not one of the eight agents matched
+ * by NAME, so the entire ranking came from words like `the` (thế), `gioi`, `nam` and `nao` appearing in
+ * someone's recent activity. Function words are the most common tokens in any sentence, so without this
+ * they dominate every comparison and the score measures sentence length rather than fit.
+ *
+ * Diacritics are already stripped when this is consulted, so the Vietnamese entries are written the way
+ * routeTokens leaves them — and `the` covers both "thế" and the English article.
+ */
+const ROUTE_STOP_WORDS = new Set([
+ // Vietnamese function words
+ 'la', 'co', 'cua', 'cho', 'den', 'tu', 'mot', 'nao', 'vao', 'nay', 'do', 'khi', 'thi', 'ma', 'ra',
+ 'len', 'xuong', 'nhung', 'hay', 'hoac', 'duoc', 'bi', 'se', 'da', 'dang', 'roi', 'chua', 'khong',
+ 'gi', 'sao', 'tai', 've', 'voi', 'boi', 'neu', 'vi', 'nen', 'cung', 'van', 'chi', 'moi', 'rat',
+ 'qua', 'cai', 'nhu', 'the', 'thu', 'con', 'de', 'trong', 'ngoai', 'tren', 'duoi', 'hon', 'nua',
+ // English function words
+ 'and', 'or', 'of', 'to', 'in', 'on', 'at', 'for', 'with', 'is', 'are', 'was', 'were', 'be', 'it',
+ 'this', 'that', 'what', 'how', 'when', 'why', 'who', 'an', 'as', 'by', 'from', 'me', 'my', 'you',
+ 'your', 'we', 'us', 'do', 'does', 'did', 'can', 'will', 'would', 'should', 'about',
+])
+
function routeTokens(s: string): string[] {
const norm = s.normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[\u0111\u0110]/g, 'd').toLowerCase()
- return norm.split(/[^a-z0-9]+/).filter((t) => t.length >= 2)
+ return norm.split(/[^a-z0-9]+/).filter((t) => t.length >= 2 && !ROUTE_STOP_WORDS.has(t))
}
// Fallback when the LLM router is unavailable (timed out / spawn failed): score each agent by how many
// transcript words appear in its NAME (strong signal) and recent activity (weak), and pick the best. Always
// returns a concrete in-machine agent with a low, capped confidence — the voice still dispatches, never errors.
-export function pickAgentHeuristic(transcript: string, agents: RouterAgent[]): RouteDecision {
+export function pickAgentHeuristic(
+ transcript: string,
+ agents: RouterAgent[],
+ continuity?: RouterContinuity,
+): RouteDecision {
const words = new Set(routeTokens(transcript))
+ // Only while the conversation is plausibly still going. An id that is no longer on the list scores
+ // nothing by construction — nobody is matched against it.
+ const stillTalking = continuity && continuity.agoMs <= CONTINUITY_WINDOW_MS ? continuity.agentId : ''
const ranked = agents
.map((agent) => {
const nameHits = routeTokens(agent.name).filter((t) => words.has(t)).length
const recentHits = routeTokens(agent.recentSummary ?? '').filter((t) => words.has(t)).length
- return { agent, score: nameHits * 3 + recentHits }
+ const carried = agent.id === stillTalking ? CONTINUITY_SCORE : 0
+ return { agent, score: nameHits * 3 + recentHits + carried }
})
// STABLE on a tie, and that matters more than it looks: with no match at all every score is 0, and
// the winner has to stay "the first agent" — the same answer this function has always given — rather
@@ -162,7 +194,10 @@ export function pickAgentHeuristic(transcript: string, agents: RouterAgent[]): R
needNewAgent: false,
// Scaled UNDER the winner rather than invented: a name matcher can say "this one beat the others",
// and that is all these say. They are for a picker to draw a bar with, never for a threshold.
- scores: ranked.slice(1, 4).map((entry) => ({
+ // The same handful the model is asked for, so a route that fell back to name matching draws the
+ // same number of bars as one that did not — the picker must not look different depending on which
+ // half of the router answered.
+ scores: ranked.slice(1, ROUTE_SCORED_ROWS).map((entry) => ({
agentId: entry.agent.id,
confidence: best && best.score > 0
? Math.max(0.05, Math.min(winner - 0.05, (entry.score / best.score) * winner))
@@ -190,26 +225,47 @@ function logDecision(via: string, agents: RouterAgent[], decision: RouteDecision
return decision
}
-export function buildRouterPrompt(transcript: string, agents: RouterAgent[]): string {
+export function buildRouterPrompt(
+ transcript: string,
+ agents: RouterAgent[],
+ continuity?: RouterContinuity,
+): string {
const lines = agents
- .map((a) => `- id=${a.id} | name="${a.name}"${a.machine ? ` | machine="${a.machine}"` : ''} | recent: ${a.recentSummary?.trim() || '(no activity yet)'}`)
+ .map((a) => `- id=${a.id} | name="${a.name}"${a.machine ? ` | machine="${a.machine}"` : ''} | recently asked: ${a.recentSummary?.trim() || '(no activity yet)'}`)
.join('\n')
+ // Stated as a FACT with its age, not as an instruction to follow it. A follow-up usually belongs to
+ // the same agent; a new subject spoken thirty seconds later does not, and only the model can tell
+ // those apart. Omitted entirely once the window has passed, so a stale id never sits in the prompt
+ // looking current.
+ const carry = continuity && continuity.agoMs <= CONTINUITY_WINDOW_MS
+ ? `Continuity: this person sent their previous task to agent id=${continuity.agentId} ` +
+ `${Math.max(1, Math.round(continuity.agoMs / 1000))}s ago. A follow-up question — a pronoun, a ` +
+ `comparison, or the same subject asked a second way — usually belongs to that same agent. A task ` +
+ `about a plainly different subject does not.\n\n`
+ : ''
return (
`You are a ROUTER. Assign ONE incoming voice task to the single best-fit agent from the fixed list ` +
`below. You MUST always choose exactly one agent from the list — there is NO "none" option and you may ` +
- `NOT decline. The agent NAME is a strong signal — the user names agents by role/domain ("Frontend", ` +
- `"Auth", "DevOps"). Each agent's RECENT activity disambiguates when names alone are ambiguous. If nothing ` +
+ `NOT decline.\n\n` +
+ `How to read an agent: its NAME is a strong signal, but it is not always a role. Some people name ` +
+ `agents by domain ("Frontend", "Auth", "DevOps"); others leave the name as the FIRST THING THEY ASKED ` +
+ `it, so a name like "Worldcup dc to chuc may lan roi" means that agent's conversation is about the ` +
+ `World Cup. Read both kinds as the agent's subject. "recently asked" lists what this person asked ` +
+ `that agent lately, newest first — the surest sign of what its conversation is about. If nothing ` +
`matches well, still pick the CLOSEST agent and give it a low confidence.\n\n` +
`Voice task (verbatim; may be Vietnamese — do NOT translate it): "${transcript}"\n\n` +
+ carry +
`Agents:\n${lines}\n\n` +
`Always pick exactly one agent id from the list above. Set confidence 0..1 for how good the fit is:\n` +
`- 0.85+ when the name and/or recent activity clearly match\n` +
`- ~0.6 when it's a reasonable but not certain match\n` +
`- ~0.3 when nothing fits well but this is the closest agent.\n\n` +
- `Also rank the next best fits in "alternates" (up to 2, most fitting first, never repeating your ` +
- `pick). They are shown to the user when your confidence is low, so they can choose; they are never ` +
- `dispatched to on their own. Omit the field when there is no other agent.\n\n` +
+ `Also rank the next best fits in "alternates" (up to ${ROUTE_SCORED_ROWS - 1}, most fitting first, ` +
+ `never repeating your pick). They are shown to the user when your confidence is low, so they can ` +
+ `choose; they are never dispatched to on their own — and the agent a person actually wants is often ` +
+ `the one you ranked fourth, so rank that far even when the first two look obvious. Omit the field ` +
+ `when there is no other agent.\n\n` +
`Respond with ONLY a single JSON object, no prose, no markdown fence:\n` +
`{"agentId":"<one id from the list>","confidence":<0..1>,"reason":"<max 12 words>",` +
`"alternates":[{"agentId":"<id>","confidence":<0..1>}]}`
@@ -255,7 +311,9 @@ export function parseRouteOutput(raw: string, agents: RouterAgent[]): RouteDecis
if (!Number.isFinite(value)) continue
seen.add(id)
scores.push({ agentId: id, confidence: Math.max(0, Math.min(1, value)) })
- if (scores.length === 3) break
+ // Bounded by the same constant the prompt asks with, so a model that over-answers cannot quietly
+ // widen what the picker draws. `ids` and `seen` bound it to the candidate list, once each.
+ if (scores.length >= ROUTE_SCORED_ROWS - 1) break
}
}
// An empty or unknown id ⇒ fall back to the closest (first) agent with capped confidence; a valid
@@ -273,6 +331,47 @@ export function parseRouteOutput(raw: string, agents: RouterAgent[]): RouteDecis
* someone else's clock can therefore ask for more — and a caller that IS should not be given it, because
* overshooting their deadline turns a fallback answer into no answer at all.
*/
+/**
+ * How many rows in the picker carry a number.
+ *
+ * The pick plus four. The picker lists EVERY agent that was weighed — that part is not capped — but the
+ * router is only asked to rank the top handful, and the rest are simply drawn without a bar. Three was
+ * too few to be useful (the right agent is often the fourth); every one of fifteen makes the classifier
+ * write a long answer on a path that already times out often enough to matter. Five is the compromise,
+ * and an unscored row is honest: it says the router did not rank this one, not that it rejected it.
+ *
+ * Read by all three places that used to cap independently — the prompt, the parse, and the name matcher
+ * — because they drifted apart once already and the symptom (three bars over a list of eight) took a
+ * person noticing it on screen to find.
+ */
+export const ROUTE_SCORED_ROWS = 5
+
+/**
+ * Who this person was last talking to, for a router deciding where a follow-up belongs.
+ *
+ * The single strongest signal there is for a second question, and the one nothing else could supply:
+ * "Chiến tranh thế giới thứ nhất kết thúc vào năm nào?" names no agent, matches no name, and belongs
+ * beyond reasonable doubt to whichever agent just answered the same question about the second world war
+ * nineteen seconds earlier.
+ */
+export interface RouterContinuity {
+ agentId: string
+ /** Milliseconds since that turn was sent. */
+ agoMs: number
+}
+
+/**
+ * How recently counts as "still the same conversation".
+ *
+ * Five minutes. Long enough to cover thinking, reading the answer and asking the next thing; short
+ * enough that the agent you used before lunch does not quietly win an unrelated afternoon question.
+ */
+export const CONTINUITY_WINDOW_MS = 5 * 60_000
+
+/** What continuity is worth to the fallback matcher: one name hit. Enough to break a tie and to beat
+ * incidental word overlap, not enough to outrank an agent the words actually describe. */
+const CONTINUITY_SCORE = 3
+
export const ROUTE_CLASSIFY_MS = 12_000
export async function routeVoiceTask(
@@ -280,6 +379,7 @@ export async function routeVoiceTask(
agents: RouterAgent[],
signal?: AbortSignal,
timeoutMs: number = ROUTE_CLASSIFY_MS,
+ continuity?: RouterContinuity,
): Promise<RouteDecision> {
// What the backend handed down, and what it may choose between. Logged before anything can fail, so a
// route that times out still shows the task and the candidates it was weighing.
@@ -294,12 +394,20 @@ export async function routeVoiceTask(
return logDecision('only-agent', agents, { agentId: agents[0].id, confidence: 1, reason: 'only agent in machine', needNewAgent: false })
}
- const prompt = buildRouterPrompt(transcript, agents)
+ const prompt = buildRouterPrompt(transcript, agents, continuity)
- // A machine running gateway agents (`ori claude`, …) classifies with ONE direct OpenRouter call: the
- // vendor one-shot it would otherwise warm has no credential to spend, and this is a 20-word
- // classification either way. Anything short of a usable answer falls through to the engine path below.
- if (env.ORI_VOICE_ROUTE_MODEL && agents.some((agent) => agent.gateway === 'ori')) {
+ // ONE DIRECT API CALL WHENEVER THERE IS A KEY TO MAKE IT WITH — not only on machines running gateway
+ // agents, which is all this used to cover.
+ //
+ // The engine path below classifies by spawning the vendor CLI. Measured on this desk:
+ // `claude --print --model haiku "Reply with only the word OK"` took 75 seconds; the router's own
+ // stripped, pre-warmed spawn still takes about 15 against a 20-second ceiling, and a third of them
+ // time out. That is not a prompt problem and no wording fixes it — it is a whole agent runtime
+ // starting up to answer a twenty-word classification. A direct call answers in about one.
+ //
+ // Still a fallthrough, not a replacement: no key, no model, or no usable answer and the engine path
+ // runs exactly as before. Machines without a credential are unaffected.
+ if (env.ORI_VOICE_ROUTE_MODEL) {
const apiKey = await resolveOpenRouterKey()
if (apiKey) {
console.log(`[voice-route] classifying with openrouter · model=${env.ORI_VOICE_ROUTE_MODEL}`)
@@ -317,7 +425,7 @@ export async function routeVoiceTask(
const engine = chooseRouterEngine(agents.filter((agent) => agent.engine).map((agent) => ({ engine: agent.engine as string }))) ?? routerEngine
if (!engine) {
console.log('[voice-route] no agent this router can run on → name matching')
- return logDecision('heuristic (no engine)', agents, pickAgentHeuristic(transcript, agents))
+ return logDecision('heuristic (no engine)', agents, pickAgentHeuristic(transcript, agents, continuity))
}
const model = routerModelFor(engine)
ensureRouterConfigured(engine) // so runRouterOneShot matches the pool config and uses the warm worker
@@ -336,6 +444,6 @@ export async function routeVoiceTask(
// The classifier timed out / spawn failed → NEVER fail the RPC. Fall back to a heuristic pick so the
// voice still dispatches to a plausible agent instead of erroring out on the device.
console.log(`[voice-route] ${engine} one-shot failed (${err instanceof Error ? err.message : String(err)}) → name matching`)
- return logDecision(`heuristic (${engine} failed)`, agents, pickAgentHeuristic(transcript, agents))
+ return logDecision(`heuristic (${engine} failed)`, agents, pickAgentHeuristic(transcript, agents, continuity))
}
}
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index e7f0c2672..963daa998 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -171,6 +171,43 @@ describe('local CLI WebSocket', () => {
ws.close()
})
+ it('carries the window\'s answer about a spoken task, and keeps it off the wire', async () => {
+ const backend = new FakeBackend()
+ const replies: Array<{ voiceId: string; reply: unknown }> = []
+ server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })
+ local = attachLocalWsServer(server, {
+ machineId,
+ backend,
+ onVoiceRouteReply: (voiceId, reply) => replies.push({ voiceId, reply }),
+ })
+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))
+ const url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/local-ws`
+
+ const ws = new WebSocket(url)
+ await onceOpen(ws)
+ const connected = onceMessage(ws)
+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))
+ await connected
+
+ ws.send(JSON.stringify({ type: 'voice_route_reply', payload: { voiceId: 'v1', state: 'taken' } }))
+ ws.send(JSON.stringify({ type: 'voice_route_reply', payload: { voiceId: 'v1', state: 'sent', agentId: 'a7' } }))
+ ws.send(JSON.stringify({ type: 'voice_route_reply', payload: { voiceId: 'v2', state: 'cancelled' } }))
+ // Neither of these is an answer: one names no request, the other a state this side cannot read.
+ // Guessing at either would settle a spoken turn on something nobody said.
+ ws.send(JSON.stringify({ type: 'voice_route_reply', payload: { state: 'sent', agentId: 'a9' } }))
+ ws.send(JSON.stringify({ type: 'voice_route_reply', payload: { voiceId: 'v3', state: 'maybe' } }))
+ await new Promise((resolve) => setTimeout(resolve, 20))
+
+ expect(replies).toEqual([
+ { voiceId: 'v1', reply: { t: 'taken' } },
+ { voiceId: 'v1', reply: { t: 'sent', agentId: 'a7' } },
+ { voiceId: 'v2', reply: { t: 'cancelled' } },
+ ])
+ // It describes a hand at this desk. The machine has no use for it.
+ expect(backend.frames).toEqual([])
+ ws.close()
+ })
+
it('answers a routed task on the id it was asked with, and sends nothing', async () => {
const backend = new FakeBackend()
const asked: string[] = []
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 38eb737fc..0076a9562 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -22,6 +22,8 @@ const MAX_JSON_BYTES = 512 * 1024
const MAX_WS_MESSAGE_BYTES = TERMINAL_LOCAL_PASTE_MAX_PAYLOAD_BYTES + 4_096
const HEARTBEAT_MS = 20_000
+import type { WindowVoiceReply } from './cable/windowRoute.js'
+
export interface LocalWsBackend {
registerLocalClient: (connId: string, sink: LocalClientSink) => boolean
unregisterLocalClient: (connId: string) => Promise<void>
@@ -57,6 +59,15 @@ export interface LocalWsServerOptions {
* on a confident route, that is a spoken instruction that vanishes with no mark anywhere.
*/
onRouteSend?: (agentId: string, text: string) => { ok: true } | { ok: false; machine: string; reason: string }
+ /**
+ * The window answering a `voice_route_request` — words spoken into the dial that IT was asked to route.
+ *
+ * One-way and uncorrelated by `requestId`, unlike ⌘B above, because the question travelled the other
+ * way: the daemon asked, so the daemon holds the pending id (`voiceId`) and the window is simply
+ * reporting. `taken` first, then `sent` or `cancelled` — see cable/windowRoute.ts for why the ack is a
+ * separate frame rather than a flag on the answer.
+ */
+ onVoiceRouteReply?: (voiceId: string, reply: WindowVoiceReply) => void
}
/** One candidate, as the window draws it in the picker. */
@@ -284,7 +295,7 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
//
// Consumed here like app_focus: it describes a hand at this desk, not anything the machine could
// act on.
- if (!isBinary && (options.onRouteTask || options.onRouteSend)) {
+ if (!isBinary && (options.onRouteTask || options.onRouteSend || options.onVoiceRouteReply)) {
const asked = jsonFrame(raw)
if (asked?.type === 'route_task' && options.onRouteTask) {
const payload = asked.payload as Record<string, unknown> | undefined
@@ -303,6 +314,20 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
sink.sendFrame({ type: 'route_result', payload: { requestId, ...answer } })
return
}
+ if (asked?.type === 'voice_route_reply' && options.onVoiceRouteReply) {
+ const payload = asked.payload as Record<string, unknown> | undefined
+ const voiceId = typeof payload?.voiceId === 'string' ? payload.voiceId : ''
+ const state = typeof payload?.state === 'string' ? payload.state : ''
+ const agentId = typeof payload?.agentId === 'string' ? payload.agentId : ''
+ // Unknown states are dropped rather than guessed at: an answer this side cannot read must
+ // not settle a spoken turn as though it had been understood.
+ if (voiceId) {
+ if (state === 'taken') options.onVoiceRouteReply(voiceId, { t: 'taken' })
+ else if (state === 'sent') options.onVoiceRouteReply(voiceId, { t: 'sent', agentId })
+ else if (state === 'cancelled') options.onVoiceRouteReply(voiceId, { t: 'cancelled' })
+ }
+ return
+ }
if (asked?.type === 'route_send' && options.onRouteSend) {
const payload = asked.payload as Record<string, unknown> | undefined
const requestId = typeof payload?.requestId === 'string' ? payload.requestId : ''