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.

harnessd: devices D0, the fleet as a service, proven across two machines (#784)

Dee8c20ac41f934
diff --git a/cli/e2e/fleet.e2e.ts b/cli/e2e/fleet.e2e.ts
new file mode 100644
index 000000000..40d19c6ed
--- /dev/null
+++ b/cli/e2e/fleet.e2e.ts
@@ -0,0 +1,213 @@
+/**
+ * Two machines on one account, end to end (harness/fleet.ts): real daemons for A and B, signed in to a
+ * fake backend whose relay is blind, A linked to B, and a dial on A. What A's fleet does reaches B's
+ * agents for real: ⌘K picks an agent on B and delivers to it; the dial on A stops, answers and forks
+ * there; B going away is refused rather than lost, and B coming back is used again; and A's fleet
+ * service failing costs A its routing and nothing else.
+ */
+import { randomUUID } from 'node:crypto'
+import { mkdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { until, type IsolatedDaemon } from './harness/daemon.js'
+import { startFleet, type Fleet } from './harness/fleet.js'
+
+const row = async (client: LocalClient, agentId: string) =>
+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)
+ .find((agent) => agent.id === agentId)
+
+/** Start a Claude Code agent and wait for it to bind its conversation. */
+async function boundAgent(daemon: IsolatedDaemon, client: LocalClient, name: string): Promise<string> {
+ const cwd = join(daemon.projectsDir, name)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 60_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agentId: string = created.agent.id
+ await until('the agent to bind its conversation', async () => (await row(client, agentId))?.sessionId || null, 45_000, 500)
+ return agentId
+}
+
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+
+/** ⌘K's pick for a typed task: `route_task` answers as `route_result`, under the asker's request id. */
+async function routeTask(client: LocalClient, text: string): Promise<Record<string, any>> {
+ const requestId = randomUUID()
+ const answered = client.next((frame) => frame.type === 'route_result' && frame.payload?.requestId === requestId, 30_000, 'route_result')
+ client.send('route_task', { requestId, text })
+ return (await answered).payload as Record<string, any>
+}
+
+const routeSend = (client: LocalClient, agentId: string, text: string) =>
+ client.request('route_send', { agentId, text }, 30_000)
+
+const notWorking = (client: LocalClient, agentId: string) =>
+ until('the agent to read as not working', async () => {
+ const agent = await row(client, agentId)
+ return agent && agent.activity?.state !== 'working' ? agent : null
+ }, 30_000, 250)
+
+/** Both machines up, an agent on B, A's dial plugged in, and A's fleet listing that agent. */
+async function linked(fleet: Fleet): Promise<{ onA: LocalClient; onB: LocalClient; agentId: string }> {
+ const { a, b, backend, dial } = fleet
+ await until('both machines connected to the backend', () => backend.nodeUp(a.machineId) && backend.nodeUp(b.machineId), 30_000)
+ const onB = await LocalClient.connect(b.daemon, { machineId: b.machineId })
+ const onA = await LocalClient.connect(a.daemon, { machineId: a.machineId })
+ const agentId = await boundAgent(b.daemon, onB, 'lives-on-b')
+ // The dial on A is what opens A's lane to the other machines: a daemon holds it on a dial's behalf.
+ await dial!.greet()
+ await until('A to list the agent on B', async () => (await routeTask(onA, 'anything')).agentId === agentId || null, 60_000, 1_000)
+ return { onA, onB, agentId }
+}
+
+describe('two machines in one fleet', () => {
+ let fleet: Fleet | undefined
+ afterEach(async () => { await fleet?.close(); fleet = undefined })
+
+ const fresh = async (options: Parameters<typeof startFleet>[0] = {}): Promise<Fleet> => {
+ const f = await startFleet(options)
+ fleet = f
+ onTestFailed(() => {
+ for (const [name, machine] of [['A', f.a], ['B', f.b]] as const) {
+ console.log(`---- daemon ${name} log\n${machine.daemon.log().split('\n').slice(-120).join('\n')}`)
+ }
+ console.log(`---- fake backend saw\n${f.backend.seen.slice(-60).join('\n')}`)
+ console.log(`---- the dial heard\n${f.dial?.messages.map((m) => m.t).join(' ') ?? '(no dial)'}`)
+ })
+ return f
+ }
+
+ it('⌘K on A picks the agent on B, and its send is the turn B runs', async () => {
+ const f = await fresh({ dialOnA: true })
+ const { a, b, backend } = f
+ const { onA, onB, agentId } = await linked(f)
+ expect(backend.devicesOpen()).toBe(1)
+ // Through an end-to-end encrypted session with B, which the relay could not read.
+ expect(a.daemon.log()).toContain(`[device] device: e2e session ready ${b.machineId}`)
+ // A has no agent of its own: the one agent ⌘K can weigh is B's, on B's machine id.
+ const picked = await routeTask(onA, 'fix the parser')
+ expect(picked).toMatchObject({ agentId, machineId: b.machineId, weighed: 1, machines: 1 })
+ expect(picked.candidates[0]).toMatchObject({ agentId, machineId: b.machineId, machine: 'machine-b' })
+
+ const started = onB.next(isTurn('turn_started', agentId), 30_000, 'turn_started on B')
+ const ended = onB.next(isTurn('turn_ended', agentId), 30_000, 'turn_ended on B')
+ expect(await routeSend(onA, agentId, 'sent from machine a')).toMatchObject({ ok: true })
+ expect((await started).payload?.userMessage).toBe('sent from machine a')
+ await ended
+ // Nothing tried to reach anywhere but the fake backend, and both daemons are the cores they started as.
+ for (const machine of [a, b]) {
+ expect(machine.daemon.log()).not.toMatch(/getaddrinfo|ENOTFOUND|autonomous\.ai/)
+ expect(machine.daemon.coresStarted()).toBe(1)
+ }
+ onA.close()
+ onB.close()
+ })
+
+ it('the dial on A stops a turn, answers a question and forks an agent, each on B', async () => {
+ const f = await fresh({ dialOnA: true })
+ const { b } = f
+ const dial = f.dial!
+ const { onA, onB, agentId } = await linked(f)
+
+ // Stop: a turn held open on B ends when the dial on A says stop.
+ const started = onB.next(isTurn('turn_started', agentId), 30_000, 'turn_started on B')
+ expect(await routeSend(onA, agentId, '!hold')).toMatchObject({ ok: true })
+ await started
+ await until('the agent on B to read as working', async () => (await row(onB, agentId))?.activity?.state === 'working' || null, 15_000, 250)
+ dial.send({ t: 'turn.stop', agentId })
+ await notWorking(onB, agentId)
+
+ // Answer: B's agent asks; the question reaches the dial on A, and the dial's answer is the one B's agent gets.
+ const asked = onB.next((frame) => frame.type === 'commander_question' && frame.agentId === agentId, 30_000, 'commander_question on B')
+ const since = dial.messages.length
+ expect(await routeSend(onA, agentId, '!ask')).toMatchObject({ ok: true })
+ const question = await asked
+ const shaped = question.payload?.questions?.[0]
+ expect(shaped?.options).toEqual(expect.arrayContaining(['Tea', 'Coffee']))
+ await dial.next((m) => m.t === 'question' && m.agentId === agentId, 30_000, 'the question from B', since)
+ const ended = onB.next(isTurn('turn_ended', agentId), 45_000, 'turn_ended on B')
+ dial.send({ t: 'answer', agentId, requestId: question.payload.requestId, answers: { [shaped.q]: 'Coffee' } })
+ await ended
+ const pane = String((await row(onB, agentId))?.tmuxPane)
+ expect(await b.daemon.capture(pane)).toContain('you chose Coffee')
+
+ // Fork: the dial forks B's agent on B, and the window on A is told where the fork is.
+ const forked = onA.next((frame) => frame.type === 'dial_forked' && frame.payload?.sourceAgentId === agentId, 60_000, 'dial_forked on A')
+ dial.send({ t: 'agent.fork', agentId })
+ const fork = (await forked).payload as { machineId: string; agentId: string }
+ expect(fork.machineId).toBe(b.machineId)
+ expect(fork.agentId).not.toBe(agentId)
+ await until('the fork to be an agent on B', async () => (await row(onB, fork.agentId)) ?? null, 30_000, 500)
+ onA.close()
+ onB.close()
+ })
+
+ it('B going away is refused, not lost, and B coming back is used again', async () => {
+ const f = await fresh({ dialOnA: true })
+ const { a, b, backend } = f
+ const { onA, onB, agentId } = await linked(f)
+ onB.close()
+ // B's daemon dies. The backend still lists B as running, as the real one does until B's presence
+ // runs out, so A goes on asking B for its agents — and those requests never come back.
+ await b.daemon.kill()
+ await until('B to be gone from the backend', () => !backend.nodeUp(b.machineId), 15_000)
+ const refused = await until('A to refuse a turn for B', async () => {
+ const sent = await routeSend(onA, agentId, 'while machine b is away')
+ return sent.ok === false ? sent : null
+ }, 45_000, 500)
+ expect(refused).toMatchObject({ ok: false, machine: 'machine-b', reason: 'the last request to it did not come back' })
+ expect(a.daemon.log()).toContain(`cable: refused a turn for ${agentId.slice(0, 8)} — machine-b last failed`)
+
+ // B comes back with its agent, which lived on in its terminal. A asks again, opens a new session with
+ // the new process, lists the agent again, and delivers to it.
+ await b.daemon.start()
+ const again = await LocalClient.connect(b.daemon, { machineId: b.machineId })
+ await until('the agent on B to be back', async () => (await row(again, agentId))?.sessionId || null, 45_000, 500)
+ const delivered = await until('A to deliver to B again', async () => {
+ if ((await routeTask(onA, 'anything')).agentId !== agentId) return null
+ const started = again.next(isTurn('turn_started', agentId), 10_000, 'turn_started on B')
+ const sent = await routeSend(onA, agentId, 'machine b is back')
+ if (!sent.ok) { started.catch(() => {}); return null }
+ return (await started.catch(() => null))?.payload?.userMessage === 'machine b is back' ? sent : null
+ }, 120_000, 1_000)
+ expect(delivered).toMatchObject({ ok: true })
+ again.close()
+ onA.close()
+ })
+
+ it('A\'s fleet service failing costs A its routing to B and nothing else', async () => {
+ for (const [faults, reason] of [['fleet', 'no agent list yet'], ['fleet.routeTask,fleet.sendTurn', 'the fleet service is unavailable']]) {
+ const f = await startFleet({ dialOnA: true, envA: { HARNESSD_TEST_FAULTS: faults } })
+ fleet = f
+ onTestFailed(() => { console.log(`---- daemon A log (${faults})\n${f.a.daemon.log().split('\n').slice(-80).join('\n')}`) })
+ const { a, b, backend } = f
+ const dial = f.dial!
+ await until('both machines connected to the backend', () => backend.nodeUp(a.machineId) && backend.nodeUp(b.machineId), 30_000)
+ const onA = await LocalClient.connect(a.daemon, { machineId: a.machineId })
+ const onB = await LocalClient.connect(b.daemon, { machineId: b.machineId })
+ const onlyB = await boundAgent(b.daemon, onB, 'on-b')
+ await dial.greet()
+ // ⌘K on A says it cannot route, and sends nothing.
+ expect(await routeTask(onA, 'anything')).toMatchObject({ agentId: '', reason, candidates: [] })
+ expect(await routeSend(onA, onlyB, 'not delivered')).toMatchObject({ ok: false, machine: '', reason })
+ // Everything else on A goes on: its own agents' turns, its link to the backend, its dial.
+ const onlyA = await boundAgent(a.daemon, onA, 'on-a')
+ const started = onA.next(isTurn('turn_started', onlyA), 30_000, 'turn_started on A')
+ const ended = onA.next(isTurn('turn_ended', onlyA), 30_000, 'turn_ended on A')
+ dial.send({ t: 'turn.send', agentId: onlyA, text: 'from the dial on a' })
+ expect((await started).payload?.userMessage).toBe('from the dial on a')
+ await ended
+ expect(backend.nodeUp(a.machineId)).toBe(true)
+ // And B is untouched.
+ const startedB = onB.next(isTurn('turn_started', onlyB), 30_000, 'turn_started on B')
+ onB.send('message', { agentId: onlyB, content: 'b runs on' })
+ expect((await startedB).payload?.userMessage).toBe('b runs on')
+ expect(a.daemon.log()).toContain(faults === 'fleet' ? '[services] fleet did not start · injected fault: fleet' : '[services] fleet.sendTurn failed · injected fault: fleet.sendTurn')
+ expect(a.daemon.coresStarted()).toBe(1)
+ onA.close()
+ onB.close()
+ await f.close()
+ fleet = undefined
+ }
+ })
+})
diff --git a/cli/e2e/harness/client.ts b/cli/e2e/harness/client.ts
index 7150add06..723d7d67f 100644
--- a/cli/e2e/harness/client.ts
+++ b/cli/e2e/harness/client.ts
@@ -41,7 +41,9 @@ export class LocalClient {
ws.on('close', (code) => { this.closed = true; this.closeCode = code })
}
- static async connect(daemon: IsolatedDaemon, options: { tcp?: boolean; tool?: boolean } = {}): Promise<LocalClient> {
+ /** `machineId`: the machine to select — a signed-in daemon serves under its account's machine id, a
+ * signed-out one under its computer id (the default). */
+ static async connect(daemon: IsolatedDaemon, options: { tcp?: boolean; tool?: boolean; machineId?: string } = {}): Promise<LocalClient> {
const url = options.tcp
? `ws://127.0.0.1:${daemon.port}/api/local-ws`
: `ws+unix://${daemon.socketPath}:/api/local-ws`
@@ -51,7 +53,7 @@ export class LocalClient {
ws.once('error', reject)
})
const client = new LocalClient(ws)
- client.send('machine_select', { machineId: daemon.computerId, localProtocolVersion: 1, ...(options.tool ? { tool: true } : {}) })
+ client.send('machine_select', { machineId: options.machineId ?? daemon.computerId, localProtocolVersion: 1, ...(options.tool ? { tool: true } : {}) })
await client.waitFor((frame) => frame.type === 'connected', 10_000, 'connected')
return client
}
diff --git a/cli/e2e/harness/fakeBackend.ts b/cli/e2e/harness/fakeBackend.ts
new file mode 100644
index 000000000..44cc58eb7
--- /dev/null
+++ b/cli/e2e/harness/fakeBackend.ts
@@ -0,0 +1,240 @@
+/**
+ * The Harness backend, faked on 127.0.0.1, for a fleet of isolated daemons signed in to one account:
+ * enough of its control plane and relay for two machines to find and reach each other, and nothing
+ * that leaves this machine.
+ *
+ * - `GET /api/machines`: the account's machines, each `running` or `offline` as the test says.
+ * - `/api/adapter-ws`: each daemon's own socket, as the node of its machine. Frames for it arrive as
+ * `{t:'down', connId, frame}`; what it sends comes back as `{t:'up', targetConnId?, commanderEligible?, frame}`.
+ * - `/api/device-ws`: a daemon's lane to its owner's other machines, as a device holding a commander
+ * on every machine of the account (`multi_machine`). A frame tagged with a machine id goes down to
+ * that machine's node, an untagged one to the machine selected; a reply to that commander comes back
+ * up tagged with the machine it is from, which is how the device knows which session opens it.
+ *
+ * Like the real relay it is blind: the machines seal everything between them end to end, and a frame
+ * for a machine whose node is not connected is simply never answered, as the real hub's would not be.
+ * Everything else is answered 404. Requests are recorded in `seen`, so a test can say what was asked.
+ */
+import { randomUUID } from 'node:crypto'
+import { createServer, type IncomingMessage, type Server } from 'node:http'
+import type { Duplex } from 'node:stream'
+import { WebSocket, WebSocketServer, type RawData } from 'ws'
+
+export interface FakeMachine {
+ machineId: string
+ computerId: string
+ name: string
+ /** The access token this machine's daemon signs in with. */
+ token: string
+}
+
+type Frame = { type?: string; machineId?: string; agentId?: string; payload?: Record<string, unknown>; [key: string]: unknown }
+
+/** One device socket: a commander on every machine of the account, one connection id per machine. */
+interface Device {
+ ws: WebSocket
+ selected: string
+ conns: Map<string, string>
+}
+
+const json = (value: unknown): string => JSON.stringify(value)
+
+export class FakeBackend {
+ readonly seen: string[] = []
+ private readonly machines = new Map<string, FakeMachine>()
+ private readonly online = new Map<string, boolean>()
+ private readonly nodes = new Map<string, WebSocket>()
+ private readonly devices = new Set<Device>()
+ private readonly connOwners = new Map<string, { device: Device; machineId: string }>()
+ private readonly wss = new WebSocketServer({ noServer: true, handleProtocols: (protocols) => [...protocols][0] ?? false })
+ private generation = 0
+
+ private constructor(private readonly server: Server, readonly port: number) {}
+
+ static async start(): Promise<FakeBackend> {
+ const server = createServer()
+ await new Promise<void>((done) => server.listen(0, '127.0.0.1', done))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('the fake backend has no port')
+ const backend = new FakeBackend(server, address.port)
+ server.on('request', (req, res) => {
+ backend.seen.push(`${req.method} ${req.url}`)
+ const machine = backend.byToken(req)
+ res.setHeader('content-type', 'application/json')
+ if (!machine) { res.statusCode = 401; res.end(json({ success: false, error: { code: 'UNAUTHORIZED' } })); return }
+ if (req.method === 'GET' && req.url?.split('?')[0] === '/api/machines') {
+ res.end(json({ success: true, data: { machines: backend.rows() } }))
+ return
+ }
+ res.statusCode = 404
+ res.end(json({ success: false, error: { code: 'NOT_FOUND', message: 'not on the fake backend' } }))
+ })
+ server.on('upgrade', (req, socket, head) => backend.upgrade(req, socket, head))
+ return backend
+ }
+
+ get httpUrl(): string { return `http://127.0.0.1:${this.port}` }
+ get wsUrl(): string { return `ws://127.0.0.1:${this.port}` }
+
+ addMachine(machine: FakeMachine): void {
+ this.machines.set(machine.machineId, machine)
+ this.online.set(machine.machineId, true)
+ }
+
+ /** What the account's machine list and the live status say about a machine — the backend's view,
+ * which lags the machine itself: a node that just went away is still `running` here until this says. */
+ setOnline(machineId: string, online: boolean): void {
+ this.online.set(machineId, online)
+ for (const device of this.devices) this.sendDevice(device, { type: 'machines_status', payload: { statuses: this.statuses() } })
+ }
+
+ /** Whether this machine's daemon is connected as its node right now. */
+ nodeUp(machineId: string): boolean {
+ return this.nodes.get(machineId)?.readyState === WebSocket.OPEN
+ }
+
+ /** How many device sockets are open: a daemon's lane to the other machines. */
+ devicesOpen(): number {
+ return [...this.devices].filter((device) => device.ws.readyState === WebSocket.OPEN).length
+ }
+
+ async close(): Promise<void> {
+ for (const client of this.wss.clients) client.terminate()
+ await new Promise<void>((done) => this.wss.close(() => done()))
+ await new Promise<void>((done) => this.server.close(() => done()))
+ }
+
+ private rows(): Array<Record<string, unknown>> {
+ return [...this.machines.values()].map((m) => ({
+ machineId: m.machineId, computerId: m.computerId, name: m.name, hostname: m.name,
+ status: this.online.get(m.machineId) ? 'running' : 'offline', authMode: 'remote',
+ }))
+ }
+
+ private statuses(): Array<{ machineId: string; online: boolean }> {
+ return [...this.machines.keys()].map((machineId) => ({ machineId, online: this.online.get(machineId) === true }))
+ }
+
+ private byToken(req: IncomingMessage): FakeMachine | undefined {
+ const bearer = /^Bearer (.+)$/.exec(String(req.headers.authorization ?? ''))?.[1]
+ const offered = String(req.headers['sec-websocket-protocol'] ?? '').split(',')[0]?.trim()
+ const token = bearer ?? offered
+ return token ? [...this.machines.values()].find((m) => m.token === token) : undefined
+ }
+
+ private upgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void {
+ const url = new URL(req.url ?? '/', this.httpUrl)
+ this.seen.push(`WS ${url.pathname}`)
+ const machine = this.byToken(req)
+ const refuse = (status: number, text: string): void => {
+ socket.end(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
+ }
+ if (!machine) { refuse(401, 'Unauthorized'); return }
+ if (url.pathname === '/api/adapter-ws') {
+ // The node is the machine that signed in, on the computer it says it is.
+ if (url.searchParams.get('computer') !== machine.computerId) { refuse(403, 'Forbidden'); return }
+ this.wss.handleUpgrade(req, socket, head, (ws) => this.attachNode(machine, ws))
+ return
+ }
+ if (url.pathname === '/api/device-ws') {
+ this.wss.handleUpgrade(req, socket, head, (ws) => this.attachDevice(ws))
+ return
+ }
+ refuse(404, 'Not Found')
+ }
+
+ // ── nodes ────────────────────────────────────────────────────────────────────────────────────
+
+ private attachNode(machine: FakeMachine, ws: WebSocket): void {
+ this.nodes.get(machine.machineId)?.terminate()
+ this.nodes.set(machine.machineId, ws)
+ // What the real backend says first: the machine's name, and how many commanders are watching it.
+ this.sendNode(machine.machineId, '', { type: 'machine_meta', payload: { name: machine.name } })
+ this.sendClients(machine.machineId)
+ ws.on('message', (raw, binary) => { if (!binary) this.fromNode(machine.machineId, raw) })
+ ws.on('close', () => { if (this.nodes.get(machine.machineId) === ws) this.nodes.delete(machine.machineId) })
+ }
+
+ private fromNode(machineId: string, raw: RawData): void {
+ let envelope: { t?: string; targetConnId?: string; commanderEligible?: boolean; frame?: Frame }
+ try { envelope = JSON.parse(raw.toString()) } catch { return }
+ if (envelope.t !== 'up' || !envelope.frame) return
+ const tagged = { ...envelope.frame, machineId }
+ if (envelope.targetConnId) {
+ const owner = this.connOwners.get(envelope.targetConnId)
+ if (owner?.machineId === machineId) this.sendDevice(owner.device, tagged)
+ return
+ }
+ if (envelope.commanderEligible) for (const device of this.devices) this.sendDevice(device, tagged)
+ }
+
+ private sendNode(machineId: string, connId: string, frame: Frame): boolean {
+ const ws = this.nodes.get(machineId)
+ if (ws?.readyState !== WebSocket.OPEN) return false
+ ws.send(json({ t: 'down', connId, frame }))
+ return true
+ }
+
+ private sendClients(machineId: string): void {
+ const commanders = [...this.devices].filter((device) => device.ws.readyState === WebSocket.OPEN).length
+ this.sendNode(machineId, '', {
+ type: '__clients',
+ payload: { commander: commanders, commanderActive: commanders, commanderJoinGeneration: this.generation },
+ })
+ }
+
+ // ── devices ──────────────────────────────────────────────────────────────────────────────────
+
+ private attachDevice(ws: WebSocket): void {
+ const device: Device = { ws, selected: '', conns: new Map() }
+ for (const machineId of this.machines.keys()) {
+ const connId = `device:${randomUUID()}`
+ device.conns.set(machineId, connId)
+ this.connOwners.set(connId, { device, machineId })
+ }
+ this.devices.add(device)
+ this.generation++
+ for (const machineId of this.machines.keys()) this.sendClients(machineId)
+ ws.on('message', (raw, binary) => { if (!binary) this.fromDevice(device, raw) })
+ ws.on('close', () => {
+ this.devices.delete(device)
+ this.generation++
+ for (const [machineId, connId] of device.conns) {
+ this.connOwners.delete(connId)
+ this.sendNode(machineId, connId, { type: '__client_disconnected', payload: {} })
+ this.sendClients(machineId)
+ }
+ })
+ }
+
+ private fromDevice(device: Device, raw: RawData): void {
+ let frame: Frame
+ try { frame = JSON.parse(raw.toString()) as Frame } catch { return }
+ const type = frame.type ?? ''
+ if (type === 'device_hello' || type === 'ping') return
+ if (type === 'machines_watch') {
+ this.sendDevice(device, { type: 'machines_status', payload: { statuses: this.statuses() } })
+ return
+ }
+ if (type === 'machine_select') {
+ const machineId = String(frame.payload?.machineId ?? '')
+ if (!this.machines.has(machineId)) {
+ this.sendDevice(device, { type: 'machine_select_error', payload: { error: 'NOT_YOUR_MACHINE' } })
+ return
+ }
+ device.selected = machineId
+ this.sendDevice(device, { type: 'machine_selected', payload: { machineId } })
+ return
+ }
+ if (type === 'machine_deselect') { device.selected = ''; return }
+ // Everything else is for a machine: the one it is tagged for, or the one selected. Never answered
+ // here: a node that is not connected leaves it unanswered, as the real hub does.
+ const machineId = frame.machineId && device.conns.has(frame.machineId) ? frame.machineId : device.selected
+ const connId = device.conns.get(machineId)
+ if (connId) this.sendNode(machineId, connId, frame)
+ }
+
+ private sendDevice(device: Device, frame: Frame): void {
+ if (device.ws.readyState === WebSocket.OPEN) device.ws.send(json(frame))
+ }
+}
diff --git a/cli/e2e/harness/fakeDial.ts b/cli/e2e/harness/fakeDial.ts
new file mode 100644
index 000000000..54e7f9956
--- /dev/null
+++ b/cli/e2e/harness/fakeDial.ts
@@ -0,0 +1,89 @@
+/**
+ * A dial for a daemon under test, on a pseudo-terminal (ptyBridge.py): it greets the daemon the way the
+ * firmware does and speaks the cable protocol with the daemon's own frame codec (src/cable/cableFrame.ts),
+ * so what it sends reaches the dial's host exactly as a press on real glass would.
+ *
+ * The daemon finds it through `HARNESSD_TEST_DIAL_PORT`, the one thing that differs from a dial on USB:
+ * a pseudo-terminal is not on the USB bus that discovery reads.
+ */
+import { spawn, type ChildProcess } from 'node:child_process'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { CableDecoder, CableType, encodeCableFrame } from '../../src/cable/cableFrame.js'
+
+const here = dirname(fileURLToPath(import.meta.url))
+
+export type DialMessage = Record<string, unknown> & { t?: string }
+
+export class FakeDial {
+ readonly messages: DialMessage[] = []
+ private readonly decoder = new CableDecoder()
+
+ private constructor(private readonly bridge: ChildProcess, readonly path: string) {
+ bridge.stdout!.on('data', (chunk: Buffer) => {
+ this.decoder.feed(chunk, (frame) => {
+ if (frame.type !== CableType.Json) return
+ let message: DialMessage
+ try { message = JSON.parse(Buffer.from(frame.payload).toString('utf8')) as DialMessage } catch { return }
+ this.messages.push(message)
+ // A dial that stops answering for 20 seconds is taken as unplugged (cableSession SILENCE_MS).
+ if (message.t === 'ping') this.send({ t: 'pong' })
+ })
+ })
+ }
+
+ static async open(): Promise<FakeDial> {
+ const bridge = spawn('python3', [join(here, 'ptyBridge.py')], { stdio: ['pipe', 'pipe', 'pipe'] })
+ const path = await new Promise<string>((resolve, reject) => {
+ let said = ''
+ const timer = setTimeout(() => reject(new Error(`the pseudo-terminal did not open: ${said}`)), 10_000)
+ bridge.stderr!.on('data', (chunk: Buffer) => {
+ said += chunk.toString('utf8')
+ const line = said.split('\n')[0]
+ if (said.includes('\n') && line.startsWith('/dev/')) { clearTimeout(timer); resolve(line) }
+ })
+ bridge.once('exit', (code) => { clearTimeout(timer); reject(new Error(`the pseudo-terminal bridge exited (${code}): ${said}`)) })
+ })
+ return new FakeDial(bridge, path)
+ }
+
+ send(message: DialMessage): void {
+ this.bridge.stdin!.write(encodeCableFrame(CableType.Json, Buffer.from(JSON.stringify(message), 'utf8')))
+ }
+
+ /** The first message from the daemon that passes `test`, waiting up to `ms` for it. */
+ async next(test: (message: DialMessage) => boolean, ms = 20_000, what = 'a message', since = 0): Promise<DialMessage> {
+ const deadline = Date.now() + ms
+ for (;;) {
+ const found = this.messages.slice(since).find(test)
+ if (found) return found
+ if (Date.now() > deadline) throw new Error(`the dial heard no ${what} in ${ms}ms (heard: ${this.messages.map((m) => m.t).join(', ') || 'nothing'})`)
+ await new Promise((done) => setTimeout(done, 100))
+ }
+ }
+
+ /**
+ * Greet the daemon as the firmware does, again and again until it answers: the daemon opens the port
+ * on its own scan, and a greeting sent before then lands on nobody.
+ */
+ async greet(ms = 60_000): Promise<DialMessage> {
+ const hello: DialMessage = { t: 'hello', product: 'harness', proto: 3, mac: 'e2:e0:00:00:00:01', fw: '0.0.0-e2e', hw: 'e2e' }
+ const deadline = Date.now() + ms
+ for (;;) {
+ this.send(hello)
+ const welcome = this.messages.find((m) => m.t === 'welcome')
+ if (welcome) return welcome
+ if (Date.now() > deadline) throw new Error(`the daemon never welcomed the dial (heard: ${this.messages.map((m) => m.t).join(', ') || 'nothing'})`)
+ await new Promise((done) => setTimeout(done, 500))
+ }
+ }
+
+ async close(): Promise<void> {
+ if (this.bridge.exitCode !== null) return
+ const exited = new Promise<void>((done) => this.bridge.once('exit', () => done()))
+ this.bridge.stdin!.end()
+ const timer = setTimeout(() => this.bridge.kill('SIGKILL'), 3_000)
+ await exited
+ clearTimeout(timer)
+ }
+}
diff --git a/cli/e2e/harness/fleet.ts b/cli/e2e/harness/fleet.ts
new file mode 100644
index 000000000..9a99e3605
--- /dev/null
+++ b/cli/e2e/harness/fleet.ts
@@ -0,0 +1,141 @@
+/**
+ * Two machines on one account: two real daemons, each under its own throwaway home, private tmux server
+ * and fake engines, with its own computer id, machine id and E2EE identity, signed in to one fake backend
+ * (fakeBackend.ts) and linked the way `harness link connect` leaves two machines — A holds B's key
+ * pinned, B trusts A's — so that A's lane to B opens a real end-to-end encrypted session through the
+ * fake relay. Machine A can have a dial on a pseudo-terminal (fakeDial.ts), which is what opens that
+ * lane: a daemon holds it on a dial's behalf.
+ *
+ * Nothing reaches beyond this machine. Every URL the daemon has a setting for points at the fake, and
+ * `assertLocalOnly` refuses to start a daemon whose environment names anything else.
+ */
+import { mkdir, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { b64e, newIdentity, type Identity } from '../../src/lib/e2ee/core.js'
+import { IsolatedDaemon, type DaemonOptions } from './daemon.js'
+import { FakeBackend, type FakeMachine } from './fakeBackend.js'
+import { FakeDial } from './fakeDial.js'
+
+export interface FleetMachine extends FakeMachine {
+ daemon: IsolatedDaemon
+ identity: Identity
+}
+
+export interface Fleet {
+ backend: FakeBackend
+ a: FleetMachine
+ b: FleetMachine
+ /** A's dial, when it has one. */
+ dial: FakeDial | null
+ close(): Promise<void>
+}
+
+export interface FleetOptions {
+ /** Plug a dial into A: its attach is what opens A's lane to B. */
+ dialOnA?: boolean
+ envA?: Record<string, string>
+ envB?: Record<string, string>
+}
+
+/** Every daemon setting whose default is a server somewhere else, all pointed at the fake. */
+function remoteSettings(backend: FakeBackend): Record<string, string> {
+ return {
+ BACKEND_WS_URL: backend.wsUrl,
+ WEB_URL: backend.httpUrl,
+ ADAPTER_UPDATE_URL: `${backend.httpUrl}/update/cli.json`,
+ ADAPTER_RUNTIME_METADATA_URL: `${backend.httpUrl}/update/runtime.json`,
+ ADAPTER_GRID_RUNTIME_METADATA_URL: `${backend.httpUrl}/update/grid.json`,
+ CABLE_FW_MANIFEST_URL: `${backend.httpUrl}/update/firmware.json`,
+ }
+}
+
+/** The host a variable names, when its value is a server address; null for anything else. */
+function serverHost(value: string | undefined): string | null {
+ if (typeof value !== 'string' || !/^(https?|wss?):\/\//i.test(value)) return null
+ try { return new URL(value).hostname } catch { return null }
+}
+const loopback = (host: string): boolean => host === '127.0.0.1' || host === 'localhost' || host === '[::1]'
+
+/**
+ * Refuse a daemon whose environment names a server that is not on this machine: the fake backend is
+ * the only one a fleet test may reach. Throws, naming the variable.
+ */
+export function assertLocalOnly(env: NodeJS.ProcessEnv, backend: FakeBackend): void {
+ for (const [key, value] of Object.entries(env)) {
+ const host = serverHost(value)
+ if (host && !loopback(host)) throw new Error(`${key} points at ${host}: a fleet test must reach nothing beyond this machine`)
+ }
+ for (const [key, value] of Object.entries(remoteSettings(backend))) {
+ if (env[key] !== value) throw new Error(`${key} is ${env[key] ?? 'unset'}, not the fake backend`)
+ }
+}
+
+/** Sign a daemon in, as `harness login` leaves a computer: a session for its machine on this account. */
+async function signIn(daemon: IsolatedDaemon, machine: FakeMachine): Promise<void> {
+ await writeFile(join(daemon.root, 'auth', 'session.json'), JSON.stringify({
+ version: 1, accessToken: machine.token, autonomousEnv: 'prod', computerId: machine.computerId,
+ machineId: machine.machineId, expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',
+ }), { mode: 0o600 })
+}
+
+/** The E2EE files `harness link connect` and pairing leave, written before the daemon first starts. */
+async function writeE2ee(daemon: IsolatedDaemon, files: Record<string, unknown>): Promise<void> {
+ const dir = join(daemon.dataDir, 'e2e')
+ await mkdir(dir, { recursive: true, mode: 0o700 })
+ for (const [name, value] of Object.entries(files)) await writeFile(join(dir, name), JSON.stringify(value, null, 2), { mode: 0o600 })
+}
+
+export async function startFleet(options: FleetOptions = {}): Promise<Fleet> {
+ const backend = await FakeBackend.start()
+ const specs: Array<FakeMachine & { identity: Identity }> = [
+ { machineId: 'a1'.repeat(16), computerId: 'e2e-computer-0000-0000-00000000000a', name: 'machine-a', token: 'e2e-token-machine-a', identity: newIdentity() },
+ { machineId: 'b2'.repeat(16), computerId: 'e2e-computer-0000-0000-00000000000b', name: 'machine-b', token: 'e2e-token-machine-b', identity: newIdentity() },
+ ]
+ for (const spec of specs) backend.addMachine(spec)
+ const dial = options.dialOnA ? await FakeDial.open() : null
+ const created: IsolatedDaemon[] = []
+ try {
+ const machines: FleetMachine[] = []
+ for (const [index, spec] of specs.entries()) {
+ const own: DaemonOptions['env'] = index === 0
+ ? { ...(dial ? { CABLE_DISABLE: 'false', HARNESSD_TEST_DIAL_PORT: dial.path } : {}), ...options.envA }
+ : { ...options.envB }
+ const daemon = await IsolatedDaemon.create({ env: { ...remoteSettings(backend), ADAPTER_COMPUTER_ID: spec.computerId, ...own } })
+ created.push(daemon)
+ // The daemon inherits the runner's environment, where a registry or a proxy may be named. None of
+ // them is anywhere a fleet daemon may go.
+ for (const [key, value] of Object.entries(daemon.env)) {
+ const host = serverHost(value)
+ if (host && !loopback(host)) delete daemon.env[key]
+ }
+ assertLocalOnly(daemon.env, backend)
+ await signIn(daemon, spec)
+ machines.push({ ...spec, daemon })
+ }
+ const [a, b] = machines
+ const linkedAt = Date.now()
+ // A pinned B's key when it linked to B; B trusts A back, as a machine (lib/e2ee/manager.ts onPeerLinked).
+ await writeE2ee(a.daemon, {
+ 'identity.json': { priv: b64e(a.identity.priv), pub: b64e(a.identity.pub) },
+ 'machinePeers.json': [{ machineId: b.machineId, pub: b64e(b.identity.pub), label: b.name, linkedAt }],
+ })
+ await writeE2ee(b.daemon, {
+ 'identity.json': { priv: b64e(b.identity.priv), pub: b64e(b.identity.pub) },
+ 'paired.json': [{ identityPub: b64e(a.identity.pub), label: a.name, pairedAt: linkedAt, role: 'web', machineId: a.machineId, kind: 'machine' }],
+ })
+ await Promise.all(machines.map((machine) => machine.daemon.start()))
+ return {
+ backend, a, b, dial,
+ async close() {
+ await dial?.close()
+ await Promise.allSettled(machines.map((machine) => machine.daemon.close()))
+ await backend.close()
+ },
+ }
+ } catch (error) {
+ await dial?.close()
+ await Promise.allSettled(created.map((daemon) => daemon.close()))
+ await backend.close()
+ throw error
+ }
+}
diff --git a/cli/e2e/harness/ptyBridge.py b/cli/e2e/harness/ptyBridge.py
new file mode 100644
index 000000000..18e546b38
--- /dev/null
+++ b/cli/e2e/harness/ptyBridge.py
@@ -0,0 +1,54 @@
+"""A dial's end of a pseudo-terminal, for a daemon under test to open as if a dial were plugged in.
+
+Prints the terminal's path on stderr, then carries bytes both ways: what the daemon writes to the
+terminal comes out on stdout, and what arrives on stdin goes to the daemon. Never enumerates or opens a
+real device: the only terminal touched is the one this process creates.
+
+The terminal's own end is closed here at once. A daemon looks for a port nobody else holds (`lsof`),
+and this process holding it would make the dial look like somebody's work in progress.
+"""
+import os
+import pty
+import select
+import sys
+import time
+import tty
+
+master, slave = pty.openpty()
+# Raw, so the line discipline neither echoes nor rewrites the binary frames before the daemon opens it.
+tty.setraw(slave)
+path = os.ttyname(slave)
+os.close(slave)
+sys.stderr.write(path + '\n')
+sys.stderr.flush()
+
+stdin = sys.stdin.fileno()
+stdout = sys.stdout.fileno()
+os.set_blocking(stdin, False)
+os.set_blocking(master, False)
+pending = b''
+while True:
+ readable, _, _ = select.select([master, stdin], [], [], 0.05)
+ if stdin in readable:
+ try:
+ chunk = os.read(stdin, 65536)
+ except BlockingIOError:
+ chunk = None
+ if chunk == b'':
+ break # the test let go of the dial
+ if chunk:
+ pending += chunk
+ if master in readable:
+ try:
+ data = os.read(master, 65536)
+ if data:
+ os.write(stdout, data)
+ except (BlockingIOError, OSError):
+ # Nobody has the terminal open yet, or the daemon closed it for a moment: wait for it.
+ time.sleep(0.05)
+ if pending:
+ try:
+ written = os.write(master, pending)
+ pending = pending[written:]
+ except (BlockingIOError, OSError):
+ time.sleep(0.05)
diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.ts
index 98fa9c991..8078ea1da 100644
--- a/cli/e2e/services.e2e.ts
+++ b/cli/e2e/services.e2e.ts
@@ -3,6 +3,7 @@
* service made to fail as it starts, and services made to fail on every call, while a client starts an
* agent, the agent binds, messages become turns that start and end, and the daemon restarts.
*/
+import { randomUUID } from 'node:crypto'
import { mkdirSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
@@ -24,6 +25,14 @@ async function boundAgent(daemon: IsolatedDaemon, client: LocalClient, name: str
return agentId
}
+/** ⌘K's pick for a typed task: `route_task` answers as `route_result`, under the asker's request id. */
+async function routeTask(client: LocalClient, text: string): Promise<Record<string, any>> {
+ const requestId = randomUUID()
+ const answered = client.next((frame) => frame.type === 'route_result' && frame.payload?.requestId === requestId, 30_000, 'route_result')
+ client.send('route_task', { requestId, text })
+ return (await answered).payload as Record<string, any>
+}
+
/** One message, one turn: it starts and it ends. */
async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {
const isTurn = (type: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
@@ -163,6 +172,47 @@ describe('a failing service never takes the core down', () => {
client.close()
})
+ it('⌘K picks and delivers through the fleet, with the dial and the window bridges failing on every call', async () => {
+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'dial,window' } })
+ onTestFailed(() => { console.log(`---- daemon log\n${daemon?.log().split('\n').slice(-80).join('\n')}`) })
+ await daemon.start()
+ const client = await LocalClient.connect(daemon)
+ const agentId = await boundAgent(daemon, client, 'routed-by-cmd-k')
+ // The only agent on this computer, picked without asking any model, on this computer's own id.
+ expect(await routeTask(client, 'fix the parser')).toMatchObject({ agentId, machineId: daemon.computerId, confidence: 1, weighed: 1, machines: 1 })
+ const isTurn = (type: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+ const started = client.next(isTurn('turn_started'), 30_000, 'turn_started (route_send)')
+ const ended = client.next(isTurn('turn_ended'), 30_000, 'turn_ended (route_send)')
+ expect(await client.request('route_send', { agentId, text: 'sent by cmd-k' })).toMatchObject({ ok: true })
+ expect((await started).payload?.userMessage).toBe('sent by cmd-k')
+ await ended
+ expect(daemon.log()).toContain('[devices] dial failed · injected fault: dial')
+ expect(daemon.coresStarted()).toBe(1)
+ client.close()
+ })
+
+ it('with the fleet not starting, or failing on every call, ⌘K says so and the core runs its agents on', async () => {
+ for (const [faults, reason, said] of [
+ ['fleet', 'no agent list yet', '[services] fleet did not start · injected fault: fleet · the core runs without it'],
+ ['fleet.routeTask,fleet.sendTurn', 'the fleet service is unavailable', '[services] fleet.sendTurn failed · injected fault: fleet.sendTurn'],
+ ]) {
+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: faults } })
+ const d = daemon
+ onTestFailed(() => { console.log(`---- daemon log (${faults})\n${d.log().split('\n').slice(-80).join('\n')}`) })
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const agentId = await boundAgent(d, client, `fleet-${faults.length}`)
+ expect(await routeTask(client, 'fix the parser')).toMatchObject({ agentId: '', reason, candidates: [] })
+ expect(await client.request('route_send', { agentId, text: 'not delivered' })).toMatchObject({ ok: false, machine: '', reason })
+ await turn(client, agentId, `the core runs on (${faults})`)
+ expect(d.log()).toContain(said)
+ expect(d.coresStarted()).toBe(1)
+ client.close()
+ await d.close()
+ daemon = undefined
+ }
+ })
+
it('the store lists what is installed here and what the registry offers', async () => {
daemon = await IsolatedDaemon.create()
await daemon.start()
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index 2250ee2b2..1cf81df6f 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -61,7 +61,7 @@ function runForegroundLines(): number {
* when you move code out; raising one needs a reason a reviewer agrees with, and the usual one is wrong:
* the code belongs in a module or a service.
*/
-const RUN_FOREGROUND_BUDGET = 2_695
+const RUN_FOREGROUND_BUDGET = 2_572
const BACKEND_SOCKET_BUDGET = 2_975
/** Exceptions, each with its reason. Keep this short. */
diff --git a/cli/src/cable/cableFleet.spec.ts b/cli/src/cable/cableFleet.spec.ts
index 9083b6e1f..9fd95b6e1 100644
--- a/cli/src/cable/cableFleet.spec.ts
+++ b/cli/src/cable/cableFleet.spec.ts
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { describe, expect, it, vi } from 'vitest'
-import { CableFleet as SourceFleet } from './cableFleet.js'
+import { CableFleet as SourceFleet, testDialDiscovery } from './cableFleet.js'
import { CableSession, type CableHost, type CablePort } from './cableSession.js'
import { CableDecoder, CableType, encodeCableFrame } from './cableFrame.js'
import { DialLog } from './dialLog.js'
@@ -64,6 +64,15 @@ function fixture() {
return { fleet, host, ports, options, logs, start, greet, setPorts: (p: DialPort[]) => { present = p } }
}
+describe('the end-to-end suite\'s dial', () => {
+ it('is found at the pseudo-terminal it names, and nothing is changed without one', async () => {
+ expect(testDialDiscovery(undefined)).toEqual({})
+ expect(testDialDiscovery('')).toEqual({})
+ const { discover } = testDialDiscovery('/dev/ttys042')
+ expect(await discover!()).toEqual([{ path: '/dev/ttys042', vendorId: 0x303a, productId: 0x1001, serialNumber: 'E2E-DIAL' }])
+ })
+})
+
describe('USB dial fleet', () => {
it('releases every dial on a macOS user switch and reconnects only when its account returns', async () => {
const f = fixture()
diff --git a/cli/src/cable/cableFleet.ts b/cli/src/cable/cableFleet.ts
index a6478d5de..fde14bec1 100644
--- a/cli/src/cable/cableFleet.ts
+++ b/cli/src/cable/cableFleet.ts
@@ -27,6 +27,16 @@ export interface CableFleetOptions {
watchEveryMs?: number
}
+/**
+ * Discovery for the end-to-end suite's dial, a pseudo-terminal (e2e/harness/fakeDial.ts) named by
+ * `HARNESSD_TEST_DIAL_PORT`: it is not on the USB bus that discovery reads, and it is the only port then
+ * looked at. Nothing otherwise: a real daemon finds its dials on USB.
+ */
+export function testDialDiscovery(path: string | undefined): Pick<CableFleetOptions, 'discover'> {
+ if (!path) return {}
+ return { discover: async () => [{ path, vendorId: 0x303a, productId: 0x1001, serialNumber: 'E2E-DIAL' }] }
+}
+
export class CableFleet {
private entries = new Map<string, Entry>()
private timer?: ReturnType<typeof setInterval>
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index d80ad5006..3bb05c26d 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -8,6 +8,11 @@
// read, the router is the one the backend already calls for remote machines, and the turn events arrive
// as the very `commander_event` cards the WiFi device receives — teed at the socket rather than emitted
// again here, so the two device surfaces cannot drift.
+//
+// Which machine an agent is on, and every turn, stop and answer sent to it, is the fleet's router
+// (services/fleetRouter.ts), shared with ⌘K and the window's voice route. This host asks it; with no
+// router handed in (its tests, or a daemon whose fleet service is off) it builds one over the fleet it
+// is given, which is what it used to hold itself.
import { join } from 'node:path'
import { notificationReadToken, type UnreadNotification } from './notificationRead.js'
@@ -16,14 +21,14 @@ import { registry, projectDisplayName, type RegisteredSession } from '../lib/reg
import { fetchRelease, loadImage, otaKeyForBoard, shouldOffer } from './fwPush.js'
import { routeVoiceTask, type RouterAgent, type RouterContinuity } from '../lib/voiceRouter.js'
import { env } from '../config/env.js'
-import { extendShortRecap } from '../lib/deviceRecap.js'
+import { FleetRouter, type ForkResult } from '../services/fleetRouter.js'
import type { AppSwarms, CableAgent, CableHost, CableMachine, CableMachineSource, CableSwarm, CableTile, DialStatus, OpenReason, RouteDecision } from './cableSession.js'
import type { WindowRoute } from './windowRoute.js'
import type { SelectionCommand, SelectionResult } from './windowSelection.js'
import type { VisitCommand, VisitResult } from './windowVisit.js'
import type { FormCommand, FormResult } from './windowForm.js'
-import { FleetError, type FleetMachine, type MachineFleet } from './machineFleet.js'
+import { FleetError, type MachineFleet } from './machineFleet.js'
import type { ReviewedAnswer, AnswerReceipt } from './questionInbox.js'
/** One completed turn's recap, as the mirror keeps them. */
@@ -89,49 +94,18 @@ export interface CableHostWiring {
log: (line: string) => void
}
-/**
- * A placeholder id for a machine this daemon does not know the real id of.
- *
- * A BELT, not a mode. `harness start` refuses to run without an SSO session and awaits
- * `resolveComputerMachine()` before it spawns the daemon, so by the time anything here runs the machineId
- * is real. The guard exists because the alternative failure is silent: an empty id makes a row that
- * renders, is tappable, and can never be selected. `cable:` is deliberately not machineId-shaped, so
- * nothing downstream mistakes it for one and announces it to the backend.
- */
-function placeholderId(computerId: string): string {
- return `cable:${computerId}`
-}
-
-/** How often another machine's agent list is re-asked. Far slower than the dial's one-second tick: the
- * list changes when a person starts an agent, not continuously. */
-const REMOTE_REFRESH_MS = 5_000
-/** How long a machine's last good list survives failures before its tiles leave the carousel. */
-const REMOTE_GRACE_MS = 30_000
-
-/** Whether an id is that placeholder rather than a machine the backend has heard of. */
+/** Whether an id is the router's placeholder for a machine with no id yet (`cable:` and the computer id;
+ * see services/fleetRouter.ts) rather than a machine the backend has heard of. */
function isPlaceholder(id: string): boolean {
return id.startsWith('cable:')
}
-/** A fleet row as the wire carries it. `authMode` does not travel: the dial has no use for the word, and
- * `remote` is just `!local`, which the row already says. */
-function toCableMachine(m: FleetMachine): CableMachine {
- return { id: m.machineId, name: m.name, state: m.state, local: false }
-}
-
-/** Split `runtime-v1:<sid>:<engine>:<model>@<effort>` back into the two words the dial's chips show. */
-function chipsFromProfile(profile: string | null | undefined): { model?: string; effort?: string } {
- if (!profile || !profile.startsWith('runtime-v1:')) return {}
- const tail = profile.split(':').slice(3).join(':')
- if (!tail) return {}
- const [model, effort] = tail.split('@')
- return { model: model || undefined, effort: effort || undefined }
-}
-
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 }
+ /** Which machine each agent is on, and the turns, stops and answers sent to it: the fleet's router. */
+ private readonly router: FleetRouter
+ /** The lane to the other machines, held on the dial's behalf (`online`, `select`, `release`); the
+ * router's own fleet. `undefined` = no lane exists; the wheel is the local row and nothing else. */
+ private readonly fleet?: MachineFleet
/**
* The machine whose agents are on the dial right now. Defaults to — and falls back to — the local one:
@@ -143,15 +117,22 @@ export class DaemonCableHost implements CableHost {
*/
private selected = ''
- /** Each other machine's agents, as last read. `asked` throttles the round; `at` ages the answer. */
- private readonly remoteAgents = new Map<string, { agents: CableAgent[]; at: number; asked: number }>()
- /** Machines with a list RPC in flight, so a slow machine is asked once rather than every tick. */
- private readonly inFlight = new Set<string>()
- /** agentId → machineId, rebuilt from the snapshot last handed to the dial. */
- private agentMachine = new Map<string, string>()
-
- /** `undefined` = no lane to any other machine exists; the wheel is the local row and nothing else. */
- constructor(private readonly wiring: CableHostWiring, private readonly fleet?: MachineFleet) {}
+ /**
+ * `fleet` is the fleet service's router (services/fleet.ts), which ⌘K and the window's voice route send
+ * through as well, or a bare lane to the other machines this host routes over by itself — its tests,
+ * and a daemon whose fleet service is off. `undefined` = no lane to any other machine exists; the wheel
+ * is the local row and nothing else.
+ */
+ constructor(private readonly wiring: CableHostWiring, fleet?: MachineFleet | FleetRouter) {
+ this.router = fleet instanceof FleetRouter ? fleet : new FleetRouter({
+ ...wiring,
+ // The same set `agents_list` answers the apps with — see the router's localAgents.
+ sessions: () => registry.advertised(),
+ displayName: projectDisplayName,
+ desk: () => this.desk,
+ }, fleet)
+ this.fleet = this.router.fleet
+ }
/** The identity of the computer at the other end of the cable. */
localMachine(): { id: string; name: string } {
@@ -159,7 +140,7 @@ export class DaemonCableHost implements CableHost {
}
private localId(): string {
- return this.wiring.machineId() || placeholderId(this.wiring.computerId())
+ return this.router.localId()
}
/** Whether the dial is looking at THIS computer. Everything forks on this one question. */
@@ -171,27 +152,9 @@ export class DaemonCableHost implements CableHost {
return this.selected || this.localId()
}
- async listMachines(): Promise<{ machines: CableMachine[]; source: CableMachineSource }> {
- const local: CableMachine = {
- id: this.localId(),
- // The machine's own name. What makes this row recognisable as the cabled one is its second line,
- // which the dial writes — see machine_meta_line.
- name: this.wiring.machineName(),
- // Always ready: the cable IS the evidence. Nothing else on this list can say that about itself.
- state: 'ready',
- local: true,
- }
- if (!this.fleet) return { machines: [local], source: 'signed-out' }
- const { machines, source } = await this.fleet.list()
- const rows: CableMachine[] = [local]
- for (const m of machines) {
- // The backend list contains THIS computer too. Dropped rather than rendered: the same machine on
- // the wheel twice, under two names, with the ✓ able to mark only one of them. Its name is already
- // here anyway — MACHINE_NAME_FILE is mirrored from the backend on every connect.
- if (m.machineId === local.id) continue
- rows.push(toCableMachine(m))
- }
- return { machines: rows, source }
+ /** The local row, then the fleet's — the router's list, which ⌘K reads too. */
+ listMachines(): Promise<{ machines: CableMachine[]; source: CableMachineSource }> {
+ return this.router.listMachines()
}
async selectMachine(machineId: string): Promise<{ ok: true } | { ok: false; code: string; message: string }> {
@@ -315,72 +278,16 @@ export class DaemonCableHost implements CableHost {
return locale.startsWith('vi') ? 'vi' : 'en'
}
- /** This computer's own agents, in the order every other surface reads them in. */
- private localAgents(): CableAgent[] {
- // `advertised()`, not `list()` — the SAME set `agents_list` answers the web and the desktop app with. They
- // read one registry and must not disagree about what is on it: a dead agent holding a tile on the dial
- // and nowhere else is a tile that cannot be driven and cannot be explained.
- // Terminals INCLUDED. A shell has no turn to watch and no model to switch, and the dial does not
- // pretend otherwise — it draws the tile and offers no Voice on it. What it does offer is the
- // thing that was missing: the tile can be reached. The window draws a shell as a tile like any
- // other, so a dial that skipped it disagreed with the app about what was on the desk, and a pane
- // the carousel cannot walk to is a pane the dial cannot explain either. A terminal that has
- // adopted an engine is that engine here, as everywhere.
- //
- // ⚠️ NOT the same question as `deviceAgentRow` in backendSocket.ts, which keeps shells out of the
- // `agents_list` RPC a CLOUD device asks over the backend. This is the cable's own list, pulled by
- // `listAgents()` on the session's tick; the two surfaces answer separately and always did.
- const sessions = registry.advertised()
- // Oldest → newest, and TOTAL: the id breaks a tie so the order cannot fall through to array position,
- // which is Map insertion order and differs between daemon runs. Both producers sort identically, so
- // the dial and the app cannot drift apart while reading the same registry.
- sessions.sort((a, b) => a.registeredAt - b.registeredAt || a.agentId.localeCompare(b.agentId))
- const machineId = this.localId()
- const machine = this.wiring.machineName()
- return sessions.map((s) => ({
- id: s.agentId,
- name: projectDisplayName(s),
- engine: s.engine ?? '',
- machineId,
- machine,
- ...chipsFromProfile(this.wiring.runtimeProfile?.(s)),
- }))
- }
-
/**
- * EVERY agent on EVERY machine, in the order the desktop app's rail reads them: this computer first,
- * then each other machine in wheel order, and within a machine whatever order that machine returns.
- *
- * Read from a CACHE, never from a live RPC. This is called on the session's one-second tick, and a
- * naive implementation would fire one cloud round trip per machine per second — the dial would spend
- * its whole life waiting on the network to answer a question whose answer changes every few minutes.
- * `refreshRemotes()` does the asking, off to the side, on its own slower clock.
- */
- /**
- * The window's tiles on its active tab, in tile order. This IS the dial's list — see listAgents.
+ * The window's tiles on its active tab, in tile order. This IS the dial's list — see listAgents. A
+ * router this host builds for itself reads it to hold a tile whose machine dropped out; the fleet
+ * service's router reads the window's own report of it.
*/
private desk: string[] = []
-
- /**
- * Every agent this daemon has listed since it started, by id.
- *
- * Kept for ONE purpose: a tile open in the window must always be a tile on the dial. A machine can
- * leave the list for reasons that have nothing to do with its agents — the backend going quiet, the
- * machine going offline while its work stays on screen — and a desk with a hole in it makes a swipe
- * skip a tile and an agent chosen in the window have nowhere to land.
- */
- private knownAgents = new Map<string, CableAgent>()
-
- /** Tiles currently held on the list from that memory, so it is logged once and not every tick. */
- private deskHeld = new Set<string>()
-
/** Last logged shape of the tab's list, so the line prints on change only. */
private deskShape = ''
- /** Size of the last flat list — see agentTotal. */
- private flatCount = 0
-
/**
* The window changed which agents have a tile, or what order they are in.
*
@@ -457,7 +364,7 @@ export class DaemonCableHost implements CableHost {
* - no window (`swarms === null`) → `[]`; the dial shows "Run OpenHarness on your computer".
* - a window with an empty tab → `[]`; the dial shows "Nothing on this tab".
* - a window with panes → those agents, in tile order; a tile whose machine dropped out
- * is held from `knownAgents` (see listAgentsFlat).
+ * is held from the router's `knownAgents` (see listAgentsFlat).
*/
async listAgents(): Promise<CableAgent[]> {
return (await this.listAgentSnapshot()).agents
@@ -482,14 +389,13 @@ export class DaemonCableHost implements CableHost {
this.deskShape = shape
this.wiring.log(`cable: tab ${shape} · ${flat.length} in all`)
}
- return { agents: out, tab, total: this.flatCount }
+ return { agents: out, tab, total: this.router.agentTotal() }
}
/** How many agents the account has across every machine — the overview's number, sent beside the
- * tab's list rather than as 70 rows the dial would hold for a digit. Read from the last flat list,
- * minus the terminals in it: the list is every TILE, this is every AGENT. */
+ * tab's list rather than as 70 rows the dial would hold for a digit. See the router's agentTotal. */
agentTotal(): number {
- return this.flatCount
+ return this.router.agentTotal()
}
/** The active tab's id, or '' with no window. Travels on `agents.end` so the dial can tell an empty
@@ -500,107 +406,34 @@ export class DaemonCableHost implements CableHost {
/**
* Name, engine and machine of an agent this daemon has ever listed — for a `summary` or `question`
- * about one the dial no longer holds. The dial used to look these up in its own copy of the fleet;
- * with that copy gone, the frame has to say who it is about.
+ * about one the dial no longer holds. See the router's describe.
*/
describe(agentId: string): { name: string; engine: string; machine: string } | undefined {
- const a = this.knownAgents.get(agentId) ?? this.localAgents().find((x) => x.id === agentId)
- if (a) return { name: a.name, engine: a.engine ?? '', machine: a.machine ?? '' }
- // A remote agent whose machine has spoken (a question, a card) before its list was ever read: no
- // name to give, but the machine's is better than nothing on a screen asking for a decision.
- const machineId = this.seenOn.get(agentId)
- const machine = machineId ? this.machineNames.get(machineId) ?? '' : ''
- return machineId ? { name: '', engine: '', machine } : undefined
+ return this.router.describe(agentId)
}
async activityText(agentId: string): Promise<string | null> {
- if (!this.isLocalAgent(agentId)) return null
+ if (!this.router.isLocalAgent(agentId)) return null
return await this.wiring.activityText?.(agentId) ?? null
}
- /**
- * A card arrived from a machine for an agent. Remembered so a `question` or `summary` about an agent
- * this daemon has never LISTED — a remote machine's, before its list was read, or one on a tab the
- * window has not opened — can still be described and, when tapped, opened: `machineOf` falls back to
- * this, and without it the open was "ignored for unknown agent" and the tap did nothing.
- */
+ /** A card arrived from a machine for an agent — see the router's noteAgent. */
noteAgent(machineId: string, agentId: string): void {
- if (machineId && agentId) this.seenOn.set(agentId, machineId)
+ this.router.noteAgent(machineId, agentId)
}
- /** agentId → machineId for agents heard from but not (yet) listed — see noteAgent. */
- private readonly seenOn = new Map<string, string>()
- /** machineId → name, from the last wheel read, for describe(). */
- private machineNames = new Map<string, string>()
-
/**
- * EVERY agent in LIST order — this computer first, then each machine in wheel order — the fleet the
- * dial no longer holds.
- *
- * 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.
+ * EVERY agent in LIST order — this computer first, then each machine in wheel order. The router's flat
+ * list, the one ⌘K weighs a typed task against; `listAgents()` is the DIAL's view of the same snapshot,
+ * re-cut around the tiles the window has open.
*/
- async listAgentsFlat(): Promise<CableAgent[]> {
- const out = this.localAgents()
- const { machines } = await this.listMachines()
- this.machineNames = new Map(machines.map((m) => [m.id, m.name]))
- for (const m of machines) {
- if (m.local) continue
- const entry = this.remoteAgents.get(m.id)
- if (entry) for (const a of entry.agents) out.push({ ...a, machineId: m.id, machine: m.name })
- }
- void this.refreshRemotes(machines)
- // Rebuilt from the SAME snapshot that is about to be pushed, so the map can never name a machine an
- // agent has already left. Every action the dial can take is routed through it.
- const next = new Map<string, string>()
- for (const a of out) if (a.machineId) next.set(a.id, a.machineId)
- this.agentMachine = next
-
- const byId = new Map(out.map((a) => [a.id, a]))
-
- for (const a of out) this.knownAgents.set(a.id, a)
- // A tile the window has open, whose agent has left the list. Put it back — under the name and
- // machine it was last seen with, so the dial's tile keeps saying what the window's tile says.
- //
- // Gated on being ON THE DESK, and only that: an agent that was deleted, or one simply never
- // opened, must not be resurrected by this memory. The window holding a tile is the whole warrant.
- const missing = this.desk.filter((id) => !byId.has(id))
- for (const id of missing) {
- const remembered = this.knownAgents.get(id)
- if (!remembered) continue
- // Appended, not slotted back where it was. When a machine drops out none of its agents are left
- // to sit beside, so the end of the list is the only honest place; the tab's list is drawn in TILE
- // order by listAgents, so where it sits here does not matter. Never routed by position either —
- // `agentMachine` below is what sends a turn home.
- out.push(remembered)
- byId.set(id, remembered)
- if (remembered.machineId) this.agentMachine.set(id, remembered.machineId)
- if (!this.deskHeld.has(id)) {
- this.deskHeld.add(id)
- this.wiring.log(`cable: holding ${id.slice(0, 8)} on the tab — the window has a tile for it`)
- }
- }
- for (const id of [...this.deskHeld]) if (!missing.includes(id)) this.deskHeld.delete(id)
-
- // The overview's number is AGENTS, and a shell is not one. The carousel carries shell tiles now —
- // they are panes the window has and the dial can reach — but "12 agents · all idle" is read as how
- // much work is in flight, and counting empty terminals in it would answer a question nobody asked.
- // Two different numbers about the same desk, each honest about what it counts.
- this.flatCount = out.filter((a) => a.engine !== 'terminal').length
- return out
+ listAgentsFlat(): Promise<CableAgent[]> {
+ return this.router.listAgentsFlat()
}
- /**
- * Which machine an agent lives on, or '' if the dial named one this daemon has never listed.
- *
- * NEVER falls back to the selected machine. A wrong answer here does not fail — it delivers the user's
- * turn to a different computer, which is the worst outcome this whole feature can produce.
- */
+ /** Which machine an agent lives on, or '' — never a guess. See the router's machineOf. */
private machineOf(agentId: string): string {
- return this.agentMachine.get(agentId) ?? this.seenOn.get(agentId) ?? ''
+ return this.router.machineOf(agentId)
}
openAgent(agentId: string, reason?: OpenReason): void {
@@ -631,193 +464,52 @@ export class DaemonCableHost implements CableHost {
* then an `open` for the new agent so the window gives it a tile — the fork's whole point on the dial
* is "this one, again, beside it", and the person's hand is on the dial, not the mouse.
*/
- async forkAgent(agentId: string): Promise<{ ok: true; agentId: string } | { ok: false; error: string; detail?: string }> {
- const machineId = this.machineOf(agentId)
- if (!machineId) return { ok: false, error: 'AGENT_NOT_FOUND', detail: 'The dial named an agent this daemon has never listed.' }
- let result: { ok: true; agentId: string } | { ok: false; error: string; detail?: string }
- if (this.isLocalAgent(agentId)) {
- if (!this.wiring.forkAgent) return { ok: false, error: 'UNSUPPORTED', detail: 'This daemon cannot fork agents.' }
- result = await this.wiring.forkAgent(agentId)
- } else {
- if (!this.fleet?.forkAgent) return { ok: false, error: 'UNSUPPORTED_ON_REMOTE' }
- try {
- result = { ok: true, agentId: await this.fleet.forkAgent(machineId, agentId) }
- } catch (err) {
- result = { ok: false, error: 'FORK_FAILED', detail: (err as Error).message }
+ forkAgent(agentId: string): Promise<ForkResult> {
+ // On the agent's own machine, through the router, which notes the new agent there. A fork it
+ // actually asked for is said, and opened in the window.
+ return this.router.forkAgent(agentId, (machineId, result) => {
+ if (result.ok) {
+ this.wiring.log(`cable: fork ${machineId}/${agentId} → ${result.agentId}`)
+ if (this.wiring.forked) this.wiring.forked(machineId, result.agentId, agentId)
+ else this.wiring.opened?.(machineId, result.agentId)
+ } else {
+ this.wiring.log(`cable: fork ${machineId}/${agentId} refused (${result.error}${result.detail ? `: ${result.detail}` : ''})`)
}
- }
- if (result.ok) {
- this.wiring.log(`cable: fork ${machineId}/${agentId} → ${result.agentId}`)
- this.seenOn.set(result.agentId, machineId)
- if (this.wiring.forked) this.wiring.forked(machineId, result.agentId, agentId)
- else this.wiring.opened?.(machineId, result.agentId)
- } else {
- this.wiring.log(`cable: fork ${machineId}/${agentId} refused (${result.error}${result.detail ? `: ${result.detail}` : ''})`)
- }
- return result
+ })
}
/** Whether this daemon's last list held that agent — see CableHost.knows. */
knows(agentId: string): boolean {
- return this.agentMachine.has(agentId)
- }
-
- /** True when the agent belongs to this computer (or is unknown, which is handled at the call site). */
- private isLocalAgent(agentId: string): boolean {
- const machineId = this.machineOf(agentId)
- return !machineId || machineId === this.localId()
+ return this.router.knows(agentId)
}
/**
- * Refresh the other machines' agent lists, on their own clock.
- *
- * Only `ready` machines are asked. An offline one has nothing to say and an unlinked one cannot be
- * read at all (no pinned key), and asking either costs a 15-second RPC timeout per machine per round.
- *
- * A machine that fails keeps its LAST GOOD list for `REMOTE_GRACE_MS` and only then goes empty. A cloud
- * blip is the common case, and dropping every one of a machine's tiles off the carousel for a few
- * seconds — then putting them back — is a far worse lie than briefly showing a list that is a minute
- * old.
- *
- * `unknown` is NOT a reason to drop anything, and reading it as one cost a morning. It means the
- * backend could not be asked — `MachineListCache.degrade()` sets every machine to it in one go when
- * the list cannot be refreshed, on the stated principle that the rows are "stale but not wrong". The
- * agents follow the rows: kept, with no timer, until the backend actually says offline. Measured on
- * the real dial, the old reading emptied a remote machine off the carousel mid-session with no log
- * line, while the window went on showing those agents — which is what made a swipe run out of agents
- * early, and an agent chosen in the window have no tile to move to.
- */
- private refreshRemotes(machines: CableMachine[]): void {
- if (!this.fleet) return
- const now = Date.now()
- for (const m of machines) {
- if (m.local) continue
- const entry = this.remoteAgents.get(m.id)
- if (m.state === 'offline' || m.state === 'needs-link') {
- // The machine ITSELF says it has nothing to offer, which is different from not being able to
- // ask it. No grace period, but never silently: an agent leaving the carousel is exactly the
- // event that is impossible to diagnose after the fact from its absence.
- if (entry && entry.agents.length) {
- this.remoteAgents.set(m.id, { agents: [], at: now, asked: entry.asked })
- this.wiring.log(`cable: ${m.name} is ${m.state} — its ${entry.agents.length} agents left the carousel`)
- }
- continue
- }
- // Not ready and not refused: the backend could not be asked. Keep what it last said.
- if (m.state !== 'ready') continue
- if (entry && now - entry.asked < REMOTE_REFRESH_MS) continue
- if (this.inFlight.has(m.id)) continue
- this.inFlight.add(m.id)
- this.remoteAgents.set(m.id, { agents: entry?.agents ?? [], at: entry?.at ?? 0, asked: now })
- void this.fleet.listAgents(m.id)
- .then((agents) => {
- const before = this.remoteAgents.get(m.id)
- this.remoteAgents.set(m.id, { agents, at: Date.now(), asked: Date.now() })
- // One line per TRANSITION, not per round: this runs every few seconds forever, and a healthy
- // machine that logs each time buries everything else in the file.
- if (!before || before.agents.length !== agents.length) {
- this.wiring.log(`cable: ${m.name} → ${agents.length} agents`)
- }
- })
- .catch((err) => {
- const before = this.remoteAgents.get(m.id)
- const stale = before && Date.now() - before.at > REMOTE_GRACE_MS
- if (stale) this.remoteAgents.set(m.id, { agents: [], at: Date.now(), asked: Date.now() })
- if (before?.agents.length && stale) {
- this.wiring.log(`cable: ${m.name} dropped off the carousel (${(err as Error).message})`)
- }
- })
- .finally(() => this.inFlight.delete(m.id))
- }
- }
-
- /**
- * 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.
+ * Deliver a turn, and SAY whether it could be — through the router, on the agent's own machine, with
+ * the refusal for a machine whose last request did not come back. See the router's sendTurn.
*/
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)
- 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() }
+ return this.router.sendTurn(agentId, text)
}
- /** Who the last delivered turn went to, and how long ago — the router's continuity signal. */
+ /** Who the last delivered turn went to, and how long ago — by any of the router's callers. */
lastRouted(): RouterContinuity | undefined {
- if (!this.lastTurn) return undefined
- return { agentId: this.lastTurn.agentId, agoMs: Date.now() - this.lastTurn.at }
+ return this.router.lastRouted()
}
stopTurn(agentId: string): void {
- if (!this.isLocalAgent(agentId)) { this.fleet!.stopTurn(this.machineOf(agentId), agentId); return }
- this.wiring.stopTurn(agentId)
+ this.router.stopTurn(agentId)
}
canSpeakQuestion(agentId: string): boolean {
- // Remote receiver capabilities are not negotiated yet; no free-text fallback.
- return this.knows(agentId) && this.isLocalAgent(agentId) && !!this.wiring.answerReviewed
+ return this.router.canSpeakQuestion(agentId)
}
- async answerReviewed(answer: ReviewedAnswer): Promise<AnswerReceipt> {
- if (answer.freeTextKeys?.length && !this.canSpeakQuestion(answer.agentId))
- return { ok: false, error: 'Use the terminal to type this answer.' }
- if (!this.isLocalAgent(answer.agentId)) {
- const machineId = this.machineOf(answer.agentId)
- if (!machineId || !this.fleet || this.fleet.reachable?.(machineId)?.ok === false) {
- return { ok: false, error: 'That machine is unavailable. Check its connection.' }
- }
- // Older remote drivers split multi-select labels on commas. Do not lose
- // a selected label when that receiver cannot prove support for exact arrays.
- if (answer.questions.some(q => q.multi && answer.selections[q.key]?.some(label => label.includes(',')))) {
- return { ok: false, error: 'Use the terminal for this multi-select answer.' }
- }
- if (this.fleet.answerReviewed) this.fleet.answerReviewed(machineId, answer)
- else this.fleet.answer(machineId, answer.agentId, answer.requestId, answer.answers)
- return { ok: true, pending: true } // Handoff only; the dialog's close is authoritative.
- }
- if (!this.wiring.answerReviewed) return { ok: false, error: 'Update Harness to answer this question.' }
- const ok = await this.wiring.answerReviewed(answer)
- return ok ? { ok: true } : { ok: false, error: 'Could not confirm the answer. Check the terminal.' }
+ answerReviewed(answer: ReviewedAnswer): Promise<AnswerReceipt> {
+ return this.router.answerReviewed(answer)
}
answer(agentId: string, requestId: string, answers: Record<string, string>): void {
- if (!this.isLocalAgent(agentId)) { this.fleet!.answer(this.machineOf(agentId), agentId, requestId, answers); return }
- this.wiring.answer(agentId, requestId, answers)
+ this.router.answer(agentId, requestId, answers)
}
@@ -876,40 +568,21 @@ export class DaemonCableHost implements CableHost {
}
updateAgent(agentId: string, model?: string, effort?: string): void {
- if (!this.isLocalAgent(agentId)) { this.fleet!.updateAgent(this.machineOf(agentId), agentId, model, effort); return }
- this.wiring.updateAgent?.(agentId, model, effort)
+ this.router.updateAgent(agentId, model, effort)
}
- /** 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; 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: extendShortRecap(r?.recap ?? '', r?.text ?? ''), text: r?.text ?? '', ask: r?.ask ?? '' }))
- .filter((s) => s.recap || s.text || s.ask)
+ /** The last few turns, newest first, in the shape the dial's tile draws — from the agent's own machine. */
+ recentSummaries(agentId: string): Promise<Array<{ recap: string; text: string; ask: string }>> {
+ return this.router.recentSummaries(agentId)
}
- /**
- * The person's own last questions to an agent, newest first — what the router ranks on.
- *
- * Its own trip rather than a field on [recentSummaries]: a question is recorded when it is asked and
- * a recap when the answer is summarised, so the two lists are different lengths on any machine where
- * a turn ended without one. Folding them together is what left the newest question — the one that
- * says where the next one belongs — off the end.
- */
- async recentAsks(agentId: string): Promise<string[]> {
- const raw = this.isLocalAgent(agentId)
- ? this.wiring.recentAsks(agentId)
- : await this.fleet!.recentAsks(this.machineOf(agentId), agentId)
- return raw.map((a) => (a || '').replace(/\s+/g, ' ').trim()).filter(Boolean)
+ /** The person's own last questions to an agent, newest first — what the router ranks on. */
+ recentAsks(agentId: string): Promise<string[]> {
+ return this.router.recentAsks(agentId)
}
- async listModels(agentId: string): Promise<string[]> {
- if (!this.isLocalAgent(agentId)) return this.fleet!.listModels(this.machineOf(agentId), agentId)
-
- const models = (await this.wiring.listModels?.(agentId)) ?? []
- return models.map((m) => m.id).filter(Boolean)
+ listModels(agentId: string): Promise<string[]> {
+ return this.router.listModels(agentId)
}
/**
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index fb06e307a..83a361164 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -40,14 +40,12 @@ import { ensureUtf8Locale } from './lib/childLocale.js'
import { DialLog } from './cable/dialLog.js'
import { buildLogBundle, bundleFileName, redactSecretsInText } from './lib/logBundle.js'
import { CableSession } from './cable/cableSession.js'
-import { CableFleet } from './cable/cableFleet.js'
+import { CableFleet, testDialDiscovery } from './cable/cableFleet.js'
import { DialVerdicts } from './cable/dialPortVerdicts.js'
import { DaemonCableHost, cableEventFor, cableQuestionFor, cableQuestionCloseFor } from './cable/cableHost.js'
import { terminalActivity } from './cable/terminalActivity.js'
import { MachineListCache, machineListCachePath, withStaleMarker } from './device/machineList.js'
-import { DeviceLink } from './device/deviceLink.js'
-import { DeviceFleet } from './device/deviceFleet.js'
import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from './lib/registry.js'
import { engineSessionTitle } from './lib/sessionTitle.js'
import { installCodexHooks } from './lib/hooks.js'
@@ -164,7 +162,7 @@ import { createAgentClosing } from './core/agents/close.js'
import { createEngineHooks, installEngineHooks } from './core/engines/hooks.js'
import { createCursorTaskHooks } from './core/engines/cursorTasks.js'
import { databaseHistory } from './core/transcripts/databaseHistory.js'
-import { createCoreApi, emptyPorts, MODELS_FALLBACKS, SEARCH_FALLBACKS, TEAMS_FALLBACKS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type TeamsPort } from './core/api.js'
+import { createCoreApi, emptyPorts, FLEET_FALLBACKS, MODELS_FALLBACKS, SEARCH_FALLBACKS, TEAMS_FALLBACKS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type TeamsPort } from './core/api.js'
import { createServiceHost, testFaults } from './core/serviceHost.js'
import { createServiceLinks } from './core/serviceLinks.js'
import { createViewersLink } from './core/viewersLink.js'
@@ -180,6 +178,8 @@ import { STORE_REQUESTS, startStore } from './services/store.js'
import { startViewers } from './services/viewers.js'
import { MODELS_REQUESTS, startModels } from './services/models.js'
import { startWorkspaces } from './services/workspaces.js'
+import { startFleet } from './services/fleet.js'
+import type { FleetRouter } from './services/fleetRouter.js'
import { describeMasterStatus, probeMaster, readStatusFile, runMaster } from './harnessd/master.js'
import { CORE_EXIT_STOP, CORE_EXIT_UPDATE } from './harnessd/protocol.js'
import { isLocalSocketName, localSocketPath, refuseServedDataFolder, type LocalSocketServer } from './lib/localSocket.js'
@@ -197,7 +197,7 @@ import { WindowForm } from './cable/windowForm.js'
import { RemoteRelayPool } from './lib/remoteRelay.js'
import { TERMINAL_BINARY_VERSION } from './lib/terminalBinary.js'
import { TeamError } from './teams/model.js'
-import { routeVoiceTask, setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter, type RouterAgent } from './lib/voiceRouter.js'
+import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from './lib/voiceRouter.js'
import { E2eeStore, identitySpent, peekIdentityPub } from './lib/e2ee/store.js'
import { confirmsRemoval, deviceRegistration, deviceStatusValue, formatDeviceDetail, formatDeviceHistory, formatDeviceList, logOrder, removeConfirmation } from './lib/e2ee/deviceDisplay.js'
import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'
@@ -265,6 +265,10 @@ const GENERIC_PAIR_LABELS: ReadonlySet<string> = new Set(['harness link', 'brows
function terminalHintMachineName(): string {
try { return readFileSync(MACHINE_NAME_FILE, 'utf-8').trim() || hostname() } catch { return hostname() }
}
+/** The name the dial's wheel and the fleet give this computer: its display name, else "This machine". */
+function dialMachineName(): string {
+ try { return readFileSync(MACHINE_NAME_FILE, 'utf8').trim() || 'This machine' } catch { return 'This machine' }
+}
// The dial's session, held at module scope for the same reason `backendRef` is: shutdown() is defined
// before the wiring that creates it, and the port has to be released on the way out.
@@ -272,16 +276,6 @@ let cableRef: CableFleet | 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
-/** 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.
*
@@ -301,8 +295,6 @@ let appPaneAgents: string[] = []
* or voice until the window happened to send its tabs again (measured 2026-10-01: 80 s).
*/
let appSwarmsLatest: Parameters<DaemonCableHost['setSwarms']>[0] = null
-/** Module scope for the same reason cableRef is: shutdown() has to release the socket. */
-let deviceLinkRef: DeviceLink | null = null
// OpenCode's SQLite store — polled per session by OpencodeReader (no per-session transcript file).
const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')
@@ -1841,6 +1833,33 @@ async function runForeground(session: AuthSession | null): Promise<void> {
return (await postJson<{ gridName?: string }>('/api/grid/name', {}, headers, AbortSignal.timeout(GRID_MINT_TIMEOUT_MS))).gridName ?? null
},
accessToken: () => new AuthSessionManager(backendHttpBase()).accessToken(),
+ // What a device or another machine asks of an agent here: the SAME handlers the backend socket
+ // drives, called directly — the slash-command adaptation and the turn and question plumbing live there.
+ runtimeProfile: (session) => runtimeProfiles.selectedModel(session),
+ setRuntime: (agentId, model, effort) => {
+ const s = registry.resolve(agentId)
+ if (!s || !model) return
+ backendRef?.onRuntimeProfileUpdate?.(s.sessionId || agentId, `runtime-v1:${s.sessionId || agentId}:${s.engine}:${model}@${effort || 'auto'}`)
+ },
+ // The same path the window's `agent_fork` takes.
+ fork: async (agentId) => {
+ if (!backendRef?.onForkAgent) return { ok: false, error: 'UNSUPPORTED' }
+ const result = await backendRef.onForkAgent({ agentId, name: null, prompt: null })
+ return result.ok ? { ok: true, agentId: result.session.agentId } : { ok: false, error: result.error, detail: result.detail }
+ },
+ turns: {
+ send: (agentId, text) => backendRef?.onMessage?.(agentId, text),
+ stop: (agentId) => backendRef?.onCancel?.(agentId),
+ recent: (agentId, n) => mirror.recent(registry.resolve(agentId)?.sessionId || agentId, n),
+ asks: (agentId) => mirror.recentAsks(registry.resolve(agentId)?.sessionId || agentId),
+ },
+ questions: {
+ // The device's own object, verbatim: rebuilt as `{ [requestId]: optionId }` it was keyed by the
+ // REQUEST id, not the question key `onQuestionAnswer` expects, and named a question that does not exist.
+ answer: (agentId, requestId, answers) => { void backendRef?.onQuestionAnswer?.({ agentId, requestId, answers }) },
+ answerReviewed: async (answer) => (await questions.answer({ agentId: answer.agentId, requestId: answer.requestId,
+ answers: answer.answers, expectedQuestions: answer.questions, selectedLabels: answer.selections, freeTextKeys: answer.freeTextKeys })).ok,
+ },
})
const ports = emptyPorts()
// Each service starts and is called through the host, so one that fails is logged and left off and
@@ -3094,142 +3113,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Ordered, not set-wise: two tiles swapping places is the same set and a different ring.
if (deskChanged) devices('dial', () => { void cableRef?.syncAgents() })
},
- // ⌘K in the window: a typed task, and which agent it belongs to.
- //
- // THE SAME ROUTER THE DIAL USES, given a second caller. routeVoiceTask has never cared that its input
- // arrived as speech — the transcript is just text by the time it sees it — so this is not a port. What
- // 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.
- //
- // 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: backend.ownerCommands.onRouteTask = async (text) => {
- const host = cableHostRef
- if (!host) return { agentId: '', machineId: '', name: '', confidence: 0, reason: 'no agent list yet', candidates: [], weighed: 0, machines: 0, via: '' }
- // 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,
- // THE PERSON'S OWN QUESTIONS, AND NOTHING ELSE.
- //
- // This used to be `turn.ask || turn.recap || turn.text`, cut to sixty characters and joined
- // into one blob — under a prompt heading that told the model every word of it was something
- // the person had asked. For any agent with no recorded question that was false: it was a
- // summary of what the AGENT REPLIED. Measured on this desk, "which year did the second world
- // war end" summarised to "1945." — an answer, labelled as a question, handed to a model asked
- // to recognise a topic. An agent with nothing on record now sends an empty list and is
- // described honestly in the prompt.
- //
- // UNCUT, too. Sixty characters was chosen when fifteen agents each carried three recaps at
- // full length and the prompt timed out; a real machine has four to eight agents, and cutting
- // a Vietnamese sentence at sixty takes the object with it — which is the topic. The bound that
- // matters now lives at the two ends: ASK_MAX_CHARS where the question is recorded, and the
- // endpoint's own per-prompt ceiling.
- prompts: await host.recentAsks(agent.id),
- })))
- // 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.
- // …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)
- // 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
- return {
- agentId: decision.agentId,
- machineId: all.find((entry) => entry.id === decision.agentId)?.machineId ?? '',
- name: named(decision.agentId)?.name ?? '',
- confidence: decision.confidence,
- reason: decision.reason,
- // How many agents were actually WEIGHED, and across how many computers. The window says this
- // while it waits, because the question a person has during those seconds is not "how long" —
- // it is "did it even look at the agent I mean". The cap above can hide agents, and until now
- // the only place that was said was this process's log.
- weighed: ranked.length,
- machines: new Set(ranked.map((agent) => agent.machine).filter(Boolean)).size,
- // 'model' or 'heuristic', coarsened from the router's own label. The two arrive at the same low
- // confidence BY DESIGN — an unsure model and a router that could not run must both stop and ask
- // — and that is exactly why the window has to be able to tell them apart when it explains itself.
- via: (decision.via ?? '').startsWith('heuristic') ? 'heuristic' : 'model',
- candidates: [decision.agentId ? named(decision.agentId) : null, ...others]
- .filter((agent): agent is RouterAgent => !!agent)
- .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 ?? '',
- engine: agent.engine ?? '',
- recent: (agent.recentSummary ?? '').slice(0, 120),
- // Drawn as a bar in the picker, never dispatched on. 0 = the router said nothing about
- // this one, which the window renders as no bar rather than as a zero-length one.
- confidence: fitOf(agent.id),
- }
- }),
- }
- },
- // 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 harness 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.
+ // ⌘K in the window: a typed task, and which agent it belongs to, on any of the owner's machines. The
+ // fleet's to answer (services/fleet.ts routeTask), so it answers with the dial absent or off.
+ onRouteTask: backend.ownerCommands.onRouteTask = async (text) => ports.fleet
+ ? ports.fleet.routeTask(text)
+ : { agentId: '', machineId: '', name: '', confidence: 0, reason: 'no agent list yet', candidates: [], weighed: 0, machines: 0, via: '' },
// A window that connects after the dial did has missed the `dial_status` that announced it.
dialStatus: () => {
let status: ReturnType<DaemonCableHost['currentDialStatus']> | undefined
@@ -3251,8 +3139,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
}),
openQuestions: () => [...openQuestions.values()],
+ // Committed. Sent through the fleet's router — 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 harness 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 uses for every voice turn.
onRouteSend: backend.ownerCommands.onRouteSend = (agentId, text) => {
- const sent = cableHostRef?.sendTurn(agentId, text) ?? { ok: false as const, machine: '', reason: 'no agent list yet' }
+ const sent = ports.fleet?.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
@@ -3922,7 +3818,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Release the serial port first. It is exclusive, and a daemon that exits still holding it makes
// esptool fail in a way that reads exactly like dead hardware.
void cableRef?.stop()
- deviceLinkRef?.stop()
+ ports.fleet?.stop()
daemonBoot.updater?.stop()
daemonBoot.tuiUpdater?.stop()
agentReconciler.stop()
@@ -3982,6 +3878,21 @@ async function runForeground(session: AuthSession | null): Promise<void> {
void shutdown('busy')
}
+ // ── the owner's OTHER machines (services/fleet.ts) ──────────────────────────────────────────────────
+ //
+ // The machine list kept fresh, the lane to the other machines, and the router ⌘K, the window's voice
+ // route and the dial send every turn through. The list is the same cache the local `/api/machines`
+ // handler answers from (built up near `proxyBackend`), so the dial's wheel and the desktop's list
+ // cannot disagree — and neither can go stale while the other is fresh.
+ const fleetService: { router?: FleetRouter } = {}
+ serviceHost.start('fleet', (core, started) => {
+ fleetService.router = startFleet(core, started, {
+ machines: machineListCache, guestMachines: guestMachinesBody, computerId, machineId: () => backend.machineId,
+ machineName: dialMachineName, desk: () => appPaneAgents, auth,
+ autonomousEnv: readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV, identity: relayIdentityStore.getIdentity(),
+ })
+ }, coreApi, FLEET_FALLBACKS)
+
// ── the dial on the USB cable ────────────────────────────────────────────────────────────────────
//
// A second device surface, served entirely over a wire the user physically owns: no backend, no
@@ -3990,54 +3901,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// of any of those is a second set of bugs.
//
// Deliberately not fatal and not blocking: an unplugged cable is this daemon's ordinary state.
- // ── the lane to the owner's OTHER machines ───────────────────────────────────────────────────────
- //
- // Three independent things, on purpose. The LIST is a REST read that works while the backend socket is
- // down; `local` is derived from the computer id and needs no network at all; and the LANE is a device
- // socket that only exists while the dial is actually looking at another machine.
- // The same cache the local `/api/machines` handler answers from (built up near `proxyBackend`), so the
- // dial's wheel and the desktop's list cannot disagree — and neither can go stale while the other is fresh.
- const machineList = machineListCache
- // Signed out there is nothing to fetch and a fetch would only earn a 401 that empties the wheel, so
- // the one row this daemon can speak for is fed in directly — the same body the local handler answers.
- const refreshMachineList = (): void => {
- const guest = guestMachinesBody()
- if (guest) { machineList.adopt(guest); return }
- void machineList.refresh()
- }
- refreshMachineList()
- const machineListTimer = setInterval(refreshMachineList, 60_000)
- machineListTimer.unref?.()
-
- const machinePeers = new MachinePeerStore()
- const deviceLink = new DeviceLink({
- auth,
- backendWsBase: env.BACKEND_WS_URL,
- computerId: computerId(),
- autonomousEnv: readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV,
- // The SAME identity `harness remote-password set` publishes and `harness link connect` proves
- // knowledge against, so one link ceremony covers the desktop app's relay and the dial's lane alike.
- identity: relayIdentityStore.getIdentity(),
- // Read FRESH on every attach: `harness link connect` runs as a separate process, so a value captured
- // at daemon start would keep answering "not linked" until the next restart.
- peer: (machineId) => machinePeers.get(machineId),
- // Read fresh for the same reason `machineId` above is a thunk: it is '' until the daemon has resolved
- // this computer's machine, and the echo guard must start working the moment it is not.
- localMachineId: () => backend.machineId,
- log: (line) => console.log(`[device] ${line}`),
- })
-
- deviceLinkRef = deviceLink
-
- const fleet = new DeviceFleet({
- list: machineList,
- link: deviceLink,
- // Read FRESH on every call, never cached: `harness link connect` runs as a separate process, so a
- // cached answer would keep saying "not linked" for as long as this daemon lives.
- hasPeerLink: (machineId) => machinePeers.get(machineId) !== null,
- log: (line) => console.log(`[device] ${line}`),
- })
-
let devicesStatusRevision = 0
const cableHost = new DaemonCableHost({
activityText: async (agentId) => {
@@ -4046,31 +3909,21 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const screen = await terminals.capture(session, { mode: 'visible', ansi: false })
return terminalActivity(session.engine, screen.state === 'succeeded' ? screen.value : null)
},
- machineName: () => { try { return readFileSync(MACHINE_NAME_FILE, 'utf8').trim() || 'This machine' } catch { return 'This machine' } },
+ machineName: dialMachineName,
machineId: () => backend.machineId,
computerId: () => computerId(),
signedIn: () => readAuthSession() !== null,
- // The SAME handlers the backend socket drives, called directly rather than reimplemented: the
- // slash-command adaptation, the turn bookkeeping and the question plumbing all live in them.
- sendTurn: (agentId, text) => backend.onMessage?.(agentId, text),
- stopTurn: (agentId) => backend.onCancel?.(agentId),
- // The dial's own object, forwarded verbatim. It used to be rebuilt here as `{ [requestId]: optionId }`
- // — keyed by the REQUEST id rather than by the question key `onQuestionAnswer` expects, so the answer
- // named a question that does not exist.
- answer: (agentId, requestId, answers) => { void backend.onQuestionAnswer?.({ agentId, requestId, answers }) },
- answerReviewed: async answer => (await questions.answer({ agentId: answer.agentId, requestId: answer.requestId,
- answers: answer.answers, expectedQuestions: answer.questions, selectedLabels: answer.selections, freeTextKeys: answer.freeTextKeys })).ok,
- recent: (id, n) => mirror.recent(registry.resolve(id)?.sessionId || id, n),
- recentAsks: (id) => mirror.recentAsks(registry.resolve(id)?.sessionId || id),
- runtimeProfile: (session) => runtimeProfiles.selectedModel(session),
- updateAgent: (agentId, model, effort) => {
- const s = registry.resolve(agentId)
- if (!s || !model) return
- backend.onRuntimeProfileUpdate?.(s.sessionId || agentId, `runtime-v1:${s.sessionId || agentId}:${s.engine}:${model}@${effort || 'auto'}`)
- },
- // The same provider the web and the WiFi device read, so the dial's picker cannot show a different
- // catalog from the one the machine will actually honour.
- listModels: runtimeModels,
+ // The core's own doors for a local agent (core/api.ts). The fleet's router reaches them the same way;
+ // the dial uses these only when it routes by itself, with the fleet service off.
+ sendTurn: coreApi.turns.send,
+ stopTurn: coreApi.turns.stop,
+ answer: coreApi.questions.answer,
+ answerReviewed: coreApi.questions.answerReviewed,
+ recent: coreApi.turns.recent,
+ recentAsks: coreApi.turns.asks,
+ runtimeProfile: coreApi.agents.runtimeProfile,
+ updateAgent: coreApi.agents.setRuntime,
+ listModels: coreApi.agents.runtimeModels,
// Both of these are LOCAL-ONLY on purpose (backend.sendLocal, not backend.send): they describe a hand
// at this desk, not a change in what the machine is doing, and the cloud web audience may be sitting
// at another computer entirely.
@@ -4083,11 +3936,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.sendLocal({ type: 'dial_notification_read', payload: { machineId, agentId, readToken } }),
forked: (machineId, agentId, sourceAgentId) => backend.sendLocal({ type: 'dial_forked', payload: { machineId, agentId, sourceAgentId } }),
// The dial's Fork: the same path the window's `agent_fork` takes, then `forked` above lands on it.
- forkAgent: async (agentId) => {
- if (!backend.onForkAgent) return { ok: false, error: 'UNSUPPORTED' }
- const result = await backend.onForkAgent({ agentId, name: null, prompt: null })
- return result.ok ? { ok: true, agentId: result.session.agentId } : { ok: false, error: result.error, detail: result.detail }
- },
+ forkAgent: coreApi.agents.fork,
// No `edge`. It used to ride along for an agent the window had no tile for, naming which end of the
// desk to replace; the carousel now only walks tiles that exist, so every focus is about one of them.
focused: (machineId, agentId) =>
@@ -4111,7 +3960,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
form: command => windowForm.command(command),
clearForm: () => windowForm.clear(),
log: (line) => console.log(`[cable] ${line}`),
- }, fleet)
+ }, fleetService.router)
cableHostRef = cableHost
backend.harnessDevices = {
status: () => cableHost.currentDialStatus(),
@@ -4131,7 +3980,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
const cable = new CableFleet(CableSession, cableHost, env.HARNESS_LOGS_DIR, DialLog,
{ serials: process.env.HARNESS_DIAL_SERIALS?.split(',').map(s => s.trim()).filter(Boolean),
- verdicts: new DialVerdicts(join(env.ADAPTER_DATA_DIR, 'dial-ports.json')) })
+ verdicts: new DialVerdicts(join(env.ADAPTER_DATA_DIR, 'dial-ports.json')), ...testDialDiscovery(process.env.HARNESSD_TEST_DIAL_PORT) })
cableRef = cable
const deviceStore = createDeviceStore({ dataDir: env.ADAPTER_DATA_DIR, machineId: backend.machineId,
@@ -4229,14 +4078,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// A remote machine's cards reach the dial through the SAME four calls the local tee uses, so a new
// event kind lands on both surfaces the day it lands on either.
- fleet.onEvent((event) => {
+ // The fleet has already noted which machine the agent is on (services/fleet.ts), so a question from it
+ // can be named and, tapped, opened.
+ fleetService.router?.fleet?.onEvent((event) => {
// A `state` event is about the WHEEL, not about a turn — live machine presence, which matters
// whichever machine is selected. Filtering it with the guard below would freeze the dots the moment
// the dial came back to this computer, which is where it sits most of the time.
if (event.kind === 'state') { void cable.syncMachines(); return }
- // Which machine this agent is on, before its list is necessarily read — what lets a question from it
- // be named and, tapped, opened. See DaemonCableHost.noteAgent.
- cableHost.noteAgent(event.machineId, event.agentId)
// No selection guard. Every machine's agents are on the carousel at once, so a card from a machine
// the wheel is not pointed at still belongs to a tile the user can see — and dropping it is what a
// tile that never leaves "Working…" looks like from the outside.
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index dff6f774e..4aec5c165 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'
-import { createCoreApi, emptyPorts, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'
+import { createCoreApi, emptyPorts, FLEET_FALLBACKS, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'
const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
@@ -28,6 +28,11 @@ describe('the core API services stand on', () => {
accessToken: vi.fn(async () => 'token'),
privateGridName: vi.fn(async () => 'grid-1'),
machineName: vi.fn(() => 'Studio'),
+ runtimeProfile: vi.fn(() => null),
+ setRuntime: vi.fn(),
+ fork: vi.fn(async () => ({ ok: true as const, agentId: 'fork' })),
+ turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(() => []), asks: vi.fn(() => []) },
+ questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => true) },
}
const core = createCoreApi(deps)
expect(core.dataDir).toBe('/data')
@@ -51,6 +56,17 @@ describe('the core API services stand on', () => {
expect(core.account.accessToken).toBe(deps.accessToken)
expect(core.account.privateGridName).toBe(deps.privateGridName)
expect(core.account.machineName).toBe(deps.machineName)
+ // What a device or another machine asks of an agent here: the core's own handlers, as they are.
+ expect(core.agents.runtimeProfile).toBe(deps.runtimeProfile)
+ expect(core.agents.setRuntime).toBe(deps.setRuntime)
+ expect(core.agents.fork).toBe(deps.fork)
+ expect(core.turns).toBe(deps.turns)
+ expect(core.questions).toBe(deps.questions)
+ })
+
+ it('answers ⌘K, when the fleet fails, with no agent picked and nothing sent, saying why', () => {
+ expect(FLEET_FALLBACKS.sendTurn).toEqual({ ok: false, machine: '', reason: 'the fleet service is unavailable' })
+ expect(FLEET_FALLBACKS.stop).toBeUndefined()
})
it('falls back, when the teams fail, to an undo that has nothing to undo', () => {
@@ -59,7 +75,7 @@ describe('the core API services stand on', () => {
})
it('starts with every port empty: a service fills its own when it starts', () => {
- expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null })
+ expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null })
expect(emptyPorts()).not.toBe(emptyPorts())
})
})
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index a9e9cd9be..ed4793375 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -10,6 +10,8 @@
* The apps reach a service through the requests it answers (`ServiceRequests`), which its start
* returns. The core routes them to it; a port is only for what the core itself must ask.
*/
+import type { RecentTurn } from '../cable/cableHost.js'
+import type { ReviewedAnswer } from '../cable/questionInbox.js'
import type { AgentDshContext } from '../lib/agentFrame.js'
import type { GridAccess } from '../lib/gridAttach.js'
import type { AgentGridTarget } from '../lib/gridModels.js'
@@ -19,9 +21,12 @@ import type { RuntimeModelOption } from '../lib/runtimeProfile.js'
import type { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'
import type { SessionSearchIndex } from '../lib/sessionSearch/indexer.js'
import type { StoppedAgentStore } from '../lib/stoppedAgents.js'
+import type { RouteAnswer } from '../localWsServer.js'
import type { SwarmPromptScopes } from '../teams/promptScope.js'
import { FAIL, later, type PortFallbacks } from './serviceHost.js'
+export type { RouteAnswer }
+
export interface CoreApi {
/** The daemon's data folder; a service keeps its own files in it. */
dataDir: string
@@ -43,6 +48,29 @@ export interface CoreApi {
/** The Model/Effort choices an agent's engine offers (opaque `runtime-v1` ids): one agent's, or
* every live agent's when none is named. */
runtimeModels(agentId?: string): Promise<RuntimeModelOption[]>
+ /** The opaque runtime-v1 profile an agent runs with: its model and effort, for a picker's chips. */
+ runtimeProfile(session: RegisteredSession): string | null
+ /** Switch a live agent's model and effort; nothing without a model. */
+ setRuntime(agentId: string, model?: string, effort?: string): void
+ /** Fork a live agent, as the window's `agent_fork` does: the new agent's id, or the refusal. */
+ fork(agentId: string): Promise<{ ok: true; agentId: string } | { ok: false; error: string; detail?: string }>
+ }
+ /** A device's or another machine's turns for an agent on this one: the doors the web and the hooks use. */
+ turns: {
+ /** Deliver text into a live agent. */
+ send(agentId: string, text: string): void
+ /** Stop a live agent's turn. */
+ stop(agentId: string): void
+ /** A live agent's last `n` completed turns, newest first. */
+ recent(agentId: string, n: number): RecentTurn[]
+ /** The person's own last questions to a live agent, newest first. */
+ asks(agentId: string): string[]
+ }
+ questions: {
+ /** Answer a live agent's question, keyed by the question keys it asked with. */
+ answer(agentId: string, requestId: string, answers: Record<string, string>): void
+ /** Answer it with the selections a device reviewed; resolves whether the terminal confirmed it. */
+ answerReviewed(answer: ReviewedAnswer): Promise<boolean>
}
transcripts: {
/** How to read a conversation its engine keeps in a database instead of a transcript file;
@@ -184,6 +212,25 @@ export type TeamsEvent = { seq: number; core: string; at: number; agentId: strin
| { kind: 'replied'; teamId: string; questionId: string }
)
+/** The core's calls into the fleet: ⌘K's two requests — which agent a typed task belongs to, on any of
+ * the owner's machines, and delivering it to that agent's own machine — and stopping the lane to the
+ * other machines for a shutdown. */
+export interface FleetPort {
+ routeTask(text: string): Promise<RouteAnswer>
+ sendTurn(agentId: string, text: string): { ok: true } | { ok: false; machine: string; reason: string }
+ stop(): void
+}
+
+const FLEET_UNAVAILABLE = 'the fleet service is unavailable'
+
+/** What the core gets when the fleet fails: ⌘K says so, picking no agent and sending nothing, and a
+ * shutdown goes on. */
+export const FLEET_FALLBACKS: PortFallbacks<FleetPort> = {
+ routeTask: later({ agentId: '', machineId: '', name: '', confidence: 0, reason: FLEET_UNAVAILABLE, candidates: [], weighed: 0, machines: 0, via: '' }),
+ sendTurn: { ok: false, machine: '', reason: FLEET_UNAVAILABLE },
+ stop: undefined,
+}
+
/** Each port is filled by the service that owns it when that service starts, and is null while the
* service is off: the core never waits on one. */
export interface CorePorts {
@@ -192,10 +239,11 @@ export interface CorePorts {
models: ModelsPort | null
workspaces: WorkspacesPort | null
teams: TeamsPort | null
+ fleet: FleetPort | null
}
export function emptyPorts(): CorePorts {
- return { search: null, viewers: null, models: null, workspaces: null, teams: null }
+ return { search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null }
}
export interface CoreApiDeps {
@@ -215,11 +263,17 @@ export interface CoreApiDeps {
accessToken: CoreApi['account']['accessToken']
privateGridName: CoreApi['account']['privateGridName']
machineName: CoreApi['account']['machineName']
+ runtimeProfile: CoreApi['agents']['runtimeProfile']
+ setRuntime: CoreApi['agents']['setRuntime']
+ fork: CoreApi['agents']['fork']
+ turns: CoreApi['turns']
+ questions: CoreApi['questions']
}
export function createCoreApi({
dataDir, registry, stoppedAgents, databaseHistory, externalSessions, openSessions, syncSession, runtimeModels, viewerChanged,
gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, privateGridName, machineName,
+ runtimeProfile, setRuntime, fork, turns, questions,
}: CoreApiDeps): CoreApi {
return {
dataDir,
@@ -232,7 +286,12 @@ export function createCoreApi({
terminalAvailable: (agentId) => registry.terminalAvailable(agentId),
sync: syncSession,
runtimeModels,
+ runtimeProfile,
+ setRuntime,
+ fork,
},
+ turns,
+ questions,
transcripts: { databaseHistory },
external: { sessions: externalSessions, open: openSessions },
account: { mintGridName, accessToken, privateGridName, machineName },
diff --git a/cli/src/services/fleet.spec.ts b/cli/src/services/fleet.spec.ts
new file mode 100644
index 000000000..f36ba957b
--- /dev/null
+++ b/cli/src/services/fleet.spec.ts
@@ -0,0 +1,256 @@
+// The fleet service: the machine list kept fresh, the lane to the other machines, the router every
+// turn goes through, and ⌘K's two requests answered from it — with the dial nowhere in sight.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { env } from '../config/env.js'
+import type { DeviceLinkOpts } from '../device/deviceLink.js'
+import type { MachineListCache } from '../device/machineList.js'
+import type { AuthSessionManager } from '../lib/authSession.js'
+import type { Identity } from '../lib/e2ee/core.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import { routeVoiceTask, type RouteDecision, type RouterAgent } from '../lib/voiceRouter.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { emptyPorts, type CorePorts, type FleetPort } from '../core/api.js'
+import { startFleet, type FleetDeps } from './fleet.js'
+
+// The lane is a cloud socket and the pinned keys a file under the data folder: neither in a test.
+const lane = vi.hoisted(() => ({
+ opts: null as DeviceLinkOpts | null,
+ frames: null as ((frame: Record<string, unknown>) => void) | null,
+ stop: vi.fn(),
+ rpc: vi.fn(async (_type: string): Promise<Record<string, unknown>> => ({})),
+ sendSealed: vi.fn(async () => {}),
+ peers: new Map<string, { pub: string }>(),
+}))
+vi.mock('../device/deviceLink.js', () => ({
+ DeviceLink: class {
+ selectedMachine = ''
+ constructor(opts: DeviceLinkOpts) { lane.opts = opts }
+ onFrame(cb: (frame: Record<string, unknown>) => void) { lane.frames = cb; return () => {} }
+ stop() { lane.stop() }
+ rpc(type: string) { return lane.rpc(type) }
+ sendSealed(...args: unknown[]) { return lane.sendSealed(...(args as [])) }
+ resetSession() { return false }
+ },
+}))
+vi.mock('../lib/e2ee/machinePeers.js', () => ({
+ MachinePeerStore: class { get(machineId: string) { return lane.peers.get(machineId) ?? null } },
+}))
+vi.mock('../lib/voiceRouter.js', () => ({ routeVoiceTask: vi.fn() }))
+
+const route = vi.mocked(routeVoiceTask)
+
+const session = (agentId: string, registeredAt = 1, engine = 'claude') =>
+ ({ agentId, registeredAt, engine, sessionId: `s-${agentId}` }) as unknown as RegisteredSession
+
+type Row = { machineId: string; name: string; state: 'ready' | 'offline' | 'unknown' | 'needs-link'; authMode: 'remote'; local: boolean }
+const THIS: Row = { machineId: 'mine', name: 'This one', state: 'ready', authMode: 'remote', local: true }
+const OTHER: Row = { machineId: 'other', name: 'office-imac', state: 'ready', authMode: 'remote', local: false }
+
+function machinesOf(rows: Row[] = [THIS, OTHER]) {
+ return {
+ list: vi.fn(() => ({ machines: rows, source: 'backend' as const })),
+ find: vi.fn((machineId: string) => rows.find((row) => row.machineId === machineId)),
+ adopt: vi.fn(() => true),
+ refresh: vi.fn(async () => {}),
+ applyLive: vi.fn(() => false),
+ }
+}
+
+function setup(over: Partial<FleetDeps> = {}, core = fakeCore()) {
+ const machines = machinesOf()
+ const deps: FleetDeps = {
+ machines: machines as unknown as MachineListCache,
+ guestMachines: vi.fn(() => null),
+ computerId: () => 'computer-1',
+ machineId: () => 'mine',
+ machineName: () => 'MacbookPro.local',
+ desk: () => [],
+ auth: { accessToken: vi.fn() } as unknown as AuthSessionManager,
+ autonomousEnv: 'test-env',
+ identity: { pub: new Uint8Array(32), priv: new Uint8Array(32) } as unknown as Identity,
+ ...over,
+ }
+ const ports: CorePorts = emptyPorts()
+ const router = startFleet(core, ports, deps)
+ return { router, ports, fleet: ports.fleet as FleetPort, deps, machines, core }
+}
+
+const decision = (over: Partial<RouteDecision> = {}): RouteDecision =>
+ ({ agentId: 'a1', confidence: 1, reason: 'only agent in machine', needNewAgent: false, via: 'only-agent', ...over })
+
+let log: ReturnType<typeof vi.spyOn>
+beforeEach(() => {
+ lane.peers = new Map([['other', { pub: 'pinned' }]])
+ log = vi.spyOn(console, 'log').mockImplementation(() => {})
+})
+afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ route.mockReset()
+ lane.stop.mockReset()
+ lane.rpc.mockReset().mockResolvedValue({})
+ lane.sendSealed.mockReset()
+})
+
+describe('the machine list', () => {
+ it('is this computer alone signed out, the backend’s signed in, read again every minute until the fleet stops', () => {
+ vi.useFakeTimers()
+ const guest = { success: true, data: { machines: [] } }
+ let signedOut = true
+ const { fleet, machines } = setup({ guestMachines: () => (signedOut ? guest : null) })
+ expect(machines.adopt).toHaveBeenCalledWith(guest)
+ expect(machines.refresh).not.toHaveBeenCalled()
+ signedOut = false
+ vi.advanceTimersByTime(60_000)
+ expect(machines.refresh).toHaveBeenCalledTimes(1)
+ fleet.stop()
+ expect(lane.stop).toHaveBeenCalled()
+ vi.advanceTimersByTime(120_000)
+ expect(machines.refresh).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('the lane to the other machines', () => {
+ it('signs in and seals as this daemon, reading the pinned keys and this machine’s id fresh', async () => {
+ let machineId = ''
+ const { deps, router } = setup({ machineId: () => machineId })
+ const opts = lane.opts!
+ expect(opts).toMatchObject({ auth: deps.auth, backendWsBase: env.BACKEND_WS_URL, computerId: 'computer-1', autonomousEnv: 'test-env', identity: deps.identity })
+ expect(opts.peer('other')).toEqual({ pub: 'pinned' })
+ expect(opts.peer('third')).toBeNull()
+ lane.peers.set('third', { pub: 'later' })
+ expect(opts.peer('third')).toEqual({ pub: 'later' })
+ expect(opts.localMachineId()).toBe('')
+ // Before this computer has a machine id, its row is named by its computer id.
+ expect(router.localId()).toBe('cable:computer-1')
+ machineId = 'mine'
+ expect(opts.localMachineId()).toBe('mine')
+ opts.log('device: connecting')
+ expect(log).toHaveBeenCalledWith('[device] device: connecting')
+ // A machine with no pinned key is reachable but unreadable, and the wheel says so.
+ lane.peers.delete('other')
+ expect((await router.listMachines()).machines.find((m) => m.id === 'other')?.state).toBe('needs-link')
+ lane.peers.set('other', { pub: 'pinned' })
+ expect((await router.listMachines()).machines.find((m) => m.id === 'other')?.state).toBe('ready')
+ })
+
+ it('notes which machine a card came from, so a question from an agent never listed is named and routed home', () => {
+ const { router } = setup()
+ lane.frames!({ type: 'node_status', machineId: 'other', payload: { online: true } })
+ expect(router.machineOf('other')).toBe('')
+ lane.frames!({ type: 'commander_question', machineId: 'other', agentId: 'r9', payload: { requestId: 'q1', questions: [] } })
+ expect(router.machineOf('r9')).toBe('other')
+ expect(router.describe('r9')).toEqual({ name: '', engine: '', machine: '' })
+ })
+
+ it('reaches another machine’s agents over the lane, and says when it could not', async () => {
+ lane.rpc.mockImplementation(async (type: string) => {
+ if (type === 'agents_list') return { agents: [{ id: 'r1', name: 'api', engine: 'claude' }] }
+ throw new Error('timed out')
+ })
+ const { router, fleet } = setup()
+ await router.listAgentsFlat()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ expect((await router.listAgentsFlat()).map((a) => a.id)).toEqual(['r1'])
+ expect(log).toHaveBeenCalledWith('[cable] cable: office-imac → 1 agents')
+ expect(fleet.sendTurn('r1', 'ship it')).toEqual({ ok: true })
+ expect(lane.sendSealed).toHaveBeenCalledWith(expect.objectContaining({ type: 'message', machineId: 'other' }))
+ expect(await router.recentSummaries('r1')).toEqual([])
+ expect(log).toHaveBeenCalledWith('[device] device: agent_recent r1 failed (timed out)')
+ })
+})
+
+describe('this computer’s side of every route', () => {
+ it('goes through the core’s own doors', async () => {
+ const core = fakeCore({
+ agents: {
+ advertised: vi.fn(() => [session('a1')]),
+ displayName: vi.fn(() => 'api'),
+ runtimeProfile: vi.fn(() => 'runtime-v1:s-a1:claude:opus@high'),
+ fork: vi.fn(async () => ({ ok: true as const, agentId: 'a1-fork' })),
+ runtimeModels: vi.fn(async () => [{ id: 'opus', displayName: 'Opus' }]),
+ },
+ turns: { recent: vi.fn(() => [{ recap: 'Done', text: 'Done' }]), asks: vi.fn(() => ['what next?']) },
+ questions: { answerReviewed: vi.fn(async () => true) },
+ })
+ const { router, fleet } = setup({ desk: () => ['a1'] }, core)
+ expect(await router.listAgentsFlat()).toEqual([
+ { id: 'a1', name: 'api', engine: 'claude', machineId: 'mine', machine: 'MacbookPro.local', model: 'opus', effort: 'high' },
+ ])
+ expect(fleet.sendTurn('a1', 'hello')).toEqual({ ok: true })
+ expect(core.turns.send).toHaveBeenCalledWith('a1', 'hello')
+ router.stopTurn('a1')
+ expect(core.turns.stop).toHaveBeenCalledWith('a1')
+ router.answer('a1', 'q', { scope: 'File' })
+ expect(core.questions.answer).toHaveBeenCalledWith('a1', 'q', { scope: 'File' })
+ const reviewed = { agentId: 'a1', requestId: 'q', questions: [], answers: {}, selections: {} }
+ expect(await router.answerReviewed(reviewed)).toEqual({ ok: true })
+ expect(core.questions.answerReviewed).toHaveBeenCalledWith(reviewed)
+ expect(await router.recentSummaries('a1')).toEqual([{ recap: 'Done', text: 'Done', ask: '' }])
+ expect(core.turns.recent).toHaveBeenCalledWith('a1', 3)
+ expect(await router.recentAsks('a1')).toEqual(['what next?'])
+ router.updateAgent('a1', 'sonnet', 'low')
+ expect(core.agents.setRuntime).toHaveBeenCalledWith('a1', 'sonnet', 'low')
+ expect(await router.listModels('a1')).toEqual(['opus'])
+ expect(await router.forkAgent('a1')).toEqual({ ok: true, agentId: 'a1-fork' })
+ expect(core.agents.fork).toHaveBeenCalledWith('a1')
+ })
+})
+
+describe('⌘K: which agent a typed task belongs to', () => {
+ it('weighs every agent it knows with the person’s own questions, and remembers who they were just talking to', async () => {
+ const core = fakeCore({
+ agents: { advertised: vi.fn(() => [session('a1'), session('a2', 2, 'codex')]), displayName: vi.fn((s: RegisteredSession) => `name-${s.agentId}`) },
+ turns: { asks: vi.fn((agentId: string) => (agentId === 'a1' ? [' fix the\nparser '] : [])) },
+ })
+ const { fleet } = setup({}, core)
+ route.mockResolvedValue(decision({ agentId: 'a2', confidence: 0.8, reason: 'parser work', via: 'claude' }))
+ expect(await fleet.routeTask('fix the lexer')).toEqual({
+ agentId: 'a2', machineId: 'mine', name: 'name-a2', confidence: 0.8, reason: 'parser work', weighed: 2, machines: 1, via: 'model',
+ candidates: [
+ { agentId: 'a2', name: 'name-a2', machineId: 'mine', machine: 'MacbookPro.local', engine: 'codex', recent: '', confidence: 0.8 },
+ { agentId: 'a1', name: 'name-a1', machineId: 'mine', machine: 'MacbookPro.local', engine: 'claude', recent: '', confidence: 0 },
+ ],
+ })
+ const [text, candidates, signal, timeoutMs, continuity] = route.mock.calls[0]!
+ expect(text).toBe('fix the lexer')
+ expect(candidates.map((c: RouterAgent) => [c.id, c.prompts])).toEqual([['a1', ['fix the parser']], ['a2', []]])
+ expect([signal, timeoutMs, continuity]).toEqual([undefined, 20_000, undefined])
+ // A turn ⌘K sent is who the person is talking to, for the next route.
+ fleet.sendTurn('a2', 'and the lexer')
+ await fleet.routeTask('one more')
+ expect(route.mock.calls[1]![4]).toMatchObject({ agentId: 'a2' })
+ })
+
+ it('weighs the first fifteen in rail order and says so; ranks the router’s runners-up first', async () => {
+ const sessions = Array.from({ length: 17 }, (_, i) => session(`a${String(i).padStart(2, '0')}`, i))
+ const { fleet } = setup({}, fakeCore({ agents: { advertised: vi.fn(() => sessions), displayName: vi.fn((s: RegisteredSession) => s.agentId) } }))
+ route.mockResolvedValue(decision({
+ agentId: 'a05', confidence: 0.3, reason: 'names', via: 'heuristic-names',
+ scores: [{ agentId: 'a09', confidence: 0.2 }, { agentId: 'a05', confidence: 0.3 }, { agentId: 'gone', confidence: 0.1 }],
+ }))
+ const answer = await fleet.routeTask('something')
+ expect(log).toHaveBeenCalledWith('[route] 17 agents · weighing the first 15 (open tiles first)')
+ expect(answer.weighed).toBe(15)
+ expect(answer.via).toBe('heuristic')
+ expect(answer.candidates.map((c) => c.agentId).slice(0, 4)).toEqual(['a05', 'a09', 'a00', 'a01'])
+ expect(answer.candidates).toHaveLength(15)
+ expect(answer.candidates.map((c) => c.confidence).slice(0, 3)).toEqual([0.3, 0.2, 0])
+ })
+
+ it('picks nobody when the router does, and still shows what it weighed', async () => {
+ const { fleet, router } = setup()
+ // An agent listed with nothing to say about where it lives or what it runs, and a router that wrote
+ // its own summary onto the candidate it read.
+ vi.spyOn(router, 'listAgentsFlat').mockResolvedValue([{ id: 'x1', name: 'orphan' }])
+ route.mockImplementation(async (_text, agents) => {
+ agents[0]!.recentSummary = 'y'.repeat(200)
+ return { agentId: '', confidence: 0, reason: 'no agents in machine', needNewAgent: true }
+ })
+ expect(await fleet.routeTask('anything')).toEqual({
+ agentId: '', machineId: '', name: '', confidence: 0, reason: 'no agents in machine', weighed: 1, machines: 0, via: 'model',
+ candidates: [{ agentId: 'x1', name: 'orphan', machineId: '', machine: '', engine: '', recent: 'y'.repeat(120), confidence: 0 }],
+ })
+ })
+})
diff --git a/cli/src/services/fleet.ts b/cli/src/services/fleet.ts
new file mode 100644
index 000000000..f72e0ba32
--- /dev/null
+++ b/cli/src/services/fleet.ts
@@ -0,0 +1,272 @@
+/**
+ * The fleet: the owner's other machines, and getting to them (docs/design/2026-10-03-harnessd.md,
+ * "Devices", step D0). The machine list kept fresh, the keys pinned for the machines linked to this
+ * one, the device lane to them (`DeviceLink`, `DeviceFleet`), and the router every turn goes through:
+ * which machine an agent is on, and a turn, a stop or an answer reaching it there (fleetRouter.ts).
+ *
+ * It was built inside the dial's wiring, and the router lived in the dial's host, so ⌘K and the
+ * window's voice route reached another machine only through the dial. They reach the fleet through its
+ * port now (`ports.fleet`), with the dial absent or off; the dial's host holds the same router until
+ * the dial has a boundary of its own (step D1).
+ *
+ * A service on the core boundary: it reads the core only through `CoreApi`, and the core reaches it
+ * only through `ports.fleet`.
+ */
+import { env } from '../config/env.js'
+import type { CoreApi, CorePorts, RouteAnswer } from '../core/api.js'
+import { DeviceFleet } from '../device/deviceFleet.js'
+import { DeviceLink } from '../device/deviceLink.js'
+import type { MachineListCache } from '../device/machineList.js'
+import type { AuthSessionManager } from '../lib/authSession.js'
+import type { Identity } from '../lib/e2ee/core.js'
+import { MachinePeerStore } from '../lib/e2ee/machinePeers.js'
+import { routeVoiceTask, type RouterAgent } from '../lib/voiceRouter.js'
+import { FleetRouter } from './fleetRouter.js'
+
+/**
+ * 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 routeTask.
+ */
+const ROUTE_MAX_CANDIDATES = 15
+/** What ⌘K gives the classifier before the name matcher answers instead. */
+const ROUTE_CLASSIFY_APP_MS = 20_000
+/** How often the machine list is read again: the wheel's dots and the agent lists follow it. */
+const MACHINE_LIST_REFRESH_MS = 60_000
+
+/** What the fleet needs that is not the core's to give. */
+export interface FleetDeps {
+ /**
+ * The owner's machines. Built by the core before this service starts, because the local
+ * `/api/machines` answer and the trust group read it too, and a cache bound late is still empty
+ * exactly when a cold boot during an outage needs it. This service keeps it fresh.
+ */
+ machines: MachineListCache
+ /** The list a signed-out daemon answers with — this computer alone — or null when signed in. */
+ guestMachines(): Record<string, unknown> | null
+ /** This computer's durable id. */
+ computerId(): string
+ /** This computer's machine id, or '' until the daemon has resolved one. */
+ machineId(): string
+ /** The name the dial and the fleet give this computer. */
+ machineName(): string
+ /** The window's tiles on its active tab, in tile order, as it last reported them. */
+ desk(): string[]
+ /**
+ * What the lane signs in and seals with, until it moves with the relay (step D3): the daemon's own
+ * session manager, which shares a refresh in flight with the backend socket; the account's
+ * environment; and this machine's E2EE identity, the one `harness link connect` proves knowledge
+ * against.
+ */
+ auth: AuthSessionManager
+ autonomousEnv: string
+ identity: Identity
+}
+
+/** Start the fleet: its port for ⌘K, and the router, which the dial's host is handed. */
+export function startFleet(core: CoreApi, ports: CorePorts, deps: FleetDeps): FleetRouter {
+ // Three independent things, on purpose. The LIST is a REST read that works while the backend socket is
+ // down; `local` is derived from the computer id and needs no network at all; and the LANE is a device
+ // socket that only exists while the dial is actually looking at another machine.
+ //
+ // Signed out there is nothing to fetch and a fetch would only earn a 401 that empties the wheel, so
+ // the one row this daemon can speak for is fed in directly — the same body the local handler answers.
+ const refreshMachineList = (): void => {
+ const guest = deps.guestMachines()
+ if (guest) { deps.machines.adopt(guest); return }
+ void deps.machines.refresh()
+ }
+ refreshMachineList()
+ const machineListTimer = setInterval(refreshMachineList, MACHINE_LIST_REFRESH_MS)
+ machineListTimer.unref?.()
+
+ const peers = new MachinePeerStore()
+ const link = new DeviceLink({
+ auth: deps.auth,
+ backendWsBase: env.BACKEND_WS_URL,
+ computerId: deps.computerId(),
+ autonomousEnv: deps.autonomousEnv,
+ // The SAME identity `harness remote-password set` publishes and `harness link connect` proves
+ // knowledge against, so one link ceremony covers the desktop app's relay and the dial's lane alike.
+ identity: deps.identity,
+ // Read FRESH on every attach: `harness link connect` runs as a separate process, so a value captured
+ // at daemon start would keep answering "not linked" until the next restart.
+ peer: (machineId) => peers.get(machineId),
+ // Read fresh for the same reason: it is '' until the daemon has resolved this computer's machine, and
+ // the echo guard must start working the moment it is not.
+ localMachineId: () => deps.machineId(),
+ log: (line) => console.log(`[device] ${line}`),
+ })
+ const devices = new DeviceFleet({
+ list: deps.machines,
+ link,
+ // Read FRESH on every call, never cached: `harness link connect` runs as a separate process, so a
+ // cached answer would keep saying "not linked" for as long as this daemon lives.
+ hasPeerLink: (machineId) => peers.get(machineId) !== null,
+ log: (line) => console.log(`[device] ${line}`),
+ })
+ // This computer's side of every route: the core's own doors, the ones the web and the hooks use.
+ const router = new FleetRouter({
+ machineName: () => deps.machineName(),
+ machineId: () => deps.machineId(),
+ computerId: () => deps.computerId(),
+ sessions: () => core.agents.advertised(),
+ displayName: (session) => core.agents.displayName(session),
+ runtimeProfile: (session) => core.agents.runtimeProfile(session),
+ desk: () => deps.desk(),
+ sendTurn: (agentId, text) => core.turns.send(agentId, text),
+ stopTurn: (agentId) => core.turns.stop(agentId),
+ answer: (agentId, requestId, answers) => core.questions.answer(agentId, requestId, answers),
+ answerReviewed: (answer) => core.questions.answerReviewed(answer),
+ recent: (agentId, n) => core.turns.recent(agentId, n),
+ recentAsks: (agentId) => core.turns.asks(agentId),
+ updateAgent: (agentId, model, effort) => core.agents.setRuntime(agentId, model, effort),
+ listModels: (agentId) => core.agents.runtimeModels(agentId),
+ forkAgent: (agentId) => core.agents.fork(agentId),
+ // The lines the dial's host always wrote, under the name people search the log for.
+ log: (line) => console.log(`[cable] ${line}`),
+ }, devices)
+ // Which machine an agent is on, before its list is necessarily read: what lets a question from it be
+ // named and, tapped, opened — whichever surface is listening, the dial or none.
+ devices.onEvent((event) => { if (event.kind !== 'state') router.noteAgent(event.machineId, event.agentId) })
+ ports.fleet = {
+ routeTask: (text) => routeTask(router, text),
+ sendTurn: (agentId, text) => router.sendTurn(agentId, text),
+ stop: () => {
+ clearInterval(machineListTimer)
+ link.stop()
+ },
+ }
+ return router
+}
+
+/**
+ * ⌘K in the window: a typed task, and which agent it belongs to.
+ *
+ * THE SAME ROUTER THE DIAL USES, given a second caller. routeVoiceTask has never cared that its input
+ * arrived as speech — the transcript is just text by the time it sees it — so this is not a port. What
+ * 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.
+ *
+ * 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).
+ */
+async function routeTask(router: FleetRouter, text: string): Promise<RouteAnswer> {
+ // 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 router.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,
+ // THE PERSON'S OWN QUESTIONS, AND NOTHING ELSE.
+ //
+ // This used to be `turn.ask || turn.recap || turn.text`, cut to sixty characters and joined
+ // into one blob — under a prompt heading that told the model every word of it was something
+ // the person had asked. For any agent with no recorded question that was false: it was a
+ // summary of what the AGENT REPLIED. Measured on this desk, "which year did the second world
+ // war end" summarised to "1945." — an answer, labelled as a question, handed to a model asked
+ // to recognise a topic. An agent with nothing on record now sends an empty list and is
+ // described honestly in the prompt.
+ //
+ // UNCUT, too. Sixty characters was chosen when fifteen agents each carried three recaps at
+ // full length and the prompt timed out; a real machine has four to eight agents, and cutting
+ // a Vietnamese sentence at sixty takes the object with it — which is the topic. The bound that
+ // matters now lives at the two ends: ASK_MAX_CHARS where the question is recorded, and the
+ // endpoint's own per-prompt ceiling.
+ prompts: await router.recentAsks(agent.id),
+ })))
+ // 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.
+ // …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, router.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)
+ // 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
+ return {
+ agentId: decision.agentId,
+ machineId: all.find((entry) => entry.id === decision.agentId)?.machineId ?? '',
+ name: named(decision.agentId)?.name ?? '',
+ confidence: decision.confidence,
+ reason: decision.reason,
+ // How many agents were actually WEIGHED, and across how many computers. The window says this
+ // while it waits, because the question a person has during those seconds is not "how long" —
+ // it is "did it even look at the agent I mean". The cap above can hide agents, and until now
+ // the only place that was said was this process's log.
+ weighed: ranked.length,
+ machines: new Set(ranked.map((agent) => agent.machine).filter(Boolean)).size,
+ // 'model' or 'heuristic', coarsened from the router's own label. The two arrive at the same low
+ // confidence BY DESIGN — an unsure model and a router that could not run must both stop and ask
+ // — and that is exactly why the window has to be able to tell them apart when it explains itself.
+ via: (decision.via ?? '').startsWith('heuristic') ? 'heuristic' : 'model',
+ candidates: [decision.agentId ? named(decision.agentId) : null, ...others]
+ .filter((agent): agent is RouterAgent => !!agent)
+ .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 ?? '',
+ engine: agent.engine ?? '',
+ recent: (agent.recentSummary ?? '').slice(0, 120),
+ // Drawn as a bar in the picker, never dispatched on. 0 = the router said nothing about
+ // this one, which the window renders as no bar rather than as a zero-length one.
+ confidence: fitOf(agent.id),
+ }
+ }),
+ }
+}
diff --git a/cli/src/services/fleetRouter.spec.ts b/cli/src/services/fleetRouter.spec.ts
new file mode 100644
index 000000000..cb7cca9a7
--- /dev/null
+++ b/cli/src/services/fleetRouter.spec.ts
@@ -0,0 +1,430 @@
+// The router across the owner's machines: which machine an agent is on, and a turn, a stop or an
+// answer reaching it there. Every caller (⌘K, the voice route, the dial) goes through one of these.
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import type { FleetMachine, MachineFleet } from '../cable/machineFleet.js'
+import type { ReviewedAnswer } from '../cable/questionInbox.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import { FleetRouter, type FleetLocal } from './fleetRouter.js'
+
+const session = (agentId: string, registeredAt: number, engine?: string) =>
+ ({ agentId, registeredAt, engine, sessionId: `s-${agentId}` }) as unknown as RegisteredSession
+
+function localOf(over: Partial<FleetLocal> = {}, sessions: RegisteredSession[] = []): FleetLocal {
+ return {
+ machineName: () => 'MacbookPro.local',
+ machineId: () => 'mine',
+ computerId: () => 'abc-123',
+ sessions: () => [...sessions],
+ displayName: (s) => `name-${s.agentId}`,
+ desk: () => [],
+ sendTurn: vi.fn(),
+ stopTurn: vi.fn(),
+ answer: vi.fn(),
+ recent: vi.fn(() => []),
+ recentAsks: vi.fn(() => []),
+ log: vi.fn(),
+ ...over,
+ }
+}
+
+const REMOTE: FleetMachine = { machineId: 'other', name: 'office-imac', state: 'ready', authMode: 'remote' }
+
+/** A fleet whose machines and agent lists are scripted. */
+function fleetOf(machines: FleetMachine[], byMachine: Record<string, Array<{ id: string; name: string; engine?: string }>> = {}): MachineFleet {
+ return {
+ list: async () => ({ machines, source: 'backend' as const }),
+ online: async () => {},
+ select: async () => {},
+ release: vi.fn(),
+ listAgents: vi.fn(async (machineId: string) => (byMachine[machineId] ?? []) as never),
+ sendTurn: vi.fn(), stopTurn: vi.fn(), answer: vi.fn(), updateAgent: vi.fn(),
+ listModels: vi.fn(async () => ['m1']),
+ recentSummaries: vi.fn(async () => []),
+ recentAsks: vi.fn(async () => []),
+ onEvent: () => () => {},
+ }
+}
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
+
+/** Two reads: the first starts the background refresh, the second reads what it wrote. */
+async function settled(router: FleetRouter) {
+ await router.listAgentsFlat()
+ await flush()
+ return router.listAgentsFlat()
+}
+
+afterEach(() => { vi.restoreAllMocks() })
+
+describe('this computer', () => {
+ it('is named by its machine id, or by a placeholder that is not machine-id shaped', () => {
+ expect(new FleetRouter(localOf()).localId()).toBe('mine')
+ expect(new FleetRouter(localOf({ machineId: () => '' })).localId()).toBe('cable:abc-123')
+ })
+
+ it('is the only row with no fleet, and the first row with one — never twice', async () => {
+ expect(await new FleetRouter(localOf()).listMachines()).toEqual({
+ machines: [{ id: 'mine', name: 'MacbookPro.local', state: 'ready', local: true }], source: 'signed-out',
+ })
+ const dupe: FleetMachine = { machineId: 'mine', name: 'renamed', state: 'offline', authMode: 'remote' }
+ const { machines, source } = await new FleetRouter(localOf(), fleetOf([dupe, REMOTE])).listMachines()
+ expect(source).toBe('backend')
+ expect(machines).toEqual([
+ { id: 'mine', name: 'MacbookPro.local', state: 'ready', local: true },
+ { id: 'other', name: 'office-imac', state: 'ready', local: false },
+ ])
+ })
+
+ it('lists its agents oldest first, ties by id, with the chips their runtime profile names', async () => {
+ const profiles: Record<string, string | null> = {
+ b: 'runtime-v1:s-b:claude:opus@high', a: 'runtime-v1:s-a:claude:sonnet', c: 'runtime-v1:s-c:claude:@low',
+ d: 'runtime-v1:s-d:claude', e: 'something-else', f: null,
+ }
+ const router = new FleetRouter(localOf({ runtimeProfile: (s) => profiles[s.agentId] ?? null },
+ [session('f', 3, 'terminal'), session('b', 1, 'claude'), session('a', 1, 'claude'), session('c', 2), session('d', 2), session('e', 2)]))
+ const agents = await router.listAgentsFlat()
+ expect(agents.map((a) => a.id)).toEqual(['a', 'b', 'c', 'd', 'e', 'f'])
+ expect(agents[0]).toEqual({ id: 'a', name: 'name-a', engine: 'claude', machineId: 'mine', machine: 'MacbookPro.local', model: 'sonnet', effort: undefined })
+ expect(agents[1]).toMatchObject({ model: 'opus', effort: 'high' })
+ expect(agents[2]).toMatchObject({ engine: '', model: undefined, effort: 'low' })
+ for (const plain of agents.slice(3)) expect(plain).not.toHaveProperty('model')
+ // A shell is a tile, not an agent: the overview's number leaves it out.
+ expect(router.agentTotal()).toBe(5)
+ // No profile reader at all: no chips.
+ const bare = new FleetRouter(localOf({}, [session('a', 1, 'claude')]))
+ expect((await bare.listAgentsFlat())[0]).not.toHaveProperty('model')
+ })
+})
+
+describe('which machine an agent is on', () => {
+ it('reads each other machine’s list off to the side, and puts this computer first', async () => {
+ const third: FleetMachine = { machineId: 'third', name: 'studio', state: 'ready', authMode: 'remote' }
+ const fleet = fleetOf([REMOTE, third], { other: [{ id: 'r1', name: 'api' }], third: [{ id: 'r2', name: 'ui', engine: 'codex' }] })
+ const log = vi.fn()
+ const router = new FleetRouter(localOf({ log }, [session('local-1', 1, 'claude')]), fleet)
+ const agents = await settled(router)
+ expect(agents.map((a) => [a.id, a.machineId, a.machine])).toEqual([
+ ['local-1', 'mine', 'MacbookPro.local'], ['r1', 'other', 'office-imac'], ['r2', 'third', 'studio'],
+ ])
+ expect(router.machineOf('r2')).toBe('third')
+ expect(router.machineOf('local-1')).toBe('mine')
+ expect(router.machineOf('ghost')).toBe('')
+ expect(router.knows('r1')).toBe(true)
+ expect(router.knows('ghost')).toBe(false)
+ expect(router.isLocalAgent('local-1')).toBe(true)
+ expect(router.isLocalAgent('ghost')).toBe(true)
+ expect(router.isLocalAgent('r1')).toBe(false)
+ expect(log).toHaveBeenCalledWith('cable: office-imac → 1 agents')
+ // Asked once a round, not on every read: the list changes when a person starts an agent.
+ await router.listAgentsFlat()
+ expect(fleet.listAgents).toHaveBeenCalledTimes(2)
+ })
+
+ it('asks a slow machine once, and logs only when a machine’s count changes', async () => {
+ let answer: (agents: never) => void = () => {}
+ const fleet = fleetOf([REMOTE])
+ fleet.listAgents = vi.fn(() => new Promise<never>((resolve) => { answer = resolve }))
+ const log = vi.fn()
+ const router = new FleetRouter(localOf({ log }), fleet)
+ await router.listAgentsFlat()
+ const now = Date.now()
+ vi.spyOn(Date, 'now').mockReturnValue(now + 6_000)
+ await router.listAgentsFlat() // past the cadence, but its first answer is still out
+ expect(fleet.listAgents).toHaveBeenCalledTimes(1)
+ answer([{ id: 'r1', name: 'api' }] as never)
+ await flush()
+ expect(log).toHaveBeenCalledWith('cable: office-imac → 1 agents')
+ log.mockClear()
+ vi.spyOn(Date, 'now').mockReturnValue(now + 12_000)
+ await router.listAgentsFlat()
+ answer([{ id: 'r1', name: 'api' }] as never)
+ await flush()
+ expect(fleet.listAgents).toHaveBeenCalledTimes(2)
+ expect(log).not.toHaveBeenCalled()
+ })
+
+ it('keeps a machine’s last good list through a failure, and only past the grace drops it, saying so', async () => {
+ const fleet = fleetOf([REMOTE], { other: [{ id: 'r1', name: 'api' }] })
+ const log = vi.fn()
+ const router = new FleetRouter(localOf({ log }), fleet)
+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])
+ ;(fleet.listAgents as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('cloud blip'))
+ const now = Date.now()
+ vi.spyOn(Date, 'now').mockReturnValue(now + 6_000)
+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])
+ vi.spyOn(Date, 'now').mockReturnValue(now + 60_000)
+ await settled(router)
+ expect(log).toHaveBeenCalledWith('cable: office-imac dropped off the carousel (cloud blip)')
+ expect(await router.listAgentsFlat()).toEqual([])
+ // Already empty: a later failure past the grace has nothing to drop and says nothing.
+ log.mockClear()
+ vi.spyOn(Date, 'now').mockReturnValue(now + 120_000)
+ await settled(router)
+ expect(log).not.toHaveBeenCalled()
+ })
+
+ it('keeps a machine’s agents while the backend cannot be asked, and drops them when the machine says offline', async () => {
+ const machines: FleetMachine[] = [{ ...REMOTE }]
+ const fleet = fleetOf(machines, { other: [{ id: 'r1', name: 'api' }] })
+ const log = vi.fn()
+ const router = new FleetRouter(localOf({ log }), fleet)
+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])
+ machines[0].state = 'unknown'
+ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 10 * 60_000)
+ expect((await settled(router)).map((a) => a.id)).toEqual(['r1'])
+ machines[0].state = 'offline'
+ expect((await settled(router)).map((a) => a.id)).toEqual([])
+ expect(log).toHaveBeenCalledWith('cable: office-imac is offline — its 1 agents left the carousel')
+ // Already empty: nothing more to say.
+ log.mockClear()
+ await settled(router)
+ expect(log).not.toHaveBeenCalled()
+ })
+
+ it('asks nothing of a machine that is not linked', async () => {
+ const fleet = fleetOf([{ ...REMOTE, state: 'needs-link' }], { other: [{ id: 'r1', name: 'api' }] })
+ const router = new FleetRouter(localOf(), fleet)
+ expect(await settled(router)).toEqual([])
+ expect(fleet.listAgents).not.toHaveBeenCalled()
+ })
+
+ it('holds a tile the window has open after its machine drops out, once, and never resurrects one without a tile', async () => {
+ const machines: FleetMachine[] = [{ ...REMOTE }]
+ const desk: string[] = []
+ const log = vi.fn()
+ const router = new FleetRouter(localOf({ log, desk: () => desk }), fleetOf(machines, { other: [{ id: 'r1', name: 'api' }, { id: 'r2', name: 'web' }] }))
+ await settled(router)
+ desk.push('r1', 'never-listed')
+ machines[0].state = 'offline'
+ const agents = await settled(router)
+ expect(agents.map((a) => a.id)).toEqual(['r1'])
+ expect(agents[0]).toMatchObject({ name: 'api', machineId: 'other', machine: 'office-imac' })
+ expect(router.knows('r1')).toBe(true)
+ expect(router.knows('r2')).toBe(false)
+ // Still held on the next read, and said only the once.
+ expect((await router.listAgentsFlat()).map((a) => a.id)).toEqual(['r1'])
+ expect(log.mock.calls.filter(([line]) => String(line).startsWith('cable: holding'))).toEqual([['cable: holding r1 on the tab — the window has a tile for it']])
+ // The tile closes: no longer held, and a later hold says so again.
+ desk.splice(0)
+ expect(await router.listAgentsFlat()).toEqual([])
+ desk.push('r1')
+ await router.listAgentsFlat()
+ expect(log.mock.calls.filter(([line]) => String(line).startsWith('cable: holding'))).toHaveLength(2)
+ })
+
+ it('routes nothing for an agent listed without a machine, even when the window holds its tile', async () => {
+ const nameless: FleetMachine = { machineId: '', name: 'ghost-row', state: 'ready', authMode: 'remote' }
+ const machines = [nameless]
+ const desk: string[] = []
+ const router = new FleetRouter(localOf({ desk: () => desk }), fleetOf(machines, { '': [{ id: 'x1', name: 'orphan' }] }))
+ expect((await settled(router)).map((a) => a.id)).toEqual(['x1'])
+ expect(router.knows('x1')).toBe(false)
+ desk.push('x1')
+ nameless.state = 'offline'
+ expect((await settled(router)).map((a) => a.id)).toEqual(['x1'])
+ expect(router.knows('x1')).toBe(false)
+ })
+
+ it('describes an agent it has listed, one it has only heard from, and nothing it has never met', async () => {
+ const unnamed = { ...REMOTE, name: undefined as unknown as string }
+ const router = new FleetRouter(localOf({}, [session('a1', 1, 'codex')]), fleetOf([unnamed], { other: [{ id: 'r1', name: 'api' }] }))
+ // Before any list: a local agent is still this computer's.
+ expect(router.describe('a1')).toEqual({ name: 'name-a1', engine: 'codex', machine: 'MacbookPro.local' })
+ await settled(router)
+ expect(router.describe('r1')).toEqual({ name: 'api', engine: '', machine: '' })
+ expect(router.describe('ghost')).toBeUndefined()
+ router.noteAgent('other', 'r9')
+ router.noteAgent('', 'r8')
+ router.noteAgent('other', '')
+ router.noteAgent('elsewhere', 'r7')
+ expect(router.describe('r9')).toEqual({ name: '', engine: '', machine: '' })
+ expect(router.describe('r8')).toBeUndefined()
+ expect(router.describe('r7')).toEqual({ name: '', engine: '', machine: '' })
+ expect(router.machineOf('r9')).toBe('other')
+ const named = new FleetRouter(localOf(), fleetOf([REMOTE]))
+ await named.listAgentsFlat()
+ named.noteAgent('other', 'r9')
+ expect(named.describe('r9')).toEqual({ name: '', engine: '', machine: 'office-imac' })
+ })
+})
+
+describe('a turn, delivered and said so', () => {
+ it('goes to the agent’s own machine, and is remembered as who the person is talking to', async () => {
+ const fleet = fleetOf([REMOTE], { other: [{ id: 'r1', name: 'api' }] })
+ const local = localOf({}, [session('local-1', 1, 'claude')])
+ const router = new FleetRouter(local, fleet)
+ await settled(router)
+ expect(router.lastRouted()).toBeUndefined()
+ expect(router.sendTurn('r1', 'ship it')).toEqual({ ok: true })
+ expect(fleet.sendTurn).toHaveBeenCalledWith('other', 'r1', 'ship it')
+ expect(router.lastRouted()).toMatchObject({ agentId: 'r1' })
+ expect(router.sendTurn('local-1', 'hello')).toEqual({ ok: true })
+ expect(local.sendTurn).toHaveBeenCalledWith('local-1', 'hello')
+ expect(router.lastRouted()?.agentId).toBe('local-1')
+ // Never guessed onto another machine: an id never listed goes to this computer's door.
+ router.sendTurn('ghost', 'where does this go?')
+ expect(local.sendTurn).toHaveBeenLastCalledWith('ghost', 'where does this go?')
+ expect(fleet.sendTurn).toHaveBeenCalledTimes(1)
+ // An empty id is delivered, but is not a conversation.
+ router.sendTurn('', 'nobody')
+ expect(router.lastRouted()?.agentId).toBe('ghost')
+ })
+
+ it('is refused for a machine whose last request did not come back, and never for one never asked', async () => {
+ const fleet = fleetOf([REMOTE], { other: [{ id: 'r1', name: 'api' }] })
+ const log = vi.fn()
+ const router = new FleetRouter(localOf({ log }), fleet)
+ await settled(router)
+ fleet.reachable = () => null
+ expect(router.sendTurn('r1', 'cold start')).toEqual({ ok: true })
+ fleet.reachable = () => ({ ok: true, at: Date.now() })
+ expect(router.sendTurn('r1', 'fine')).toEqual({ ok: true })
+ fleet.reachable = () => ({ ok: false, at: Date.now() - 4_000 })
+ expect(router.sendTurn('r1', 'deaf')).toEqual({ ok: false, machine: 'office-imac', reason: 'the last request to it did not come back' })
+ expect(log).toHaveBeenCalledWith('cable: refused a turn for r1 — office-imac last failed 4s ago')
+ expect(router.lastRouted()?.agentId).toBe('r1')
+ expect(fleet.sendTurn).toHaveBeenCalledTimes(2)
+ // Heard from but never listed: the refusal names the machine by its id.
+ router.noteAgent('abcdef0123456789', 'r9')
+ expect(router.sendTurn('r9', 'deaf too')).toMatchObject({ ok: false, machine: 'abcdef01' })
+ })
+
+ it('stops, answers and switches models on the agent’s own machine', async () => {
+ const fleet = fleetOf([REMOTE], { other: [{ id: 'r1', name: 'api' }] })
+ const updateAgent = vi.fn()
+ const local = localOf({ updateAgent }, [session('a1', 1, 'claude')])
+ const router = new FleetRouter(local, fleet)
+ await settled(router)
+ router.stopTurn('r1'); router.stopTurn('a1')
+ expect(fleet.stopTurn).toHaveBeenCalledWith('other', 'r1')
+ expect(local.stopTurn).toHaveBeenCalledWith('a1')
+ router.answer('r1', 'q', { k: 'v' }); router.answer('a1', 'q', { k: 'v' })
+ expect(fleet.answer).toHaveBeenCalledWith('other', 'r1', 'q', { k: 'v' })
+ expect(local.answer).toHaveBeenCalledWith('a1', 'q', { k: 'v' })
+ router.updateAgent('r1', 'opus', 'high'); router.updateAgent('a1', 'sonnet')
+ expect(fleet.updateAgent).toHaveBeenCalledWith('other', 'r1', 'opus', 'high')
+ expect(updateAgent).toHaveBeenCalledWith('a1', 'sonnet', undefined)
+ // A daemon with no model switch: nothing happens.
+ new FleetRouter(localOf()).updateAgent('a1', 'opus')
+ })
+
+ it('reads recaps, questions and models from the agent’s own machine, tidied', async () => {
+ const fleet = fleetOf([REMOTE], { other: [{ id: 'r1', name: 'api' }] })
+ fleet.recentSummaries = vi.fn(async () => [{ recap: 'Done.', text: 'Shipped the fix.', ask: 'ship it' }])
+ fleet.recentAsks = vi.fn(async () => [' ship\n it ', ''])
+ const local = localOf({
+ recent: vi.fn(() => [null, {}, { recap: 'Local recap', text: 'body' }, { ask: 'only a question' }] as never),
+ recentAsks: vi.fn(() => ['what next?', null] as never),
+ listModels: vi.fn(async () => [{ id: 'opus' }, { id: '' }]),
+ }, [session('a1', 1, 'claude')])
+ const router = new FleetRouter(local, fleet)
+ await settled(router)
+ expect(await router.recentSummaries('r1')).toEqual([{ recap: expect.any(String), text: 'Shipped the fix.', ask: 'ship it' }])
+ expect(fleet.recentSummaries).toHaveBeenCalledWith('other', 'r1')
+ expect(await router.recentSummaries('a1')).toEqual([
+ { recap: expect.any(String), text: 'body', ask: '' }, { recap: '', text: '', ask: 'only a question' },
+ ])
+ expect(local.recent).toHaveBeenCalledWith('a1', 3)
+ expect(await router.recentAsks('r1')).toEqual(['ship it'])
+ expect(await router.recentAsks('a1')).toEqual(['what next?'])
+ expect(await router.listModels('r1')).toEqual(['m1'])
+ expect(await router.listModels('a1')).toEqual(['opus'])
+ expect(await new FleetRouter(localOf()).listModels('a1')).toEqual([])
+ })
+})
+
+describe('a fork, on the agent’s own machine', () => {
+ it('forks a local agent through the daemon, notes the fork here, and says how the attempt went', async () => {
+ const forkAgent = vi.fn(async () => ({ ok: true as const, agentId: 'a1-fork' }))
+ const router = new FleetRouter(localOf({ forkAgent }, [session('a1', 1, 'claude')]))
+ await router.listAgentsFlat()
+ const attempted = vi.fn()
+ expect(await router.forkAgent('a1', attempted)).toEqual({ ok: true, agentId: 'a1-fork' })
+ expect(attempted).toHaveBeenCalledWith('mine', { ok: true, agentId: 'a1-fork' })
+ expect(router.machineOf('a1-fork')).toBe('mine')
+ forkAgent.mockResolvedValueOnce({ ok: false, error: 'BUSY' } as never)
+ expect(await router.forkAgent('a1')).toEqual({ ok: false, error: 'BUSY' })
+ })
+
+ it('refuses without asking anyone for an agent never listed, or a daemon that cannot fork', async () => {
+ const attempted = vi.fn()
+ const router = new FleetRouter(localOf({}, [session('a1', 1, 'claude')]))
+ await router.listAgentsFlat()
+ expect(await router.forkAgent('ghost', attempted)).toMatchObject({ ok: false, error: 'AGENT_NOT_FOUND' })
+ expect(await router.forkAgent('a1', attempted)).toMatchObject({ ok: false, error: 'UNSUPPORTED' })
+ // A remote agent heard from, with no fleet to fork it through.
+ router.noteAgent('other', 'r1')
+ expect(await router.forkAgent('r1', attempted)).toEqual({ ok: false, error: 'UNSUPPORTED_ON_REMOTE' })
+ expect(attempted).not.toHaveBeenCalled()
+ })
+
+ it('forks a remote agent on its machine, and reports the far end’s refusal', async () => {
+ const fleet = fleetOf([REMOTE], { other: [{ id: 'r1', name: 'api' }, { id: 'r2', name: 'busy' }] })
+ fleet.forkAgent = vi.fn(async (_m: string, id: string) => { if (id === 'r1') return 'r1-fork'; throw new Error('r2 is in the middle of a turn') })
+ const router = new FleetRouter(localOf(), fleet)
+ await settled(router)
+ expect(await router.forkAgent('r1')).toEqual({ ok: true, agentId: 'r1-fork' })
+ expect(router.machineOf('r1-fork')).toBe('other')
+ expect(await router.forkAgent('r2')).toEqual({ ok: false, error: 'FORK_FAILED', detail: 'r2 is in the middle of a turn' })
+ })
+})
+
+describe('an answer reviewed on a device', () => {
+ const answer: ReviewedAnswer = {
+ agentId: 'a1', requestId: 'question-1',
+ questions: [{ key: 'scope', q: 'Which scope?', options: ['File', 'Project'], multi: false }],
+ answers: { scope: 'File' }, selections: { scope: ['File'] },
+ }
+
+ it('is confirmed by the local terminal, or says it could not be', async () => {
+ const answerReviewed = vi.fn(async () => true)
+ const router = new FleetRouter(localOf({ answerReviewed }, [session('a1', 1, 'claude')]))
+ expect(await router.answerReviewed(answer)).toEqual({ ok: true })
+ answerReviewed.mockResolvedValue(false)
+ expect(await router.answerReviewed(answer)).toEqual({ ok: false, error: 'Could not confirm the answer. Check the terminal.' })
+ expect(await new FleetRouter(localOf()).answerReviewed(answer)).toEqual({ ok: false, error: 'Update Harness to answer this question.' })
+ })
+
+ it('takes spoken free text only for a known local agent that can confirm it', async () => {
+ const answerReviewed = vi.fn(async () => true)
+ const fleet = fleetOf([REMOTE], { other: [{ id: 'r1', name: 'api' }] })
+ const router = new FleetRouter(localOf({ answerReviewed }, [session('a1', 1, 'claude')]), fleet)
+ await settled(router)
+ expect(router.canSpeakQuestion('a1')).toBe(true)
+ expect(router.canSpeakQuestion('r1')).toBe(false)
+ expect(router.canSpeakQuestion('ghost')).toBe(false)
+ // A known local agent on a daemon that cannot confirm a reviewed answer.
+ const unconfirmed = new FleetRouter(localOf({}, [session('a1', 1)]))
+ await unconfirmed.listAgentsFlat()
+ expect(unconfirmed.canSpeakQuestion('a1')).toBe(false)
+ const spoken = { ...answer, freeTextKeys: ['scope'] }
+ expect(await router.answerReviewed(spoken)).toEqual({ ok: true })
+ expect(await router.answerReviewed({ ...spoken, agentId: 'r1' })).toEqual({ ok: false, error: 'Use the terminal to type this answer.' })
+ expect(await router.answerReviewed({ ...answer, freeTextKeys: [] })).toEqual({ ok: true })
+ })
+
+ it('is handed to a remote machine, never to one that is unreachable, and never as a comma-split multi-select', async () => {
+ const fleet = fleetOf([REMOTE])
+ const router = new FleetRouter(localOf(), fleet)
+ router.noteAgent('other', 'r1')
+ const remote = { ...answer, agentId: 'r1' }
+ // An older fleet that has only the plain answer.
+ expect(await router.answerReviewed(remote)).toEqual({ ok: true, pending: true })
+ expect(fleet.answer).toHaveBeenCalledWith('other', 'r1', 'question-1', { scope: 'File' })
+ fleet.answerReviewed = vi.fn()
+ expect(await router.answerReviewed(remote)).toEqual({ ok: true, pending: true })
+ expect(fleet.answerReviewed).toHaveBeenCalledWith('other', remote)
+ fleet.reachable = () => ({ ok: false, at: Date.now() })
+ expect(await router.answerReviewed(remote)).toEqual({ ok: false, error: 'That machine is unavailable. Check its connection.' })
+ fleet.reachable = () => ({ ok: true, at: Date.now() })
+ const multi = { ...remote, questions: [{ ...remote.questions[0], multi: true }] }
+ expect(await router.answerReviewed({ ...multi, selections: { scope: ['CSV, UTF-8'] } })).toEqual({ ok: false, error: 'Use the terminal for this multi-select answer.' })
+ expect(await router.answerReviewed({ ...multi, selections: {} })).toEqual({ ok: true, pending: true })
+ expect(await router.answerReviewed({ ...multi, selections: { scope: ['CSV'] } })).toEqual({ ok: true, pending: true })
+ // No fleet at all: a remote agent heard from cannot be answered.
+ const alone = new FleetRouter(localOf())
+ alone.noteAgent('other', 'r1')
+ expect(await alone.answerReviewed(remote)).toEqual({ ok: false, error: 'That machine is unavailable. Check its connection.' })
+ })
+})
diff --git a/cli/src/services/fleetRouter.ts b/cli/src/services/fleetRouter.ts
new file mode 100644
index 000000000..cd51609bb
--- /dev/null
+++ b/cli/src/services/fleetRouter.ts
@@ -0,0 +1,526 @@
+/**
+ * Which machine an agent is on, and getting a turn, a stop or an answer to it there: the turn router
+ * across the owner's machines (docs/design/2026-10-03-harnessd.md, "Devices", step D0).
+ *
+ * It lived inside the dial's host (cable/cableHost.ts), so ⌘K and the window's voice route reached
+ * another machine's agent only through the dial: with the dial off, ⌘K would have answered "no agent
+ * list yet". It belongs to the fleet service now (services/fleet.ts), and ⌘K, the voice route and the
+ * dial all send through one router, so who the person was just talking to (`lastRouted`) is one fact
+ * for all three, as it was when the dial's host held it.
+ *
+ * Its own file, apart from the service that builds it, so the dial's host can build one over a bare
+ * fleet (its tests, and a daemon whose fleet service is off) without loading the cloud socket and the
+ * E2EE stores the service starts.
+ */
+import { extendShortRecap } from '../lib/deviceRecap.js'
+import type { RegisteredSession } from '../lib/registry.js'
+import type { RouterContinuity } from '../lib/voiceRouter.js'
+import type { RecentTurn } from '../cable/cableHost.js'
+import type { CableAgent, CableMachine, CableMachineSource } from '../cable/cableSession.js'
+import type { FleetMachine, MachineFleet } from '../cable/machineFleet.js'
+import type { AnswerReceipt, ReviewedAnswer } from '../cable/questionInbox.js'
+
+/** What a fork answers: the new agent's id, or why not. */
+export type ForkResult = { ok: true; agentId: string } | { ok: false; error: string; detail?: string }
+
+/** What a delivered turn answers: delivered, or refused with the machine's name and a reason a person can read. */
+export type SendResult = { ok: true } | { ok: false; machine: string; reason: string }
+
+/**
+ * This computer, as the router needs it: its identity, its agents, the window's tiles, and the doors a
+ * turn, a stop or an answer for one of its own agents goes through. The dial's host fills it from its
+ * wiring; the fleet service from the core (`CoreApi`).
+ */
+export interface FleetLocal {
+ machineName(): string
+ /** This computer's machineId, or '' when the daemon has never resolved one (signed out). */
+ machineId(): string
+ /** A stable id for this computer, used to name the local row when there is no machineId yet. */
+ computerId(): string
+ /** The live agents the apps are shown. */
+ sessions(): RegisteredSession[]
+ /** The name the apps show for an agent. */
+ displayName(session: RegisteredSession): string
+ /** The opaque runtime-v1 profile, which is where the dial's Model/Effort chips come from. */
+ runtimeProfile?: (session: RegisteredSession) => string | null
+ /** The window's tiles on its active tab, in tile order, as last reported. */
+ desk(): string[]
+ /** Deliver text into a local agent. The SAME path the web and the WiFi device use. */
+ sendTurn: (agentId: string, text: string) => void
+ stopTurn: (agentId: string) => void
+ answer: (agentId: string, requestId: string, answers: Record<string, string>) => void
+ answerReviewed?: (answer: ReviewedAnswer) => Promise<boolean>
+ /** Recaps of a local agent's last `n` completed turns. */
+ recent: (agentId: string, n: number) => RecentTurn[]
+ /** The person's own last questions to a LOCAL agent, newest first. */
+ recentAsks: (agentId: string) => string[]
+ updateAgent?: (agentId: string, model?: string, effort?: string) => void
+ listModels?: (agentId: string) => Promise<Array<{ id: string }>>
+ /** Fork a LOCAL agent — see lib/forkAgent.ts. Resolves to the new agent's id. */
+ forkAgent?: (agentId: string) => Promise<ForkResult>
+ log: (line: string) => void
+}
+
+/**
+ * A placeholder id for a machine this daemon does not know the real id of.
+ *
+ * A BELT, not a mode. `harness start` refuses to run without an SSO session and awaits
+ * `resolveComputerMachine()` before it spawns the daemon, so by the time anything here runs the machineId
+ * is real. The guard exists because the alternative failure is silent: an empty id makes a row that
+ * renders, is tappable, and can never be selected. `cable:` is deliberately not machineId-shaped, so
+ * nothing downstream mistakes it for one and announces it to the backend.
+ */
+function placeholderId(computerId: string): string {
+ return `cable:${computerId}`
+}
+
+/** How often another machine's agent list is re-asked. Far slower than the dial's one-second tick: the
+ * list changes when a person starts an agent, not continuously. */
+const REMOTE_REFRESH_MS = 5_000
+/** How long a machine's last good list survives failures before its tiles leave the carousel. */
+const REMOTE_GRACE_MS = 30_000
+
+/** A fleet row as the wire carries it. `authMode` does not travel: the dial has no use for the word, and
+ * `remote` is just `!local`, which the row already says. */
+function toCableMachine(m: FleetMachine): CableMachine {
+ return { id: m.machineId, name: m.name, state: m.state, local: false }
+}
+
+/** Split `runtime-v1:<sid>:<engine>:<model>@<effort>` back into the two words the dial's chips show. */
+function chipsFromProfile(profile: string | null | undefined): { model?: string; effort?: string } {
+ if (!profile || !profile.startsWith('runtime-v1:')) return {}
+ const tail = profile.split(':').slice(3).join(':')
+ if (!tail) return {}
+ const [model, effort] = tail.split('@')
+ return { model: model || undefined, effort: effort || undefined }
+}
+
+export class FleetRouter {
+ /** 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 }
+
+ /** Each other machine's agents, as last read. `asked` throttles the round; `at` ages the answer. */
+ private readonly remoteAgents = new Map<string, { agents: CableAgent[]; at: number; asked: number }>()
+ /** Machines with a list RPC in flight, so a slow machine is asked once rather than every tick. */
+ private readonly inFlight = new Set<string>()
+ /** agentId → machineId, rebuilt from the snapshot last handed to the dial. */
+ private agentMachine = new Map<string, string>()
+
+ /**
+ * Every agent this daemon has listed since it started, by id.
+ *
+ * Kept for ONE purpose: a tile open in the window must always be a tile on the dial. A machine can
+ * leave the list for reasons that have nothing to do with its agents — the backend going quiet, the
+ * machine going offline while its work stays on screen — and a desk with a hole in it makes a swipe
+ * skip a tile and an agent chosen in the window have nowhere to land.
+ */
+ private readonly knownAgents = new Map<string, CableAgent>()
+
+ /** Tiles currently held on the list from that memory, so it is logged once and not every tick. */
+ private readonly deskHeld = new Set<string>()
+
+ /** Size of the last flat list — see agentTotal. */
+ private flatCount = 0
+
+ /** agentId → machineId for agents heard from but not (yet) listed — see noteAgent. */
+ private readonly seenOn = new Map<string, string>()
+ /** machineId → name, from the last wheel read, for describe(). */
+ private machineNames = new Map<string, string>()
+
+ /** `fleet` undefined = no lane to any other machine exists; every agent is this computer's. */
+ constructor(private readonly local: FleetLocal, readonly fleet?: MachineFleet) {}
+
+ /** This computer's id, or the placeholder when it has none yet. */
+ localId(): string {
+ return this.local.machineId() || placeholderId(this.local.computerId())
+ }
+
+ async listMachines(): Promise<{ machines: CableMachine[]; source: CableMachineSource }> {
+ const local: CableMachine = {
+ id: this.localId(),
+ // The machine's own name. What makes this row recognisable as the cabled one is its second line,
+ // which the dial writes — see machine_meta_line.
+ name: this.local.machineName(),
+ // Always ready: the cable IS the evidence. Nothing else on this list can say that about itself.
+ state: 'ready',
+ local: true,
+ }
+ if (!this.fleet) return { machines: [local], source: 'signed-out' }
+ const { machines, source } = await this.fleet.list()
+ const rows: CableMachine[] = [local]
+ for (const m of machines) {
+ // The backend list contains THIS computer too. Dropped rather than rendered: the same machine on
+ // the wheel twice, under two names, with the ✓ able to mark only one of them. Its name is already
+ // here anyway — MACHINE_NAME_FILE is mirrored from the backend on every connect.
+ if (m.machineId === local.id) continue
+ rows.push(toCableMachine(m))
+ }
+ return { machines: rows, source }
+ }
+
+ /** This computer's own agents, in the order every other surface reads them in. */
+ private localAgents(): CableAgent[] {
+ // `advertised()`, not `list()` — the SAME set `agents_list` answers the web and the desktop app with. They
+ // read one registry and must not disagree about what is on it: a dead agent holding a tile on the dial
+ // and nowhere else is a tile that cannot be driven and cannot be explained.
+ // Terminals INCLUDED. A shell has no turn to watch and no model to switch, and the dial does not
+ // pretend otherwise — it draws the tile and offers no Voice on it. What it does offer is the
+ // thing that was missing: the tile can be reached. The window draws a shell as a tile like any
+ // other, so a dial that skipped it disagreed with the app about what was on the desk, and a pane
+ // the carousel cannot walk to is a pane the dial cannot explain either. A terminal that has
+ // adopted an engine is that engine here, as everywhere.
+ //
+ // ⚠️ NOT the same question as `deviceAgentRow` in backendSocket.ts, which keeps shells out of the
+ // `agents_list` RPC a CLOUD device asks over the backend. This is the cable's own list, pulled by
+ // `listAgents()` on the session's tick; the two surfaces answer separately and always did.
+ const sessions = this.local.sessions()
+ // Oldest → newest, and TOTAL: the id breaks a tie so the order cannot fall through to array position,
+ // which is Map insertion order and differs between daemon runs. Both producers sort identically, so
+ // the dial and the app cannot drift apart while reading the same registry.
+ sessions.sort((a, b) => a.registeredAt - b.registeredAt || a.agentId.localeCompare(b.agentId))
+ const machineId = this.localId()
+ const machine = this.local.machineName()
+ return sessions.map((s) => ({
+ id: s.agentId,
+ name: this.local.displayName(s),
+ engine: s.engine ?? '',
+ machineId,
+ machine,
+ ...chipsFromProfile(this.local.runtimeProfile?.(s)),
+ }))
+ }
+
+ /**
+ * Name, engine and machine of an agent this daemon has ever listed — for a `summary` or `question`
+ * about one the dial no longer holds. The dial used to look these up in its own copy of the fleet;
+ * with that copy gone, the frame has to say who it is about.
+ */
+ describe(agentId: string): { name: string; engine: string; machine: string } | undefined {
+ const a = this.knownAgents.get(agentId) ?? this.localAgents().find((x) => x.id === agentId)
+ if (a) return { name: a.name, engine: a.engine ?? '', machine: a.machine ?? '' }
+ // A remote agent whose machine has spoken (a question, a card) before its list was ever read: no
+ // name to give, but the machine's is better than nothing on a screen asking for a decision.
+ const machineId = this.seenOn.get(agentId)
+ const machine = machineId ? this.machineNames.get(machineId) ?? '' : ''
+ return machineId ? { name: '', engine: '', machine } : undefined
+ }
+
+ /**
+ * A card arrived from a machine for an agent. Remembered so a `question` or `summary` about an agent
+ * this daemon has never LISTED — a remote machine's, before its list was read, or one on a tab the
+ * window has not opened — can still be described and, when tapped, opened: `machineOf` falls back to
+ * this, and without it the open was "ignored for unknown agent" and the tap did nothing.
+ */
+ noteAgent(machineId: string, agentId: string): void {
+ if (machineId && agentId) this.seenOn.set(agentId, machineId)
+ }
+
+ /**
+ * EVERY agent in LIST order — this computer first, then each machine in wheel order — the fleet the
+ * dial no longer holds.
+ *
+ * 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. The dial's
+ * `listAgents()` is its 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.
+ *
+ * Read from a CACHE, never from a live RPC. The dial calls this on the session's one-second tick, and a
+ * naive implementation would fire one cloud round trip per machine per second — the dial would spend
+ * its whole life waiting on the network to answer a question whose answer changes every few minutes.
+ * `refreshRemotes()` does the asking, off to the side, on its own slower clock.
+ */
+ async listAgentsFlat(): Promise<CableAgent[]> {
+ const out = this.localAgents()
+ const { machines } = await this.listMachines()
+ this.machineNames = new Map(machines.map((m) => [m.id, m.name]))
+ for (const m of machines) {
+ if (m.local) continue
+ const entry = this.remoteAgents.get(m.id)
+ if (entry) for (const a of entry.agents) out.push({ ...a, machineId: m.id, machine: m.name })
+ }
+ this.refreshRemotes(machines)
+ // Rebuilt from the SAME snapshot that is about to be pushed, so the map can never name a machine an
+ // agent has already left. Every action the dial can take is routed through it.
+ const next = new Map<string, string>()
+ for (const a of out) if (a.machineId) next.set(a.id, a.machineId)
+ this.agentMachine = next
+
+ const byId = new Map(out.map((a) => [a.id, a]))
+
+ for (const a of out) this.knownAgents.set(a.id, a)
+ // A tile the window has open, whose agent has left the list. Put it back — under the name and
+ // machine it was last seen with, so the dial's tile keeps saying what the window's tile says.
+ //
+ // Gated on being ON THE DESK, and only that: an agent that was deleted, or one simply never
+ // opened, must not be resurrected by this memory. The window holding a tile is the whole warrant.
+ const missing = this.local.desk().filter((id) => !byId.has(id))
+ for (const id of missing) {
+ const remembered = this.knownAgents.get(id)
+ if (!remembered) continue
+ // Appended, not slotted back where it was. When a machine drops out none of its agents are left
+ // to sit beside, so the end of the list is the only honest place; the tab's list is drawn in TILE
+ // order by the dial's listAgents, so where it sits here does not matter. Never routed by position
+ // either — `agentMachine` below is what sends a turn home.
+ out.push(remembered)
+ byId.set(id, remembered)
+ if (remembered.machineId) this.agentMachine.set(id, remembered.machineId)
+ if (!this.deskHeld.has(id)) {
+ this.deskHeld.add(id)
+ this.local.log(`cable: holding ${id.slice(0, 8)} on the tab — the window has a tile for it`)
+ }
+ }
+ for (const id of [...this.deskHeld]) if (!missing.includes(id)) this.deskHeld.delete(id)
+
+ // The overview's number is AGENTS, and a shell is not one. The carousel carries shell tiles now —
+ // they are panes the window has and the dial can reach — but "12 agents · all idle" is read as how
+ // much work is in flight, and counting empty terminals in it would answer a question nobody asked.
+ // Two different numbers about the same desk, each honest about what it counts.
+ this.flatCount = out.filter((a) => a.engine !== 'terminal').length
+ return out
+ }
+
+ /** How many agents the account has across every machine — the overview's number, sent beside the
+ * tab's list rather than as 70 rows the dial would hold for a digit. Read from the last flat list,
+ * minus the terminals in it: the list is every TILE, this is every AGENT. */
+ agentTotal(): number {
+ return this.flatCount
+ }
+
+ /**
+ * Which machine an agent lives on, or '' if the dial named one this daemon has never listed.
+ *
+ * NEVER falls back to the selected machine. A wrong answer here does not fail — it delivers the user's
+ * turn to a different computer, which is the worst outcome this whole feature can produce.
+ */
+ machineOf(agentId: string): string {
+ return this.agentMachine.get(agentId) ?? this.seenOn.get(agentId) ?? ''
+ }
+
+ /** Whether this daemon's last list held that agent — see CableHost.knows. */
+ knows(agentId: string): boolean {
+ return this.agentMachine.has(agentId)
+ }
+
+ /** True when the agent belongs to this computer (or is unknown, which is handled at the call site). */
+ isLocalAgent(agentId: string): boolean {
+ const machineId = this.machineOf(agentId)
+ return !machineId || machineId === this.localId()
+ }
+
+ /**
+ * Fork an agent on its own machine: the same `agent_fork` the window sends. The new agent is noted on
+ * that machine at once, so the open that follows lands before any list has named it. `attempted` hears
+ * how a fork that was actually asked for went, with the machine it was asked of: a refusal before
+ * asking anyone (an agent never listed, a daemon or a fleet that cannot fork) is only returned.
+ */
+ async forkAgent(agentId: string, attempted?: (machineId: string, result: ForkResult) => void): Promise<ForkResult> {
+ const machineId = this.machineOf(agentId)
+ if (!machineId) return { ok: false, error: 'AGENT_NOT_FOUND', detail: 'The dial named an agent this daemon has never listed.' }
+ let result: ForkResult
+ if (this.isLocalAgent(agentId)) {
+ if (!this.local.forkAgent) return { ok: false, error: 'UNSUPPORTED', detail: 'This daemon cannot fork agents.' }
+ result = await this.local.forkAgent(agentId)
+ } else {
+ if (!this.fleet?.forkAgent) return { ok: false, error: 'UNSUPPORTED_ON_REMOTE' }
+ try {
+ result = { ok: true, agentId: await this.fleet.forkAgent(machineId, agentId) }
+ } catch (err) {
+ result = { ok: false, error: 'FORK_FAILED', detail: (err as Error).message }
+ }
+ }
+ if (result.ok) this.seenOn.set(result.agentId, machineId)
+ attempted?.(machineId, result)
+ return result
+ }
+
+ /**
+ * Refresh the other machines' agent lists, on their own clock.
+ *
+ * Only `ready` machines are asked. An offline one has nothing to say and an unlinked one cannot be
+ * read at all (no pinned key), and asking either costs a 15-second RPC timeout per machine per round.
+ *
+ * A machine that fails keeps its LAST GOOD list for `REMOTE_GRACE_MS` and only then goes empty. A cloud
+ * blip is the common case, and dropping every one of a machine's tiles off the carousel for a few
+ * seconds — then putting them back — is a far worse lie than briefly showing a list that is a minute
+ * old.
+ *
+ * `unknown` is NOT a reason to drop anything, and reading it as one cost a morning. It means the
+ * backend could not be asked — `MachineListCache.degrade()` sets every machine to it in one go when
+ * the list cannot be refreshed, on the stated principle that the rows are "stale but not wrong". The
+ * agents follow the rows: kept, with no timer, until the backend actually says offline. Measured on
+ * the real dial, the old reading emptied a remote machine off the carousel mid-session with no log
+ * line, while the window went on showing those agents — which is what made a swipe run out of agents
+ * early, and an agent chosen in the window have no tile to move to.
+ */
+ private refreshRemotes(machines: CableMachine[]): void {
+ if (!this.fleet) return
+ const fleet = this.fleet
+ const now = Date.now()
+ for (const m of machines) {
+ if (m.local) continue
+ const entry = this.remoteAgents.get(m.id)
+ if (m.state === 'offline' || m.state === 'needs-link') {
+ // The machine ITSELF says it has nothing to offer, which is different from not being able to
+ // ask it. No grace period, but never silently: an agent leaving the carousel is exactly the
+ // event that is impossible to diagnose after the fact from its absence.
+ if (entry && entry.agents.length) {
+ this.remoteAgents.set(m.id, { agents: [], at: now, asked: entry.asked })
+ this.local.log(`cable: ${m.name} is ${m.state} — its ${entry.agents.length} agents left the carousel`)
+ }
+ continue
+ }
+ // Not ready and not refused: the backend could not be asked. Keep what it last said.
+ if (m.state !== 'ready') continue
+ if (entry && now - entry.asked < REMOTE_REFRESH_MS) continue
+ if (this.inFlight.has(m.id)) continue
+ this.inFlight.add(m.id)
+ this.remoteAgents.set(m.id, { agents: entry?.agents ?? [], at: entry?.at ?? 0, asked: now })
+ void fleet.listAgents(m.id)
+ .then((agents) => {
+ const before = this.remoteAgents.get(m.id)
+ this.remoteAgents.set(m.id, { agents, at: Date.now(), asked: Date.now() })
+ // One line per TRANSITION, not per round: this runs every few seconds forever, and a healthy
+ // machine that logs each time buries everything else in the file.
+ if (!before || before.agents.length !== agents.length) {
+ this.local.log(`cable: ${m.name} → ${agents.length} agents`)
+ }
+ })
+ .catch((err) => {
+ const before = this.remoteAgents.get(m.id)
+ const stale = before && Date.now() - before.at > REMOTE_GRACE_MS
+ if (stale) this.remoteAgents.set(m.id, { agents: [], at: Date.now(), asked: Date.now() })
+ if (before?.agents.length && stale) {
+ this.local.log(`cable: ${m.name} dropped off the carousel (${(err as Error).message})`)
+ }
+ })
+ .finally(() => this.inFlight.delete(m.id))
+ }
+ }
+
+ /**
+ * 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): SendResult {
+ if (!this.isLocalAgent(agentId)) {
+ const machineId = this.machineOf(agentId)
+ const machine = this.knownAgents.get(agentId)?.machine || machineId.slice(0, 8)
+ const seen = this.fleet?.reachable?.(machineId)
+ if (seen && !seen.ok) {
+ const ago = Math.round((Date.now() - seen.at) / 1000)
+ this.local.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)
+ this.spokeTo(agentId)
+ return { ok: true }
+ }
+ this.local.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.local.stopTurn(agentId)
+ }
+
+ canSpeakQuestion(agentId: string): boolean {
+ // Remote receiver capabilities are not negotiated yet; no free-text fallback.
+ return this.knows(agentId) && this.isLocalAgent(agentId) && !!this.local.answerReviewed
+ }
+
+ async answerReviewed(answer: ReviewedAnswer): Promise<AnswerReceipt> {
+ if (answer.freeTextKeys?.length && !this.canSpeakQuestion(answer.agentId))
+ return { ok: false, error: 'Use the terminal to type this answer.' }
+ if (!this.isLocalAgent(answer.agentId)) {
+ const machineId = this.machineOf(answer.agentId)
+ if (!this.fleet || this.fleet.reachable?.(machineId)?.ok === false) {
+ return { ok: false, error: 'That machine is unavailable. Check its connection.' }
+ }
+ // Older remote drivers split multi-select labels on commas. Do not lose
+ // a selected label when that receiver cannot prove support for exact arrays.
+ if (answer.questions.some(q => q.multi && answer.selections[q.key]?.some(label => label.includes(',')))) {
+ return { ok: false, error: 'Use the terminal for this multi-select answer.' }
+ }
+ if (this.fleet.answerReviewed) this.fleet.answerReviewed(machineId, answer)
+ else this.fleet.answer(machineId, answer.agentId, answer.requestId, answer.answers)
+ return { ok: true, pending: true } // Handoff only; the dialog's close is authoritative.
+ }
+ if (!this.local.answerReviewed) return { ok: false, error: 'Update Harness to answer this question.' }
+ const ok = await this.local.answerReviewed(answer)
+ return ok ? { ok: true } : { ok: false, error: 'Could not confirm the answer. Check the terminal.' }
+ }
+
+ answer(agentId: string, requestId: string, answers: Record<string, string>): void {
+ if (!this.isLocalAgent(agentId)) { this.fleet!.answer(this.machineOf(agentId), agentId, requestId, answers); return }
+ this.local.answer(agentId, requestId, answers)
+ }
+
+ updateAgent(agentId: string, model?: string, effort?: string): void {
+ if (!this.isLocalAgent(agentId)) { this.fleet!.updateAgent(this.machineOf(agentId), agentId, model, effort); return }
+ this.local.updateAgent?.(agentId, model, effort)
+ }
+
+ /** 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; ask: string }>> {
+ const raw = this.isLocalAgent(agentId)
+ ? this.local.recent(agentId, 3)
+ : await this.fleet!.recentSummaries(this.machineOf(agentId), agentId)
+ return raw
+ .map((r) => ({ recap: extendShortRecap(r?.recap ?? '', r?.text ?? ''), text: r?.text ?? '', ask: r?.ask ?? '' }))
+ .filter((s) => s.recap || s.text || s.ask)
+ }
+
+ /**
+ * The person's own last questions to an agent, newest first — what the router ranks on.
+ *
+ * Its own trip rather than a field on [recentSummaries]: a question is recorded when it is asked and
+ * a recap when the answer is summarised, so the two lists are different lengths on any machine where
+ * a turn ended without one. Folding them together is what left the newest question — the one that
+ * says where the next one belongs — off the end.
+ */
+ async recentAsks(agentId: string): Promise<string[]> {
+ const raw = this.isLocalAgent(agentId)
+ ? this.local.recentAsks(agentId)
+ : await this.fleet!.recentAsks(this.machineOf(agentId), agentId)
+ return raw.map((a) => (a || '').replace(/\s+/g, ' ').trim()).filter(Boolean)
+ }
+
+ async listModels(agentId: string): Promise<string[]> {
+ if (!this.isLocalAgent(agentId)) return this.fleet!.listModels(this.machineOf(agentId), agentId)
+
+ const models = (await this.local.listModels?.(agentId)) ?? []
+ return models.map((m) => m.id).filter(Boolean)
+ }
+}
diff --git a/cli/src/services/searchProcess.spec.ts b/cli/src/services/searchProcess.spec.ts
index ddd967d3d..4952c0f52 100644
--- a/cli/src/services/searchProcess.spec.ts
+++ b/cli/src/services/searchProcess.spec.ts
@@ -122,6 +122,15 @@ describe('search in its own process', () => {
expect(api.agents.terminalAvailable('live')).toBe(false)
api.agents.sync(live as never)
await expect(api.agents.runtimeModels('live')).resolves.toEqual([])
+ expect(api.agents.runtimeProfile(live as never)).toBeNull()
+ api.agents.setRuntime('live', 'opus')
+ await expect(api.agents.fork('live')).resolves.toEqual({ ok: false, error: 'UNSUPPORTED' })
+ api.turns.send('live', 'text')
+ api.turns.stop('live')
+ expect(api.turns.recent('live', 3)).toEqual([])
+ expect(api.turns.asks('live')).toEqual([])
+ api.questions.answer('live', 'q', {})
+ await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)
expect(api.transcripts.databaseHistory({ engine: 'claude' } as never)).toBeUndefined()
expect(api.external.sessions.list()).toEqual([])
await expect(api.account.mintGridName()).resolves.toBeNull()
diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.ts
index f86cbbfb5..de48fd4e2 100644
--- a/cli/src/services/searchProcess.ts
+++ b/cli/src/services/searchProcess.ts
@@ -49,7 +49,13 @@ export function searchCoreApi(
terminalAvailable: () => false,
sync: () => {},
runtimeModels: async () => [],
+ runtimeProfile: () => null,
+ setRuntime: () => {},
+ fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),
},
+ // Search drives no agent: these are never asked of it.
+ turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [] },
+ questions: { answer: () => {}, answerReviewed: async () => false },
transcripts: { databaseHistory },
external: {
sessions: new ExternalSessions({ providers, excluded: [dataDir], log: console.warn }),
diff --git a/cli/src/services/viewersProcess.spec.ts b/cli/src/services/viewersProcess.spec.ts
index 2c8e54441..8c6ae10ff 100644
--- a/cli/src/services/viewersProcess.spec.ts
+++ b/cli/src/services/viewersProcess.spec.ts
@@ -232,6 +232,15 @@ describe('the viewers in their own process', () => {
await expect(api.account.privateGridName()).resolves.toBeNull()
expect(api.account.machineName()).toBeNull()
await expect(api.agents.runtimeModels()).resolves.toEqual([])
+ expect(api.agents.runtimeProfile(agent())).toBeNull()
+ api.agents.setRuntime('a1', 'opus')
+ await expect(api.agents.fork('a1')).resolves.toEqual({ ok: false, error: 'UNSUPPORTED' })
+ api.turns.send('a1', 'text')
+ api.turns.stop('a1')
+ expect(api.turns.recent('a1', 3)).toEqual([])
+ expect(api.turns.asks('a1')).toEqual([])
+ api.questions.answer('a1', 'q', {})
+ await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)
api.clients.gridNamed('grid')
api.clients.gridModelsChanged()
api.clients.dshInstallStatus({ phase: 'clone' })
diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.ts
index a020a9cdf..ed6ecce18 100644
--- a/cli/src/services/viewersProcess.ts
+++ b/cli/src/services/viewersProcess.ts
@@ -59,7 +59,13 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, Re
terminalAvailable: () => true,
sync: (session) => tell(session.agentId),
runtimeModels: async () => [],
+ runtimeProfile: () => null,
+ setRuntime: () => {},
+ fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),
},
+ // The viewers drive no agent: these are never asked of them.
+ turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [] },
+ questions: { answer: () => {}, answerReviewed: async () => false },
transcripts: { databaseHistory: () => undefined },
external: {
sessions: { list: () => [], scan: async () => [] },
diff --git a/cli/src/services/workspacesProcess.spec.ts b/cli/src/services/workspacesProcess.spec.ts
index 310b9ee3a..26af06036 100644
--- a/cli/src/services/workspacesProcess.spec.ts
+++ b/cli/src/services/workspacesProcess.spec.ts
@@ -167,6 +167,15 @@ describe('workspaces in their own process', () => {
await expect(api.account.privateGridName()).resolves.toBeNull()
expect(api.account.machineName()).toBeNull()
await expect(api.agents.runtimeModels()).resolves.toEqual([])
+ expect(api.agents.runtimeProfile({} as never)).toBeNull()
+ api.agents.setRuntime('a1', 'opus')
+ await expect(api.agents.fork('a1')).resolves.toEqual({ ok: false, error: 'UNSUPPORTED' })
+ api.turns.send('a1', 'text')
+ api.turns.stop('a1')
+ expect(api.turns.recent('a1', 3)).toEqual([])
+ expect(api.turns.asks('a1')).toEqual([])
+ api.questions.answer('a1', 'q', {})
+ await expect(api.questions.answerReviewed({} as never)).resolves.toBe(false)
api.clients.gridModelsChanged()
api.clients.viewerChanged('a1')
api.clients.gridNamed('grid')
diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.ts
index b9d771f2e..bc78125db 100644
--- a/cli/src/services/workspacesProcess.ts
+++ b/cli/src/services/workspacesProcess.ts
@@ -58,7 +58,13 @@ export function workspacesCoreApi(
terminalAvailable: () => false,
sync: (session) => renamed(session.agentId),
runtimeModels: async () => [],
+ runtimeProfile: () => null,
+ setRuntime: () => {},
+ fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),
},
+ // The workspaces drive no agent: these are never asked of them.
+ turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [] },
+ questions: { answer: () => {}, answerReviewed: async () => false },
transcripts: { databaseHistory: () => undefined },
external: {
sessions: { list: () => [], scan: async () => [] },
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index 9c7a87a77..6f5a324c3 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -20,8 +20,13 @@ export function fakeCore(over: Overrides = {}): CoreApi {
terminalAvailable: vi.fn(() => false),
sync: vi.fn(),
runtimeModels: vi.fn(async () => []),
+ runtimeProfile: vi.fn(() => null),
+ setRuntime: vi.fn(),
+ fork: vi.fn(async () => ({ ok: false as const, error: 'UNSUPPORTED' })),
...over.agents,
},
+ turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(() => []), asks: vi.fn(() => []), ...over.turns },
+ questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => false), ...over.questions },
transcripts: { databaseHistory: vi.fn(() => undefined), ...over.transcripts },
external: {
sessions: { list: vi.fn(() => []), scan: vi.fn(async () => []) },
diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.md
index 07a3f2b6b..f10d3faf5 100644
--- a/docs/design/2026-10-03-harnessd.md
+++ b/docs/design/2026-10-03-harnessd.md
@@ -201,12 +201,12 @@ lines wire it inside `runForeground`. Every call the core makes into it is guard
(`outsideConsumers('devices')`), so an exception there costs one call. A native crash in the serial
port code, or a leak, would still cost the whole core. Three couplings decide the order:
-1. **The dial's host also routes turns between machines.** ⌘K and the window's voice route send a
- turn through `DaemonCableHost.sendTurn`. It knows a local agent from a remote one by the agent
- lists it learned from the fleet (`DeviceFleet` over `DeviceLink`, the lane to the owner's other
- machines). With the dial off, ⌘K would answer "no agent list yet". So the router, and the fleet
- and machine list it reads, leave the dial's host first, as a fleet service of their own that ⌘K
- and the dial both use.
+1. **The dial's host also routed turns between machines** (until D0). ⌘K and the window's voice
+ route sent a turn through `DaemonCableHost.sendTurn`. It knew a local agent from a remote one by
+ the agent lists it learned from the fleet (`DeviceFleet` over `DeviceLink`, the lane to the
+ owner's other machines). With the dial off, ⌘K would have answered "no agent list yet". So the
+ router, and the fleet and machine list it reads, left the dial's host first, as a fleet service of
+ their own that ⌘K and the dial both use.
2. **The Wi-Fi device rides the relay's encrypted sessions.** `AutonomousDeviceService` and
`AutonomousDeviceDirect` pair, attach and receive through `BackendSocket`, so they move with the
relay, after it has a boundary of its own.
@@ -216,9 +216,37 @@ port code, or a leak, would still cost the whole core. Three couplings decide th
The steps, each a pull request with its end-to-end proof:
-- **D0, the fleet on its own.** The machine list, peers, `DeviceLink`, `DeviceFleet` and the turn
- router across machines become `services/fleet.ts`. ⌘K, the voice route and the dial all send
- turns through it.
+- **D0, the fleet on its own** (done). The machine list refresh, the pinned peers, `DeviceLink`,
+ `DeviceFleet` and the turn router across machines are `services/fleet.ts`, started by the service
+ host. The router is `services/fleetRouter.ts`: which machine an agent is on, the turn, stop,
+ answer, model switch, recap and fork sent there, the refusal for a machine whose last request did
+ not come back, and `lastRouted`. Its local side is the core's own doors, new `CoreApi` members
+ (`turns`, `questions`, and the runtime profile, model switch, models and fork on `agents`). ⌘K's
+ `route_task` (with its ranking, moved out of `runForeground`) and `route_send`, which the voice
+ route commits through, reach it through `ports.fleet` (`FleetPort`, with fallbacks). The dial's
+ host is handed the same router until D1, so the person's last turn is one fact for all three; with
+ the fleet off it routes this computer alone. The machine list cache itself is still built early in
+ `runForeground`, for the local `/api/machines` answer and the trust group, and the lane still signs
+ in and seals with the relay's credentials, handed to the service until they move with it (D3).
+
+ **Two machines, end to end** (`cli/e2e/fleet.e2e.ts`). Two real daemons are two machines on one
+ account (`e2e/harness/fleet.ts`): each has its own computer id, machine id, E2EE identity and
+ signed-in session, and A is linked to B the way `harness link connect` leaves them. They are
+ signed in to a fake backend on 127.0.0.1 (`e2e/harness/fakeBackend.ts`): the machine list, each
+ daemon's adapter socket, and a blind device relay, so the encrypted session between the machines
+ is the real one. A's dial is a fake dial on a pseudo-terminal (`e2e/harness/fakeDial.ts`) speaking
+ the cable protocol with the daemon's own frame codec; `HARNESSD_TEST_DIAL_PORT` is the one test
+ switch in the daemon, because a pseudo-terminal is not on the USB bus that discovery reads. Proven:
+ ⌘K on A picks B's agent and delivers to it; the dial on A stops, answers and forks on B; B going
+ away is refused ("did not come back") and B coming back is used again; and A's fleet service
+ failing costs A only its routing. Every URL setting points at the fake, and the harness refuses a
+ daemon whose environment names any other server.
+
+ **Still to decide: the lane follows the dial.** A's lane to the other machines opens only when a
+ dial attaches (`onDialAttached` → `fleet.online()`) or selects a machine. With no dial, ⌘K weighs
+ this computer's agents alone and never sees another machine's, so cross-machine ⌘K works today only
+ with a dial plugged in. Opening the lane for ⌘K changes what the backend counts as a commander
+ watching each machine, so it is a decision, not a refactor.
- **D1, the dial behind the boundary, in process.** `services/dial.ts` owns the serial ports, the
dial's host, its log and the `harness_devices_*` requests. The core reaches it through a `DialPort`, each member with its fallback: the desk, the
swarms, what is unread, focus, what was seen, the turn and question events teed to it, settings,
@@ -228,7 +256,7 @@ The steps, each a pull request with its end-to-end proof:
- **D2, the dial in its own process.** The serial ports belong to `harness __service dial`; the
same handlers answer. A crash in the native serial code then costs the dial alone, and the master
starts it again. It is proven end to end with a fake dial on a pseudo-terminal, speaking the cable
- protocol from `cable/vectors/`.
+ protocol (the fake dial and the two-machine fleet from D0's proof are there to reuse).
- **D3, the Wi-Fi device**, with the relay.
### Models