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(route): ⌘K weighs every machine's agents, and says when it cannot deliver

0xdiego257dcfe4fae91d
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index b2a058748..dbcccdb64 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -285,6 +285,30 @@ describe('DaemonCableHost.listAgents across machines', () => {
expect(host.knows('r1')).toBe(true)
})
+ it('answers the RAIL\'s order flat, and the dial\'s ring separately, from one snapshot', async () => {
+ // Two questions, two right answers, and they must not be confused for each other. The dial walks a
+ // ring cut around the window's open tiles; ⌘K weighs "the first fifteen agents" against a list the
+ // person is reading top to bottom in their rail. Serving the ring to ⌘K makes the fifteen it picks
+ // impossible to predict from the screen — the tile someone happened to open last silently reorders
+ // what a typed task is even compared against.
+ AGENTS.length = 0
+ AGENTS.push({ agentId: 'local-1', registeredAt: 1, active: true, terminalAvailable: true, engine: 'claude' })
+ AGENTS.push({ agentId: 'local-2', registeredAt: 2, active: true, terminalAvailable: true, engine: 'claude' })
+ const host = new DaemonCableHost(wiring(), crossFleet({ other: [{ id: 'r1', name: 'api' }] }))
+ await settled(host)
+ // Two tiles, in an order the rail does not have: the remote agent first. ONE tile would not show the
+ // difference — a single-tile desk cuts the ring into head + tile + tail, which reassembles into the
+ // flat order exactly, so a test built on it would pass against either implementation.
+ host.setDesk(['r1', 'local-1'])
+
+ // The rail: this computer's agents in their own order, then the other machine's.
+ expect((await host.listAgentsFlat()).map((a) => a.id)).toEqual(['local-1', 'local-2', 'r1'])
+ // The ring: the same three, re-cut around the desk — the tiles in tile order, the rest off its edges.
+ const ring = await host.listAgents()
+ expect([...ring].map((a) => a.id).sort()).toEqual(['local-1', 'local-2', 'r1'])
+ expect(ring.map((a) => a.id)).toEqual(['r1', 'local-1', 'local-2'])
+ })
+
it('lists every agent, marking the ones the carousel does not walk', async () => {
// Ring first, then the rest — the session sends the count of the first
// group, so the ORDER is the split. Every agent is still listed, because
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index 995fcedc5..7bea73388 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -312,6 +312,49 @@ export class DaemonCableHost implements CableHost {
}
async listAgents(): Promise<CableAgent[]> {
+ const out = await this.listAgentsFlat()
+
+ const ring = deskRing(out.map((a) => a.id), this.desk)
+ this.deskEdge = ring.edgeOf
+ // Walked agents first, then the ones the dial knows but does not walk to —
+ // the session sends the count of the first group, so the order is the split.
+ const listed = [...ring.order, ...ring.offRing]
+ // One line per CHANGE. The failure this catches is silent by nature: tiles
+ // whose ids this daemon does not know leave the ring flat and every agent
+ // edgeless, which looks exactly like the feature not being installed.
+ const onDesk = new Set(this.desk)
+ const short = (id: string) => `${onDesk.has(id) ? '*' : ''}${id.slice(0, 4)}`
+ // Both halves: what the thumb walks, and what the dial merely knows. Reading
+ // only the first half is how "the dial says 5 agents" looked like a counting
+ // bug rather than a list that had been cut in two.
+ const shape = ring.order.map(short).join(' ')
+ + (ring.offRing.length ? ` · off-ring ${ring.offRing.map(short).join(' ')}` : '')
+ if (shape !== this.deskShape) {
+ this.deskShape = shape
+ // The WHOLE ring, marked: `*` is a tile. Short of this the shape has to be
+ // guessed from behaviour, and every guess so far has been wrong about
+ // which end the agents nobody stepped onto ended up at.
+ this.wiring.log(`cable: ring ${shape}`)
+ }
+ const offRing = new Set(ring.offRing)
+ const byId = new Map(out.map((a) => [a.id, a]))
+ return listed
+ .map((id) => byId.get(id))
+ .filter((a): a is CableAgent => !!a)
+ .map((a) => (offRing.has(a.id) ? { ...a, offRing: true } : a))
+ }
+
+ /**
+ * The same agents in LIST order — this computer first, then each machine in wheel order — with no ring
+ * laid over them.
+ *
+ * It is the order the desktop app's rail draws, and the two must not drift: ⌘K reads this to decide
+ * which agents a typed task is weighed against, and a person looking at their rail while they type has
+ * every right to expect "the first fifteen" to mean the first fifteen they can see. `listAgents()` is
+ * the DIAL's view of the same snapshot — the same agents, re-cut around the tiles the window has open,
+ * which is a different question with a different right answer.
+ */
+ async listAgentsFlat(): Promise<CableAgent[]> {
const out = this.localAgents()
const { machines } = await this.listMachines()
for (const m of machines) {
@@ -358,33 +401,7 @@ export class DaemonCableHost implements CableHost {
}
for (const id of [...this.deskHeld]) if (!missing.includes(id)) this.deskHeld.delete(id)
- const ring = deskRing(out.map((a) => a.id), this.desk)
- this.deskEdge = ring.edgeOf
- // Walked agents first, then the ones the dial knows but does not walk to —
- // the session sends the count of the first group, so the order is the split.
- const listed = [...ring.order, ...ring.offRing]
- // One line per CHANGE. The failure this catches is silent by nature: tiles
- // whose ids this daemon does not know leave the ring flat and every agent
- // edgeless, which looks exactly like the feature not being installed.
- const onDesk = new Set(this.desk)
- const short = (id: string) => `${onDesk.has(id) ? '*' : ''}${id.slice(0, 4)}`
- // Both halves: what the thumb walks, and what the dial merely knows. Reading
- // only the first half is how "the dial says 5 agents" looked like a counting
- // bug rather than a list that had been cut in two.
- const shape = ring.order.map(short).join(' ')
- + (ring.offRing.length ? ` · off-ring ${ring.offRing.map(short).join(' ')}` : '')
- if (shape !== this.deskShape) {
- this.deskShape = shape
- // The WHOLE ring, marked: `*` is a tile. Short of this the shape has to be
- // guessed from behaviour, and every guess so far has been wrong about
- // which end the agents nobody stepped onto ended up at.
- this.wiring.log(`cable: ring ${shape}`)
- }
- const offRing = new Set(ring.offRing)
- return listed
- .map((id) => byId.get(id))
- .filter((a): a is CableAgent => !!a)
- .map((a) => (offRing.has(a.id) ? { ...a, offRing: true } : a))
+ return out
}
/**
@@ -483,9 +500,36 @@ export class DaemonCableHost implements CableHost {
}
}
- sendTurn(agentId: string, text: string): void {
- if (!this.isLocalAgent(agentId)) { this.fleet!.sendTurn(this.machineOf(agentId), agentId, text); return }
+ /**
+ * Deliver a turn, and SAY whether it could be.
+ *
+ * The remote leg is fire-and-forget by protocol — `message` frames carry no ack — so a machine that
+ * has stopped answering takes the turn and nothing comes back. Measured: the fleet's own `agents_list`
+ * was timing out every twenty seconds while a ⌘K route was handed to an agent on that machine, and
+ * every side stayed silent about it. The E2EE session still said `ready`, because it handshook while
+ * the machine was alive; the backend's list still called it online.
+ *
+ * So the check is the one thing that actually knows: did the LAST request to that machine come back.
+ * Never asked (null) is not a refusal — a cold start must not read as a failure.
+ *
+ * Callers that do not care may ignore the result; nothing here changes for them.
+ */
+ sendTurn(agentId: string, text: string): { ok: true } | { ok: false; machine: string; reason: string } {
+ if (!this.isLocalAgent(agentId)) {
+ const machineId = this.machineOf(agentId)
+ const machine = this.knownAgents.get(agentId)?.machine || machineId.slice(0, 8)
+ if (!machineId) return { ok: false, machine, reason: 'that agent has no machine on this daemon' }
+ const seen = this.fleet?.reachable?.(machineId)
+ if (seen && !seen.ok) {
+ const ago = Math.round((Date.now() - seen.at) / 1000)
+ this.wiring.log(`cable: refused a turn for ${agentId.slice(0, 8)} — ${machine} last failed ${ago}s ago`)
+ return { ok: false, machine, reason: 'the last request to it did not come back' }
+ }
+ this.fleet!.sendTurn(machineId, agentId, text)
+ return { ok: true }
+ }
this.wiring.sendTurn(agentId, text)
+ return { ok: true }
}
stopTurn(agentId: string): void {
diff --git a/cli/src/cable/machineFleet.ts b/cli/src/cable/machineFleet.ts
index e9f1fa620..e96397a44 100644
--- a/cli/src/cable/machineFleet.ts
+++ b/cli/src/cable/machineFleet.ts
@@ -73,6 +73,13 @@ export interface MachineFleet {
updateAgent(machineId: string, agentId: string, model?: string, effort?: string): void
listModels(machineId: string, agentId: string): Promise<string[]>
recentSummaries(machineId: string, agentId: string): Promise<RecentTurn[]>
+ /**
+ * How the last round trip to this machine went, or null if nobody has asked it yet.
+ *
+ * Optional because it is a witness, not a contract: an implementation that keeps no record simply
+ * cannot say, and callers must treat "cannot say" the same as "never asked" — never as unreachable.
+ */
+ reachable?(machineId: string): { ok: boolean; at: number } | null
/** Cards + liveness from the attached machine. Returns an unsubscribe. */
onEvent(cb: (event: FleetEvent) => void): () => void
}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 919e3f35e..67211671d 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -108,6 +108,7 @@ import {
deriveTurnSummary,
syncSummaryPoolSessions,
} from './lib/summarize.js'
+import type { CableAgent } from './cable/cableSession.js'
import { routeVoiceTask, setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter, type RouterAgent } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
import { E2eeStore } from './lib/e2ee/store.js'
@@ -198,6 +199,18 @@ let cableRef: CableSession | null = null
/** The same object the session holds — module scope so the recap gates can ask which machine is selected
* without threading it through every constructor between here and there. */
let cableHostRef: DaemonCableHost | null = null
+/**
+ * How many agents ⌘K weighs at once.
+ *
+ * A classifier budget, not a UI one: each candidate spends its name, its machine and three recaps inside
+ * one prompt, and past a point the window that decides the pick is more crowded than it is informed.
+ * Fifteen is the owner's number; the ordering that decides WHICH fifteen is in onRouteTask.
+ */
+const ROUTE_MAX_CANDIDATES = 15
+/** Each recent turn, cut to this before it enters the classifier's prompt. See onRouteTask. */
+const ROUTE_RECAP_CHARS = 60
+/** What ⌘K gives the classifier before the name matcher answers instead. */
+const ROUTE_CLASSIFY_APP_MS = 20_000
/**
* The window's tiles, in tile order, as last reported.
*
@@ -2848,47 +2861,97 @@ async function runForeground(session: AuthSession): Promise<void> {
// is new is the answer coming back to something that can SHOW it: the dial had to act on the pick,
// the window can ask.
//
- // LOCAL AGENTS ONLY (owner's call). It is what keeps this fast: the dial's cross-machine route pays an
- // RPC per remote agent to fetch recaps, and that is most of its latency. The cost is real and chosen —
- // ⌘K cannot reach an agent on another computer, even while its pane is on screen.
+ // EVERY AGENT, EVERY MACHINE. The candidate list is the dial's own — this computer first, then each
+ // machine in wheel order — because the agent that fits the words is not always the one on the desk in
+ // front of you, and a router that cannot see the others cannot say so.
+ //
+ // CAPPED AT FIFTEEN, and the cap is about the CLASSIFIER, not about us: every candidate spends its
+ // name and three recaps in one prompt, and a list long enough to crowd that window makes the pick
+ // worse, not slower.
+ //
+ // WHICH fifteen is the rail's own order — this computer's agents, then each other machine's — because
+ // that is the list the person is looking at while they type, and "the first fifteen" has to mean the
+ // first fifteen they can SEE. An earlier cut put open tiles first, on the theory that working on
+ // something is a statement about relevance; it is, but it also made the fifteen unpredictable from
+ // the screen, and predictable beat clever here (owner's call).
onRouteTask: async (text) => {
- const sessions = registry.advertised()
- sessions.sort((a, b) => a.registeredAt - b.registeredAt || a.agentId.localeCompare(b.agentId))
- const candidates: RouterAgent[] = sessions.map((session) => ({
- id: session.agentId,
- name: projectDisplayName(session),
- engine: session.engine,
- // The same three recaps the dial's router weighs. `recent` reads the mirror this daemon already
- // keeps, so this costs nothing and cannot be stale in a way the rest of the app is not.
- recentSummary: mirror.recent(session.sessionId || session.agentId, 3)
- .map((turn) => turn.recap || turn.text || '')
+ const host = cableHostRef
+ if (!host) return { agentId: '', machineId: '', name: '', confidence: 0, reason: 'no agent list yet', candidates: [] }
+ // Whatever the daemon knows right now. This also kicks a refresh of the remote machines, so a list
+ // that is short because a machine has not been asked yet fills in for the NEXT question rather than
+ // holding this one open.
+ // FLAT, not the dial's ring: listAgents() re-cuts the same snapshot around the window's open
+ // tiles, which is the right answer for a carousel and the wrong one for a list the person reads
+ // top to bottom.
+ const all = await host.listAgentsFlat()
+ const ranked = all.slice(0, ROUTE_MAX_CANDIDATES)
+ if (ranked.length < all.length) {
+ // Never a silent truncation: a route that could not have picked the right agent must not read
+ // like a route that considered it and said no.
+ console.log(`[route] ${all.length} agents · weighing the first ${ranked.length} (open tiles first)`)
+ }
+ // Recaps AFTER the cap, and in parallel: a remote agent's recap is an RPC to its machine, so
+ // fetching for agents that were never going to be weighed is latency spent on nothing. They are
+ // cached per agent on the fleet side, so a second ⌘K costs no round trip at all.
+ const candidates: RouterAgent[] = await Promise.all(ranked.map(async (agent) => ({
+ id: agent.id,
+ name: agent.name,
+ engine: agent.engine,
+ machine: agent.machine,
+ // EACH TURN CUT TO 60 CHARS before it goes anywhere near the prompt.
+ //
+ // Nothing trimmed these: the 120-char cut further down is for the PICKER, which the person reads,
+ // and the classifier was being handed three recaps at full length per agent. That is what turned a
+ // 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.
+ recentSummary: (await host.recentSummaries(agent.id))
+ .map((turn) => (turn.recap || turn.text || '').replace(/\s+/g, ' ').trim().slice(0, ROUTE_RECAP_CHARS))
.filter(Boolean)
.join(' · '),
- }))
- const decision = await routeVoiceTask(text, candidates)
+ })))
+ // 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)
const named = (id: string) => candidates.find((agent) => agent.id === id)
- // The runners-up, for the window to offer when the pick is weak. Scored the same way the fallback
- // matcher scores — name over recent — so the list the person reads is ordered by the same rule the
- // router used, not by registry position.
- const others = candidates
- .filter((agent) => agent.id !== decision.agentId)
- .slice(0, 2)
+ const others = candidates.filter((agent) => agent.id !== decision.agentId).slice(0, 2)
return {
agentId: decision.agentId,
+ machineId: all.find((entry) => entry.id === decision.agentId)?.machineId ?? '',
name: named(decision.agentId)?.name ?? '',
confidence: decision.confidence,
reason: decision.reason,
candidates: [decision.agentId ? named(decision.agentId) : null, ...others]
.filter((agent): agent is RouterAgent => !!agent)
- .map((agent) => ({ agentId: agent.id, name: agent.name, recent: (agent.recentSummary ?? '').slice(0, 120) })),
+ .map((agent) => {
+ const listed = all.find((entry) => entry.id === agent.id)
+ return {
+ agentId: agent.id,
+ name: agent.name,
+ // The machine travels twice, and both are needed: the NAME because two agents called "api"
+ // on two computers are otherwise one row twice, and the ID because the window has to open
+ // the pane on the machine the agent actually lives on.
+ machineId: listed?.machineId ?? '',
+ machine: agent.machine ?? '',
+ recent: (agent.recentSummary ?? '').slice(0, 120),
+ }
+ }),
}
},
- // Committed. Delivered through the SAME door as every other message — the web's, the dial's, a
- // hook's — so queueing, retries and the per-engine slash-command adaptation are not re-implemented
- // for the one caller that types instead of speaking.
+ // Committed. Sent through cableHost.sendTurn — the dial's own dispatch — and NOT straight into
+ // backend.onMessage.
+ //
+ // That distinction is the whole of remote support: onMessage resolves the id against THIS computer's
+ // registry, so a remote agent lands as "This agent is no longer available" — an error about an agent
+ // that is alive and answering on another machine. sendTurn is the fork that already knows the
+ // difference (local → the same door the web and the hooks use, remote → the fleet), and it is the
+ // one the dial has been using for every voice turn.
onRouteSend: (agentId, text) => {
- console.log(`[route] ⌘K → ${sid(agentId)} · bytes=${Buffer.byteLength(text, 'utf8')}`)
- backend.onMessage?.(agentId, text)
+ const sent = cableHostRef?.sendTurn(agentId, text) ?? { ok: false as const, machine: '', reason: 'no agent list yet' }
+ console.log(`[route] ⌘K → ${sid(agentId)} · bytes=${Buffer.byteLength(text, 'utf8')}`
+ + (sent.ok ? '' : ` · REFUSED: ${sent.reason}${sent.machine ? ` (${sent.machine})` : ''}`))
+ return sent
},
machineId: backend.machineId,
backend,
diff --git a/cli/src/lib/voiceRouter.ts b/cli/src/lib/voiceRouter.ts
index 58a5ee165..167877314 100644
--- a/cli/src/lib/voiceRouter.ts
+++ b/cli/src/lib/voiceRouter.ts
@@ -217,7 +217,22 @@ export function parseRouteOutput(raw: string, agents: RouterAgent[]): RouteDecis
}
// Route a transcript to an agent. Skips the LLM for the trivial cases (0 / 1 agent).
-export async function routeVoiceTask(transcript: string, agents: RouterAgent[], signal?: AbortSignal): Promise<RouteDecision> {
+/**
+ * How long the classifier gets before the name matcher answers instead.
+ *
+ * 12s is what every caller had, and it was chosen to stay under a backend RPC deadline that no longer
+ * carries this: the dial routes over the cable now, straight to this daemon. Callers that are not under
+ * 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.
+ */
+export const ROUTE_CLASSIFY_MS = 12_000
+
+export async function routeVoiceTask(
+ transcript: string,
+ agents: RouterAgent[],
+ signal?: AbortSignal,
+ timeoutMs: number = ROUTE_CLASSIFY_MS,
+): 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.
console.log(
@@ -241,7 +256,7 @@ export async function routeVoiceTask(transcript: string, agents: RouterAgent[],
if (apiKey) {
console.log(`[voice-route] classifying with openrouter · model=${env.ORI_VOICE_ROUTE_MODEL}`)
const text = await openRouterComplete({
- prompt, model: env.ORI_VOICE_ROUTE_MODEL, apiKey, signal, timeoutMs: 12_000, maxTokens: 256,
+ prompt, model: env.ORI_VOICE_ROUTE_MODEL, apiKey, signal, timeoutMs, maxTokens: 256,
})
if (text) return logDecision('openrouter', agents, parseRouteOutput(text, agents))
console.log('[voice-route] openrouter classification unavailable → engine one-shot')
@@ -259,11 +274,11 @@ export async function routeVoiceTask(transcript: string, agents: RouterAgent[],
const model = routerModelFor(engine)
ensureRouterConfigured(engine) // so runRouterOneShot matches the pool config and uses the warm worker
// BEFORE the call: on a timeout this is the only record of which CLI was asked.
- console.log(`[voice-route] classifying with ${engine} · model=${model || '(engine default)'}`)
+ console.log(`[voice-route] classifying with ${engine} · model=${model || '(engine default)'} · budget=${timeoutMs}ms · prompt=${prompt.length}c`)
try {
- // Served from the warm router worker (no cold spawn). Cap under the backend's 15s nodeRequest budget so
- // a slow route surfaces before the RPC deadline.
- const options = { prompt, model, effort: 'low' as const, cwd: ensureRouteScratch(), signal, timeoutMs: 12_000 }
+ // Served from the warm router worker (no cold spawn). The budget is the CALLER's — see
+ // ROUTE_CLASSIFY_MS for why it is no longer one number for everyone.
+ const options = { prompt, model, effort: 'low' as const, cwd: ensureRouteScratch(), signal, timeoutMs }
const { text } = engine === 'grok'
? await runGrokOneShot(options)
: await runRouterOneShot(engine, options)
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index 329174985..e272c92aa 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -181,8 +181,8 @@ describe('local CLI WebSocket', () => {
onRouteTask: async (text) => {
asked.push(text)
return {
- agentId: 'a1', name: 'auth-api', confidence: 0.86, reason: 'name matches',
- candidates: [{ agentId: 'a1', name: 'auth-api', recent: 'token rotation' }],
+ agentId: 'a1', machineId: 'm-local', name: 'auth-api', confidence: 0.86, reason: 'name matches',
+ candidates: [{ agentId: 'a1', machineId: 'm-local', name: 'auth-api', machine: 'this computer', recent: 'token rotation' }],
}
},
})
@@ -201,7 +201,7 @@ describe('local CLI WebSocket', () => {
// The requestId comes back UNTOUCHED — it is the window's own rpc id, and the only thing tying this
// answer to the spinner it is holding open.
expect(reply.type).toBe('route_result')
- expect(reply.payload).toMatchObject({ requestId: 'q-7', agentId: 'a1', name: 'auth-api', confidence: 0.86 })
+ expect(reply.payload).toMatchObject({ requestId: 'q-7', agentId: 'a1', machineId: 'm-local', name: 'auth-api', confidence: 0.86 })
expect(asked).toEqual(['fix the retry'])
// Asking is not sending. Nothing reached the machine.
expect(backend.frames.map((frame) => frame.type)).toEqual([])
@@ -244,7 +244,10 @@ describe('local CLI WebSocket', () => {
local = attachLocalWsServer(server, {
machineId,
backend,
- onRouteSend: (agentId, text) => sent.push({ agentId, text }),
+ onRouteSend: (agentId, text) => {
+ sent.push({ agentId, text })
+ return { ok: true as const }
+ },
})
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`
@@ -255,15 +258,49 @@ describe('local CLI WebSocket', () => {
ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))
await connected
- ws.send(JSON.stringify({ type: 'route_send', payload: { agentId: 'a2', text: 'do the thing' } }))
- ws.send(JSON.stringify({ type: 'route_send', payload: { agentId: '', text: 'nobody' } }))
- await new Promise((resolve) => setTimeout(resolve, 20))
- // The half-formed one is dropped rather than delivered to whoever sorts first.
+ const delivered = onceMessage(ws)
+ ws.send(JSON.stringify({ type: 'route_send', payload: { requestId: 's-1', agentId: 'a2', text: 'do the thing' } }))
+ expect((await delivered).payload).toMatchObject({ requestId: 's-1', ok: true })
+
+ // The half-formed one is dropped rather than delivered to whoever sorts first — and it is REFUSED
+ // out loud, because the window is waiting on this id either way.
+ const refused = onceMessage(ws)
+ ws.send(JSON.stringify({ type: 'route_send', payload: { requestId: 's-2', agentId: '', text: 'nobody' } }))
+ expect((await refused).payload).toMatchObject({ requestId: 's-2', ok: false })
+
expect(sent).toEqual([{ agentId: 'a2', text: 'do the thing' }])
expect(backend.frames.map((frame) => frame.type)).toEqual([])
ws.close()
})
+ it('says so when the agent could not be delivered to', async () => {
+ // The remote leg carries no ack of its own: a machine that has gone deaf takes the turn and nothing
+ // comes back. With the palette closing silently on a confident route, that is a task that vanishes
+ // without a mark anywhere — so the refusal has to travel.
+ const backend = new FakeBackend()
+ server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })
+ local = attachLocalWsServer(server, {
+ machineId,
+ backend,
+ onRouteSend: () => ({ ok: false as const, machine: 'mac-mini', reason: 'the last request to it did not come back' }),
+ })
+ 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
+
+ const answered = onceMessage(ws)
+ ws.send(JSON.stringify({ type: 'route_send', payload: { requestId: 's-3', agentId: 'a9', text: 'work' } }))
+ expect((await answered).payload).toMatchObject({
+ requestId: 's-3', ok: false, machine: 'mac-mini', reason: 'the last request to it did not come back',
+ })
+ ws.close()
+ })
+
it('does not require a credential on the loopback transport', async () => {
const url = await start(new FakeBackend())
const ws = new WebSocket(url, ['legacy-client-label'])
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 838fb5619..6fe9ec754 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -39,20 +39,32 @@ export interface LocalWsServerOptions {
* here, where nothing knows what the person is looking at.
*/
onRouteTask?: (text: string) => Promise<RouteAnswer>
- /** The window committed to an agent — deliver the task the way every other message is delivered. */
- onRouteSend?: (agentId: string, text: string) => void
+ /**
+ * The window committed to an agent — deliver the task, and SAY whether it could be delivered.
+ *
+ * It answers for the same reason `route_task` does. The remote leg carries no ack of its own, so a
+ * machine that has gone deaf takes the turn and nothing comes back; with the palette closing silently
+ * 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 }
}
/** One candidate, as the window draws it in the picker. */
export interface RouteCandidate {
agentId: string
+ /** Which machine to open the pane on. Names are for reading; this is for acting. */
+ machineId: string
name: string
+ /** Which computer it runs on. The list spans every machine, and two agents called "api" on two of them
+ * are otherwise the same row twice. */
+ machine: string
/** What it was last doing — the line under the name when the window has to ask. */
recent: string
}
export interface RouteAnswer {
agentId: string
+ machineId: string
name: string
confidence: number
reason: string
@@ -254,12 +266,12 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
const text = typeof payload?.text === 'string' ? payload.text.trim() : ''
// An answer ALWAYS goes back, even for a question we cannot serve: the window is holding a
// spinner open on this id, and silence is the one reply it cannot recover from.
- let answer: RouteAnswer = { agentId: '', name: '', confidence: 0, reason: 'empty task', candidates: [] }
+ let answer: RouteAnswer = { agentId: '', machineId: '', name: '', confidence: 0, reason: 'empty task', candidates: [] }
if (text) {
try {
answer = await options.onRouteTask(text)
} catch (err) {
- answer = { agentId: '', name: '', confidence: 0, reason: (err as Error).message.slice(0, 120), candidates: [] }
+ answer = { agentId: '', machineId: '', name: '', confidence: 0, reason: (err as Error).message.slice(0, 120), candidates: [] }
}
}
sink.sendFrame({ type: 'route_result', payload: { requestId, ...answer } })
@@ -267,9 +279,24 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
}
if (asked?.type === 'route_send' && options.onRouteSend) {
const payload = asked.payload as Record<string, unknown> | undefined
+ const requestId = typeof payload?.requestId === 'string' ? payload.requestId : ''
const agentId = typeof payload?.agentId === 'string' ? payload.agentId : ''
const text = typeof payload?.text === 'string' ? payload.text : ''
- if (agentId && text) options.onRouteSend(agentId, text)
+ let sent: { ok: true } | { ok: false; machine: string; reason: string } =
+ { ok: false, machine: '', reason: 'nothing to send' }
+ if (agentId && text) {
+ try {
+ sent = options.onRouteSend(agentId, text)
+ } catch (err) {
+ sent = { ok: false, machine: '', reason: (err as Error).message.slice(0, 120) }
+ }
+ }
+ sink.sendFrame({
+ type: 'route_send_result',
+ payload: sent.ok
+ ? { requestId, ok: true }
+ : { requestId, ok: false, machine: sent.machine, reason: sent.reason },
+ })
return
}
}