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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
harnessd: devices D1, the dial reaches the fleet through the core's port (#798)
Dee9c03107beced
diff --git a/cli/e2e/fleet.e2e.ts b/cli/e2e/fleet.e2e.tsindex 40d19c6ed..dd0225752 100644--- a/cli/e2e/fleet.e2e.ts+++ b/cli/e2e/fleet.e2e.ts@@ -175,8 +175,28 @@ describe('two machines in one fleet', () => {onA.close()})+ it('the dial\'s routing failing through the port leaves the dial serving A, and ⌘K serving both machines', async () => {+ const f = await fresh({ dialOnA: true, envA: { HARNESSD_TEST_FAULTS: 'fleet.sendTurn' } })+ const { a, b } = f+ const dial = f.dial!+ const { onA, onB, agentId } = await linked(f)+ // The dial's send fails at the port, and the dial routes this computer by itself: its own agent's turn runs.+ const onlyA = await boundAgent(a.daemon, onA, 'on-a')+ const started = onA.next(isTurn('turn_started', onlyA), 30_000, 'turn_started 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')+ expect(a.daemon.log()).toContain('[services] fleet.sendTurn failed · injected fault: fleet.sendTurn')+ // ⌘K's own send is another member, and B is still reached through it.+ const startedB = onB.next(isTurn('turn_started', agentId), 30_000, 'turn_started on B')+ expect(await routeSend(onA, agentId, 'cmd-k still reaches b')).toMatchObject({ ok: true })+ expect((await startedB).payload?.userMessage).toBe('cmd-k still reaches b')+ expect(b.daemon.coresStarted()).toBe(1)+ onA.close()+ onB.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']]) {+ for (const [faults, reason] of [['fleet', 'no agent list yet'], ['fleet.routeTask,fleet.routeSend', 'the fleet service is unavailable']]) {const f = await startFleet({ dialOnA: true, envA: { HARNESSD_TEST_FAULTS: faults } })fleet = fonTestFailed(() => { console.log(`---- daemon A log (${faults})\n${f.a.daemon.log().split('\n').slice(-80).join('\n')}`) })@@ -202,7 +222,7 @@ describe('two machines in one fleet', () => {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.log()).toContain(faults === 'fleet' ? '[services] fleet did not start · injected fault: fleet' : '[services] fleet.routeSend failed · injected fault: fleet.routeSend')expect(a.daemon.coresStarted()).toBe(1)onA.close()onB.close()diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.tsindex 8078ea1da..8599571a4 100644--- a/cli/e2e/services.e2e.ts+++ b/cli/e2e/services.e2e.ts@@ -194,7 +194,7 @@ describe('a failing service never takes the core down', () => {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'],+ ['fleet.routeTask,fleet.routeSend', 'the fleet service is unavailable', '[services] fleet.routeSend failed · injected fault: fleet.routeSend'],]) {daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: faults } })const d = daemondiff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.tsindex 5de2de94a..d982d3967 100644--- a/cli/src/cable/cableHost.spec.ts+++ b/cli/src/cable/cableHost.spec.ts@@ -3,6 +3,8 @@ import { describe, expect, it, vi } from 'vitest'import { DaemonCableHost, cableEventFor, type CableHostWiring } from './cableHost.js'import type { FleetMachine, MachineFleet } from './machineFleet.js'+import type { FleetRouting } from '../core/api.js'+import { ServiceUnavailableError } from '../core/serviceHost.js'const AGENTS: Array<{ agentId: string; registeredAt: number; active: boolean; terminalAvailable: boolean; engine: string }> = []vi.mock('../lib/registry.js', () => ({@@ -750,3 +752,143 @@ describe('spoken question capability', () => {expect(answerReviewed).toHaveBeenCalledTimes(1)})})++describe('the dial reaches the fleet through the core\'s port', () => {+ /** The fleet service's routing as the port carries it, every answer scripted. */+ function port(over: Partial<FleetRouting> = {}): FleetRouting {+ return {+ listMachines: vi.fn(async () => ({ machines: [{ id: 'mine', name: 'MacbookPro.local', state: 'ready' as const, local: true }, { id: 'other', name: 'office-imac', state: 'ready' as const, local: false }], source: 'backend' as const })),+ listAgentsFlat: vi.fn(async () => [{ id: 'r1', name: 'api', machineId: 'other', machine: 'office-imac' }]),+ agentTotal: vi.fn(() => 7),+ describe: vi.fn(() => ({ name: 'api', engine: 'claude', machine: 'office-imac' })),+ noteAgent: vi.fn(),+ machineOf: vi.fn(() => 'other'),+ knows: vi.fn(() => true),+ isLocalAgent: vi.fn(() => false),+ sendTurn: vi.fn(() => ({ ok: true as const })),+ lastRouted: vi.fn(() => ({ agentId: 'r1', agoMs: 5 })),+ stopTurn: vi.fn(),+ canSpeakQuestion: vi.fn(() => false),+ answerReviewed: vi.fn(async () => ({ ok: true as const, pending: true })),+ answer: vi.fn(),+ updateAgent: vi.fn(),+ recentSummaries: vi.fn(async () => [{ recap: 'Shipped', text: 'Shipped', ask: 'ship it' }]),+ recentAsks: vi.fn(async () => ['ship it']),+ listModels: vi.fn(async () => ['opus']),+ forkAgent: vi.fn(async () => ({ result: { ok: true as const, agentId: 'r1-fork' }, machineId: 'other', asked: true })),+ hasLane: vi.fn(() => true),+ online: vi.fn(async () => ({ ok: true as const })),+ select: vi.fn(async () => ({ ok: true as const })),+ release: vi.fn(),+ ...over,+ }+ }+ const unavailable = () => new ServiceUnavailableError('fleet')++ it('asks the fleet\'s router for every route, and holds no answer of its own', async () => {+ AGENTS.length = 0+ const fleet = port()+ const w = wiring({ fleet: () => fleet, focused: vi.fn(), opened: vi.fn() })+ const host = new DaemonCableHost(w)+ expect((await host.listMachines()).machines.map((m) => m.id)).toEqual(['mine', 'other'])+ expect((await host.listAgentsFlat()).map((a) => a.id)).toEqual(['r1'])+ expect(host.agentTotal()).toBe(7)+ expect(host.describe('r1')).toEqual({ name: 'api', engine: 'claude', machine: 'office-imac' })+ host.noteAgent('other', 'r9')+ expect(fleet.noteAgent).toHaveBeenCalledWith('other', 'r9')+ expect(host.knows('r1')).toBe(true)+ expect(host.sendTurn('r1', 'ship it')).toEqual({ ok: true })+ expect(fleet.sendTurn).toHaveBeenCalledWith('r1', 'ship it')+ expect(w.sendTurn).not.toHaveBeenCalled()+ expect(host.lastRouted()).toEqual({ agentId: 'r1', agoMs: 5 })+ host.stopTurn('r1'); host.answer('r1', 'q', { k: 'v' }); host.updateAgent('r1', 'opus')+ expect(fleet.stopTurn).toHaveBeenCalledWith('r1')+ expect(fleet.answer).toHaveBeenCalledWith('r1', 'q', { k: 'v' })+ expect(fleet.updateAgent).toHaveBeenCalledWith('r1', 'opus', undefined)+ expect(host.canSpeakQuestion('r1')).toBe(false)+ expect(await host.answerReviewed({ agentId: 'r1', requestId: 'q', questions: [], answers: {}, selections: {} })).toEqual({ ok: true, pending: true })+ expect(await host.recentSummaries('r1')).toEqual([{ recap: 'Shipped', text: 'Shipped', ask: 'ship it' }])+ expect(await host.recentAsks('r1')).toEqual(['ship it'])+ expect(await host.listModels('r1')).toEqual(['opus'])+ // An agent the router places on another machine has no terminal footer here.+ expect(await host.activityText('r1')).toBeNull()+ host.focus('r1')+ expect(w.focused).toHaveBeenCalledWith('other', 'r1')+ expect(await host.forkAgent('r1')).toEqual({ ok: true, agentId: 'r1-fork' })+ expect(w.opened).toHaveBeenCalledWith('other', 'r1-fork')+ expect(w.log).toHaveBeenCalledWith('cable: fork other/r1 → r1-fork')+ })++ it('routes this computer by itself while the fleet is off, or when a call comes back unavailable', async () => {+ AGENTS.length = 0+ AGENTS.push({ agentId: 'local-1', registeredAt: 1, active: true, terminalAvailable: true, engine: 'claude' })+ let fleet: FleetRouting | null = null+ const w = wiring({ fleet: () => fleet })+ const host = new DaemonCableHost(w)+ // Off: this computer alone, as before the fleet was a service.+ expect(await host.listMachines()).toEqual({ machines: [{ id: 'mine', name: 'MacbookPro.local', state: 'ready', local: true }], source: 'signed-out' })+ expect((await host.listAgentsFlat()).map((a) => a.id)).toEqual(['local-1'])+ host.sendTurn('local-1', 'hello')+ expect(w.sendTurn).toHaveBeenCalledWith('local-1', 'hello')+ // On, but failing: a sync call that throws unavailable, an async one that rejects unavailable.+ fleet = port({+ sendTurn: vi.fn(() => { throw unavailable() }),+ listAgentsFlat: vi.fn(async () => { throw unavailable() }),+ })+ expect(host.sendTurn('local-1', 'again')).toEqual({ ok: true })+ expect(w.sendTurn).toHaveBeenLastCalledWith('local-1', 'again')+ expect((await host.listAgentsFlat()).map((a) => a.id)).toEqual(['local-1'])+ })++ it('lets any other failure through, as before: only an unavailable fleet is routed around', async () => {+ const host = new DaemonCableHost(wiring({ fleet: () => port({+ knows: vi.fn(() => { throw new TypeError('a bug') }),+ recentAsks: vi.fn(async () => { throw new Error('a far-end bug') }),+ }) }))+ expect(() => host.knows('r1')).toThrow('a bug')+ await expect(host.recentAsks('r1')).rejects.toThrow('a far-end bug')+ })++ it('holds the lane through the port: opens it, announces where the dial is, says when it will not, and lets go', async () => {+ const fleet = port()+ const log = vi.fn()+ const host = new DaemonCableHost(wiring({ fleet: () => fleet, log }))+ host.onDialAttached()+ await new Promise((r) => setTimeout(r, 0))+ expect(fleet.online).toHaveBeenCalled()+ expect(fleet.select).toHaveBeenCalledWith('mine')+ expect(await host.selectMachine('other')).toEqual({ ok: true })+ expect(host.selectedMachine()).toBe('other')+ fleet.select = vi.fn(async () => ({ ok: false as const, code: 'NEEDS_LINK', message: 'Link office-imac to this computer first' }))+ expect(await host.selectMachine('third')).toEqual({ ok: false, code: 'NEEDS_LINK', message: 'Link office-imac to this computer first' })+ expect(host.selectedMachine()).toBe('other')+ expect(await host.selectMachine('mine')).toEqual({ ok: true })+ expect(fleet.release).toHaveBeenCalledWith()+ await new Promise((r) => setTimeout(r, 0))+ expect(log).toHaveBeenCalledWith('cable: could not announce mine (Link office-imac to this computer first)')+ fleet.online = vi.fn(async () => ({ ok: false as const, message: 'backend unreachable' }))+ host.onDialAttached()+ await new Promise((r) => setTimeout(r, 0))+ expect(log).toHaveBeenCalledWith('cable: could not open the lane (backend unreachable)')+ host.onDialGone()+ expect(fleet.release).toHaveBeenLastCalledWith(true)+ // No lane to hold: nothing is opened, and a remote machine cannot be chosen.+ fleet.hasLane = vi.fn(() => false)+ fleet.online = vi.fn(async () => ({ ok: true as const }))+ host.onDialAttached()+ expect(fleet.online).not.toHaveBeenCalled()+ expect(await host.selectMachine('other')).toMatchObject({ ok: false, code: 'UNAVAILABLE' })+ })++ it('says nothing of a fork that was refused before anyone was asked, and says a refused one that was', async () => {+ const fleet = port({ forkAgent: vi.fn(async () => ({ result: { ok: false as const, error: 'AGENT_NOT_FOUND' }, machineId: '', asked: false })) })+ const w = wiring({ fleet: () => fleet, opened: vi.fn() })+ const host = new DaemonCableHost(w)+ expect(await host.forkAgent('ghost')).toEqual({ ok: false, error: 'AGENT_NOT_FOUND' })+ expect(w.log).not.toHaveBeenCalled()+ fleet.forkAgent = vi.fn(async () => ({ result: { ok: false as const, error: 'FORK_FAILED', detail: 'busy' }, machineId: 'other', asked: true }))+ expect(await host.forkAgent('r1')).toEqual({ ok: false, error: 'FORK_FAILED', detail: 'busy' })+ expect(w.log).toHaveBeenCalledWith('cable: fork other/r1 refused (FORK_FAILED: busy)')+ expect(w.opened).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 3bb05c26d..8e80b8ba6 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -10,9 +10,11 @@// 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.+// (services/fleetRouter.ts), shared with ⌘K and the window's voice route. This host asks it through the+// core's port (`wiring.fleet`), never holding it (step D1): a dial in a process of its own asks the same+// port across the service link. It keeps a router of its own for this computer alone, and uses it+// whenever the fleet cannot answer — off, or its call failed — as the dial did before the fleet was a+// service. Its tests give it a bare fleet to route over by itself.import { join } from 'node:path'import { notificationReadToken, type UnreadNotification } from './notificationRead.js'@@ -21,14 +23,16 @@ import { registry, projectDisplayName, type RegisteredSession } from '../lib/regimport { fetchRelease, loadImage, otaKeyForBoard, shouldOffer } from './fwPush.js'import { routeVoiceTask, type RouterAgent, type RouterContinuity } from '../lib/voiceRouter.js'import { env } from '../config/env.js'-import { FleetRouter, type ForkResult } from '../services/fleetRouter.js'+import { FleetRouter } from '../services/fleetRouter.js'+import type { FleetRouting, ForkResult } from '../core/api.js'+import { ServiceUnavailableError } from '../core/serviceHost.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 MachineFleet } from './machineFleet.js'+import type { MachineFleet } from './machineFleet.js'import type { ReviewedAnswer, AnswerReceipt } from './questionInbox.js'/** One completed turn's recap, as the mirror keeps them. */@@ -92,6 +96,12 @@ export interface CableHostWiring {form?: (command: FormCommand) => Promise<FormResult>clearForm?: () => voidlog: (line: string) => void+ /**+ * Which machine an agent is on, and getting a turn, a stop or an answer there: the fleet service's+ * routing, through the core's port (core/api.ts `FleetRouting`). Read at every call, and null while the+ * fleet is off. Absent, this host routes by itself.+ */+ fleet?: () => FleetRouting | null}/** Whether an id is the router's placeholder for a machine with no id yet (`cable:` and the computer id;@@ -101,11 +111,11 @@ function isPlaceholder(id: string): boolean {}export class DaemonCableHost implements CableHost {- /** 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+ /**+ * This host's own router: over the bare fleet it is given (its tests), or over none, for this computer+ * alone. Asked whenever the fleet service cannot answer — see route.+ */+ private readonly local: FleetRouter/*** The machine whose agents are on the dial right now. Defaults to — and falls back to — the local one:@@ -118,20 +128,39 @@ export class DaemonCableHost implements CableHost {private selected = ''/**- * `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.+ * `fleet` is a bare lane to the other machines for this host's own router — its tests give it one. A+ * daemon gives none: its dial reaches the fleet service's router through the core (`wiring.fleet`).+ * With neither, 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({+ constructor(private readonly wiring: CableHostWiring, fleet?: MachineFleet) {+ this.local = 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+ }++ /**+ * Ask the fleet service's router through the core's port, or this host's own when the fleet is off or+ * its call came back unavailable (a failing port's fallback, core/api.ts FLEET_FALLBACKS). Either way the+ * answer is a router's, refusals included: the dial never reads a made-up answer as the fleet's.+ */+ private viaFleet<T>(ask: (routing: FleetRouting) => T): T {+ const fleet = this.wiring.fleet?.()+ if (!fleet) return ask(this.local)+ const unavailable = (error: unknown): T => {+ if (error instanceof ServiceUnavailableError) return ask(this.local)+ throw error+ }+ let answer: T+ try {+ answer = ask(fleet)+ } catch (error) {+ return unavailable(error)+ }+ return answer instanceof Promise ? answer.catch(unavailable) as T : answer}/** The identity of the computer at the other end of the cable. */@@ -140,7 +169,7 @@ export class DaemonCableHost implements CableHost {}private localId(): string {- return this.router.localId()+ return this.local.localId()}/** Whether the dial is looking at THIS computer. Everything forks on this one question. */@@ -154,7 +183,7 @@ export class DaemonCableHost implements CableHost {/** 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()+ return this.viaFleet((r) => r.listMachines())}async selectMachine(machineId: string): Promise<{ ok: true } | { ok: false; code: string; message: string }> {@@ -163,19 +192,15 @@ export class DaemonCableHost implements CableHost {// Let go of the REMOTE machine after a linger, keeping the socket — then announce where the dial// actually is. `activeMachineId` on the account is then true for this machine too, instead of// silently going stale on whatever was selected last.- this.fleet?.release()+ this.viaFleet((r) => r.release())void this.announceSelection()return { ok: true }}- if (!this.fleet) {+ if (!this.viaFleet((r) => r.hasLane())) {return { ok: false, code: 'UNAVAILABLE', message: 'Sign in on this computer to reach other machines' }}- try {- await this.fleet.select(machineId)- } catch (err) {- if (err instanceof FleetError) return { ok: false, code: err.code, message: err.message }- return { ok: false, code: 'UNREACHABLE', message: (err as Error).message }- }+ const selected = await this.viaFleet((r) => r.select(machineId))+ if (!selected.ok) return selectedthis.selected = machineIdreturn { ok: true }}@@ -189,8 +214,7 @@ export class DaemonCableHost implements CableHost {* it loses the race; a failure marks the machine unreachable rather than pretending it has no agents.*/onDialAttached(): void {- if (!this.fleet) return- const fleet = this.fleet+ if (!this.viaFleet((r) => r.hasLane())) return// Signed out there is no lane to open: the socket is authenticated, so dialling it would fail once// per plug-in and log a failure for something nobody asked for. The dial still works — it is on the// cable, and everything it shows on this computer is served in-process.@@ -202,7 +226,8 @@ export class DaemonCableHost implements CableHost {void (async () => {// The socket first, and unconditionally: it is what makes the machine wheel's dots live, and it is// held for as long as the dial is plugged in whether or not anything is selected.- await fleet.online()+ const online = await this.viaFleet((r) => r.online())+ if (!online.ok) throw new Error(online.message)await this.announceSelection()})().catch((err) => this.wiring.log(`cable: could not open the lane (${(err as Error).message})`))}@@ -217,16 +242,13 @@ export class DaemonCableHost implements CableHost {* Skipped only for the placeholder id, which is not a machineId and means nothing to the backend.*/private async announceSelection(): Promise<void> {- if (!this.fleet) return+ if (!this.viaFleet((r) => r.hasLane())) returnconst machineId = this.selectedMachine()if (isPlaceholder(machineId)) return- try {- await this.fleet.select(machineId)- } catch (err) {- // Never fatal. The local machine in particular must stay usable with no backend at all — it is the- // one machine the cable can vouch for on its own.- this.wiring.log(`cable: could not announce ${machineId} (${(err as Error).message})`)- }+ const selected = await this.viaFleet((r) => r.select(machineId))+ // Never fatal. The local machine in particular must stay usable with no backend at all — it is the+ // one machine the cable can vouch for on its own.+ if (!selected.ok) this.wiring.log(`cable: could not announce ${machineId} (${selected.message})`)}/**@@ -241,7 +263,7 @@ export class DaemonCableHost implements CableHost {this.wiring.clearSelection?.()this.wiring.clearVisit?.()this.wiring.clearForm?.()- this.fleet?.release(true)+ this.viaFleet((r) => r.release(true))}/**@@ -389,13 +411,13 @@ export class DaemonCableHost implements CableHost {this.deskShape = shapethis.wiring.log(`cable: tab ${shape} · ${flat.length} in all`)}- return { agents: out, tab, total: this.router.agentTotal() }+ return { agents: out, tab, total: this.viaFleet((r) => r.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. See the router's agentTotal. */agentTotal(): number {- return this.router.agentTotal()+ return this.viaFleet((r) => r.agentTotal())}/** The active tab's id, or '' with no window. Travels on `agents.end` so the dial can tell an empty@@ -409,17 +431,17 @@ export class DaemonCableHost implements CableHost {* about one the dial no longer holds. See the router's describe.*/describe(agentId: string): { name: string; engine: string; machine: string } | undefined {- return this.router.describe(agentId)+ return this.viaFleet((r) => r.describe(agentId))}async activityText(agentId: string): Promise<string | null> {- if (!this.router.isLocalAgent(agentId)) return null+ if (!this.viaFleet((r) => r.isLocalAgent(agentId))) return nullreturn await this.wiring.activityText?.(agentId) ?? null}/** A card arrived from a machine for an agent — see the router's noteAgent. */noteAgent(machineId: string, agentId: string): void {- this.router.noteAgent(machineId, agentId)+ this.viaFleet((r) => r.noteAgent(machineId, agentId))}/**@@ -428,12 +450,12 @@ export class DaemonCableHost implements CableHost {* re-cut around the tiles the window has open.*/listAgentsFlat(): Promise<CableAgent[]> {- return this.router.listAgentsFlat()+ return this.viaFleet((r) => r.listAgentsFlat())}/** Which machine an agent lives on, or '' — never a guess. See the router's machineOf. */private machineOf(agentId: string): string {- return this.router.machineOf(agentId)+ return this.viaFleet((r) => r.machineOf(agentId))}openAgent(agentId: string, reason?: OpenReason): void {@@ -467,7 +489,8 @@ export class DaemonCableHost implements CableHost {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) => {+ return this.viaFleet((r) => r.forkAgent(agentId)).then(({ result, machineId, asked }) => {+ if (!asked) return resultif (result.ok) {this.wiring.log(`cable: fork ${machineId}/${agentId} → ${result.agentId}`)if (this.wiring.forked) this.wiring.forked(machineId, result.agentId, agentId)@@ -475,12 +498,13 @@ export class DaemonCableHost implements CableHost {} 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.router.knows(agentId)+ return this.viaFleet((r) => r.knows(agentId))}/**@@ -488,28 +512,28 @@ export class DaemonCableHost implements CableHost {* 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 } {- return this.router.sendTurn(agentId, text)+ return this.viaFleet((r) => r.sendTurn(agentId, text))}/** Who the last delivered turn went to, and how long ago — by any of the router's callers. */lastRouted(): RouterContinuity | undefined {- return this.router.lastRouted()+ return this.viaFleet((r) => r.lastRouted())}stopTurn(agentId: string): void {- this.router.stopTurn(agentId)+ this.viaFleet((r) => r.stopTurn(agentId))}canSpeakQuestion(agentId: string): boolean {- return this.router.canSpeakQuestion(agentId)+ return this.viaFleet((r) => r.canSpeakQuestion(agentId))}answerReviewed(answer: ReviewedAnswer): Promise<AnswerReceipt> {- return this.router.answerReviewed(answer)+ return this.viaFleet((r) => r.answerReviewed(answer))}answer(agentId: string, requestId: string, answers: Record<string, string>): void {- this.router.answer(agentId, requestId, answers)+ this.viaFleet((r) => r.answer(agentId, requestId, answers))}@@ -568,21 +592,21 @@ export class DaemonCableHost implements CableHost {}updateAgent(agentId: string, model?: string, effort?: string): void {- this.router.updateAgent(agentId, model, effort)+ this.viaFleet((r) => r.updateAgent(agentId, model, effort))}/** 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)+ return this.viaFleet((r) => r.recentSummaries(agentId))}/** 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)+ return this.viaFleet((r) => r.recentAsks(agentId))}listModels(agentId: string): Promise<string[]> {- return this.router.listModels(agentId)+ return this.viaFleet((r) => r.listModels(agentId))}/**diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 83a361164..ffadbad38 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -179,7 +179,6 @@ 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'@@ -3148,7 +3147,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// 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 = ports.fleet?.sendTurn(agentId, text) ?? { ok: false as const, machine: '', reason: 'no agent list yet' }+ const sent = ports.fleet?.routeSend(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@@ -3884,9 +3883,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// 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, {+ 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(),@@ -3960,7 +3958,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {form: command => windowForm.command(command),clearForm: () => windowForm.clear(),log: (line) => console.log(`[cable] ${line}`),- }, fleetService.router)+ // Which machine an agent is on, and getting there: the fleet's router, through its port (D1).+ fleet: () => ports.fleet,+ })cableHostRef = cableHostbackend.harnessDevices = {status: () => cableHost.currentDialStatus(),@@ -4080,7 +4080,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// event kind lands on both surfaces the day it lands on either.// 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) => {+ ports.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.diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 4aec5c165..1936025b9 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -1,6 +1,7 @@import { describe, expect, it, vi } from 'vitest'import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'import { createCoreApi, emptyPorts, FLEET_FALLBACKS, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'+import { FAIL } from './serviceHost.js'const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession@@ -65,8 +66,18 @@ describe('the core API services stand on', () => {})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.routeSend).toEqual({ ok: false, machine: '', reason: 'the fleet service is unavailable' })expect(FLEET_FALLBACKS.stop).toBeUndefined()+ // No cards, and nothing to stop hearing.+ expect((FLEET_FALLBACKS.onEvent as () => void)()).toBeUndefined()+ })++ it('fails the dial\'s routing, when the fleet fails, rather than making an answer up', () => {+ // The dial routes this computer by itself then (cable/cableHost.ts): a made-up answer read as the+ // fleet's would send a turn nowhere and say it went.+ for (const member of ['agentTotal', 'describe', 'machineOf', 'knows', 'isLocalAgent', 'sendTurn', 'hasLane', 'release'] as const) {+ expect(FLEET_FALLBACKS[member], member).toBe(FAIL)+ }})it('falls back, when the teams fail, to an undo that has nothing to undo', () => {diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex ed4793375..8fccc4762 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -11,13 +11,16 @@* 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 { CableAgent, CableMachine, CableMachineSource } from '../cable/cableSession.js'+import type { FleetEvent } from '../cable/machineFleet.js'+import type { AnswerReceipt, 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'import type { LiveEvent } from '../lib/normalize.js'import { projectDisplayName, type registry, type RegisteredSession } from '../lib/registry.js'import type { RuntimeModelOption } from '../lib/runtimeProfile.js'+import type { RouterContinuity } from '../lib/voiceRouter.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'@@ -212,23 +215,78 @@ export type TeamsEvent = { seq: number; core: string; at: number; agentId: strin| { kind: 'replied'; teamId: string; questionId: 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 }+/** 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 }+/** A fork and where it was asked: `asked` is false for a refusal made before asking anyone (an agent+ * never listed, a daemon or a fleet that cannot fork), which nobody needs to hear about. */+export interface ForkOutcome { result: ForkResult; machineId: string; asked: boolean }+/** A machine selected for the dial, or the refusal a person can act on. */+export type SelectResult = { ok: true } | { ok: false; code: string; message: string }++/**+ * Which machine an agent is on, and a turn, a stop or an answer reaching it there: the fleet's router+ * (services/fleetRouter.ts), as the dial asks it. Also the lane to the other machines, which the dial+ * holds while it is plugged in. A refusal is an answer here, never a throw: through the port, a throw is+ * a failure of the fleet service, and counts toward switching it off.+ */+export interface FleetRouting {+ listMachines(): Promise<{ machines: CableMachine[]; source: CableMachineSource }>+ listAgentsFlat(): Promise<CableAgent[]>+ agentTotal(): number+ describe(agentId: string): { name: string; engine: string; machine: string } | undefined+ noteAgent(machineId: string, agentId: string): void+ machineOf(agentId: string): string+ knows(agentId: string): boolean+ isLocalAgent(agentId: string): boolean+ sendTurn(agentId: string, text: string): SendResult+ lastRouted(): RouterContinuity | undefined+ stopTurn(agentId: string): void+ canSpeakQuestion(agentId: string): boolean+ answerReviewed(answer: ReviewedAnswer): Promise<AnswerReceipt>+ answer(agentId: string, requestId: string, answers: Record<string, string>): void+ updateAgent(agentId: string, model?: string, effort?: string): void+ recentSummaries(agentId: string): Promise<Array<{ recap: string; text: string; ask: string }>>+ recentAsks(agentId: string): Promise<string[]>+ listModels(agentId: string): Promise<string[]>+ forkAgent(agentId: string): Promise<ForkOutcome>+ /** Whether a lane to the other machines exists: signed in, with the fleet's own fleet. */+ hasLane(): boolean+ /** Hold the lane for a dial, attached to no machine. Resolves with how it went; never rejects. */+ online(): Promise<{ ok: true } | { ok: false; message: string }>+ select(machineId: string): Promise<SelectResult>+ release(immediate?: boolean): void+}+/** 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 {+ * the owner's machines, and delivering it to that agent's own machine — the routing the dial asks of+ * it, the cards the other machines send, and stopping the lane to them for a shutdown. */+export interface FleetPort extends FleetRouting {routeTask(text: string): Promise<RouteAnswer>- sendTurn(agentId: string, text: string): { ok: true } | { ok: false; machine: string; reason: string }+ routeSend(agentId: string, text: string): SendResult+ /** The other machines' cards, for the dial. Returns how to stop hearing them. */+ onEvent(listener: (event: FleetEvent) => void): () => voidstop(): 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. */+/**+ * What the core gets when the fleet fails. ⌘K says so, picking no agent and sending nothing; a shutdown+ * goes on; the cards stop. The dial's routing FAILs: the dial routes this computer by itself then, as it+ * does with the fleet off (cable/cableHost.ts), rather than reading a made-up answer as the fleet's.+ */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 },+ routeSend: { ok: false, machine: '', reason: FLEET_UNAVAILABLE },+ onEvent: () => {},stop: undefined,+ listMachines: later(FAIL), listAgentsFlat: later(FAIL), agentTotal: FAIL, describe: FAIL, noteAgent: FAIL,+ machineOf: FAIL, knows: FAIL, isLocalAgent: FAIL, sendTurn: FAIL, lastRouted: FAIL, stopTurn: FAIL,+ canSpeakQuestion: FAIL, answerReviewed: later(FAIL), answer: FAIL, updateAgent: FAIL, recentSummaries: later(FAIL),+ recentAsks: later(FAIL), listModels: later(FAIL), forkAgent: later(FAIL), hasLane: FAIL, online: later(FAIL),+ select: later(FAIL), release: FAIL,}/** Each port is filled by the service that owns it when that service starts, and is null while thediff --git a/cli/src/services/fleet.spec.ts b/cli/src/services/fleet.spec.tsindex f36ba957b..3b87e7f59 100644--- a/cli/src/services/fleet.spec.ts+++ b/cli/src/services/fleet.spec.ts@@ -20,6 +20,9 @@ const lane = vi.hoisted(() => ({stop: vi.fn(),rpc: vi.fn(async (_type: string): Promise<Record<string, unknown>> => ({})),sendSealed: vi.fn(async () => {}),+ online: vi.fn(async () => {}),+ attach: vi.fn(async (_machineId: string) => {}),+ release: vi.fn(),peers: new Map<string, { pub: string }>(),}))vi.mock('../device/deviceLink.js', () => ({@@ -30,6 +33,9 @@ vi.mock('../device/deviceLink.js', () => ({stop() { lane.stop() }rpc(type: string) { return lane.rpc(type) }sendSealed(...args: unknown[]) { return lane.sendSealed(...(args as [])) }+ online() { return lane.online() }+ attach(machineId: string) { return lane.attach(machineId) }+ release() { lane.release() }resetSession() { return false }},}))@@ -174,30 +180,70 @@ describe('this computer’s side of every route', () => {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([+ // Asked as the dial asks it: through the port, the router's own answers.+ const { fleet } = setup({ desk: () => ['a1'] }, core)+ expect(await fleet.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(fleet.routeSend('a1', 'from cmd-k')).toEqual({ ok: true })+ expect(core.turns.send).toHaveBeenLastCalledWith('a1', 'from cmd-k')+ fleet.stopTurn('a1')expect(core.turns.stop).toHaveBeenCalledWith('a1')- router.answer('a1', 'q', { scope: 'File' })+ fleet.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(await fleet.answerReviewed(reviewed)).toEqual({ ok: true })expect(core.questions.answerReviewed).toHaveBeenCalledWith(reviewed)- expect(await router.recentSummaries('a1')).toEqual([{ recap: 'Done', text: 'Done', ask: '' }])+ expect(await fleet.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(await fleet.recentAsks('a1')).toEqual(['what next?'])+ fleet.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(await fleet.listModels('a1')).toEqual(['opus'])+ expect(await fleet.forkAgent('a1')).toEqual({ result: { ok: true, agentId: 'a1-fork' }, machineId: 'mine', asked: true })expect(core.agents.fork).toHaveBeenCalledWith('a1')})})+describe('what the dial asks through the port', () => {+ it('is the router\'s: its machines, what it knows of an agent, the person\'s last turn, and the lane', async () => {+ const core = fakeCore({ agents: { advertised: vi.fn(() => [session('a1')]), displayName: vi.fn(() => 'api') } })+ const { fleet } = setup({}, core)+ const { machines, source } = await fleet.listMachines()+ expect(source).toBe('backend')+ expect(machines.map((m) => m.id)).toEqual(['mine', 'other'])+ await fleet.listAgentsFlat()+ expect(fleet.agentTotal()).toBe(1)+ expect(fleet.describe('a1')).toEqual({ name: 'api', engine: 'claude', machine: 'MacbookPro.local' })+ fleet.noteAgent('other', 'r9')+ expect(fleet.machineOf('r9')).toBe('other')+ expect(fleet.knows('a1')).toBe(true)+ expect(fleet.isLocalAgent('r9')).toBe(false)+ expect(fleet.canSpeakQuestion('a1')).toBe(true)+ expect(fleet.lastRouted()).toBeUndefined()+ fleet.sendTurn('a1', 'hello')+ expect(fleet.lastRouted()).toMatchObject({ agentId: 'a1' })+ // The lane: there while signed in, held for a dial, and let go of.+ expect(fleet.hasLane()).toBe(true)+ expect(await fleet.online()).toEqual({ ok: true })+ expect(await fleet.select('other')).toEqual({ ok: true })+ fleet.release(true)+ expect(lane.release).toHaveBeenCalled()+ })++ it('carries the other machines\' cards to whoever listens, until they stop', () => {+ const { fleet } = setup()+ const heard: unknown[] = []+ const stop = fleet.onEvent((event) => heard.push(event))+ lane.frames!({ type: 'commander_event', machineId: 'other', agentId: 'r1', payload: { kind: 'done' } })+ stop()+ lane.frames!({ type: 'commander_event', machineId: 'other', agentId: 'r1', payload: { kind: 'done' } })+ expect(heard).toEqual([{ machineId: 'other', kind: 'done', agentId: 'r1', text: '', recap: '' }])+ })+})+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({diff --git a/cli/src/services/fleet.ts b/cli/src/services/fleet.tsindex f72e0ba32..e4bcf4e1e 100644--- a/cli/src/services/fleet.ts+++ b/cli/src/services/fleet.ts@@ -5,9 +5,9 @@* 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).+ * window's voice route reached another machine only through the dial. ⌘K, the voice route and the dial+ * all reach it through its port now (`ports.fleet`), and none holds the router itself (steps D0 and D1):+ * a dial that moves into a process of its own asks the same port through the core.** A service on the core boundary: it reads the core only through `CoreApi`, and the core reaches it* only through `ports.fleet`.@@ -65,7 +65,8 @@ export interface FleetDeps {identity: Identity}-/** Start the fleet: its port for ⌘K, and the router, which the dial's host is handed. */+/** Start the fleet: its port, through which ⌘K and the dial reach the router. The router itself is+ * returned for this service's own tests; nothing else holds it. */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@@ -132,8 +133,35 @@ export function startFleet(core: CoreApi, ports: CorePorts, deps: FleetDeps): Fl// 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 = {+ // ⌘K's two requests.routeTask: (text) => routeTask(router, text),+ routeSend: (agentId, text) => router.sendTurn(agentId, text),+ // What the dial asks: the router's own answers, through the core's port (step D1).+ listMachines: () => router.listMachines(),+ listAgentsFlat: () => router.listAgentsFlat(),+ agentTotal: () => router.agentTotal(),+ describe: (agentId) => router.describe(agentId),+ noteAgent: (machineId, agentId) => router.noteAgent(machineId, agentId),+ machineOf: (agentId) => router.machineOf(agentId),+ knows: (agentId) => router.knows(agentId),+ isLocalAgent: (agentId) => router.isLocalAgent(agentId),sendTurn: (agentId, text) => router.sendTurn(agentId, text),+ lastRouted: () => router.lastRouted(),+ stopTurn: (agentId) => router.stopTurn(agentId),+ canSpeakQuestion: (agentId) => router.canSpeakQuestion(agentId),+ answerReviewed: (answer) => router.answerReviewed(answer),+ answer: (agentId, requestId, answers) => router.answer(agentId, requestId, answers),+ updateAgent: (agentId, model, effort) => router.updateAgent(agentId, model, effort),+ recentSummaries: (agentId) => router.recentSummaries(agentId),+ recentAsks: (agentId) => router.recentAsks(agentId),+ listModels: (agentId) => router.listModels(agentId),+ forkAgent: (agentId) => router.forkAgent(agentId),+ hasLane: () => router.hasLane(),+ online: () => router.online(),+ select: (machineId) => router.select(machineId),+ release: (immediate) => router.release(immediate),+ // The other machines' cards, for the dial's screen. The router notes their machines itself, above.+ onEvent: (listener) => devices.onEvent(listener),stop: () => {clearInterval(machineListTimer)link.stop()diff --git a/cli/src/services/fleetRouter.spec.ts b/cli/src/services/fleetRouter.spec.tsindex cb7cca9a7..82c59ce4d 100644--- a/cli/src/services/fleetRouter.spec.ts+++ b/cli/src/services/fleetRouter.spec.ts@@ -2,7 +2,7 @@// 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 { FleetError, type FleetMachine, type 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'@@ -335,28 +335,24 @@ describe('a turn, delivered and said so', () => {})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 () => {+ it('forks a local agent through the daemon, notes the fork here, and says which machine was asked', 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(await router.forkAgent('a1')).toEqual({ result: { ok: true, agentId: 'a1-fork' }, machineId: 'mine', asked: true })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' })+ expect(await router.forkAgent('a1')).toEqual({ result: { ok: false, error: 'BUSY' }, machineId: 'mine', asked: true })})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' })+ expect(await router.forkAgent('ghost')).toMatchObject({ result: { ok: false, error: 'AGENT_NOT_FOUND' }, machineId: '', asked: false })+ expect(await router.forkAgent('a1')).toMatchObject({ result: { ok: false, error: 'UNSUPPORTED' }, machineId: 'mine', asked: false })// 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()+ expect(await router.forkAgent('r1')).toEqual({ result: { ok: false, error: 'UNSUPPORTED_ON_REMOTE' }, machineId: 'other', asked: false })})it('forks a remote agent on its machine, and reports the far end’s refusal', async () => {@@ -364,9 +360,41 @@ describe('a fork, on the agent’s own machine', () => {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(await router.forkAgent('r1')).toEqual({ result: { ok: true, agentId: 'r1-fork' }, machineId: 'other', asked: true })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' })+ expect((await router.forkAgent('r2')).result).toEqual({ ok: false, error: 'FORK_FAILED', detail: 'r2 is in the middle of a turn' })+ })+})++describe('the lane, held while a dial is plugged in', () => {+ it('is there only with a fleet, and comes online, selects and lets go through it', async () => {+ expect(new FleetRouter(localOf()).hasLane()).toBe(false)+ // Nothing to let go of without one.+ new FleetRouter(localOf()).release(true)+ const fleet = fleetOf([REMOTE])+ fleet.online = vi.fn(async () => {})+ fleet.select = vi.fn(async () => {})+ const router = new FleetRouter(localOf(), fleet)+ expect(router.hasLane()).toBe(true)+ expect(await router.online()).toEqual({ ok: true })+ expect(await router.select('other')).toEqual({ ok: true })+ expect(fleet.select).toHaveBeenCalledWith('other')+ router.release(true)+ router.release()+ expect((fleet.release as ReturnType<typeof vi.fn>).mock.calls).toEqual([[true], [undefined]])+ })++ it('answers a lane that will not open and a refused selection, rather than throwing them', async () => {+ const fleet = fleetOf([REMOTE])+ fleet.online = vi.fn(async () => { throw new Error('backend unreachable') })+ fleet.select = vi.fn(async (machineId: string) => {+ if (machineId === 'other') throw new FleetError('NEEDS_LINK', 'Link office-imac to this computer first')+ throw new Error('socket closed')+ })+ const router = new FleetRouter(localOf(), fleet)+ expect(await router.online()).toEqual({ ok: false, message: 'backend unreachable' })+ expect(await router.select('other')).toEqual({ ok: false, code: 'NEEDS_LINK', message: 'Link office-imac to this computer first' })+ expect(await router.select('third')).toEqual({ ok: false, code: 'UNREACHABLE', message: 'socket closed' })})})diff --git a/cli/src/services/fleetRouter.ts b/cli/src/services/fleetRouter.tsindex cd51609bb..bce3882eb 100644--- a/cli/src/services/fleetRouter.ts+++ b/cli/src/services/fleetRouter.ts@@ -12,19 +12,16 @@* fleet (its tests, and a daemon whose fleet service is off) without loading the cloud socket and the* E2EE stores the service starts.*/+import type { FleetRouting, ForkOutcome, ForkResult, SelectResult, SendResult } from '../core/api.js'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 { FleetError, type FleetMachine, type 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 }+export type { ForkResult, SendResult }/*** This computer, as the router needs it: its identity, its agents, the window's tiles, and the doors a@@ -95,7 +92,7 @@ function chipsFromProfile(profile: string | null | undefined): { model?: string;return { model: model || undefined, effort: effort || undefined }}-export class FleetRouter {+export class FleetRouter implements FleetRouting {/** 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 }@@ -311,19 +308,20 @@ export class FleetRouter {/*** 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.+ * that machine at once, so the open that follows lands before any list has named it. The outcome says+ * which machine was asked, and whether anyone was: a refusal before asking (an agent never listed, a+ * daemon or a fleet that cannot fork) is only an answer.*/- async forkAgent(agentId: string, attempted?: (machineId: string, result: ForkResult) => void): Promise<ForkResult> {+ async forkAgent(agentId: string): Promise<ForkOutcome> {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.' }+ const refused = (result: ForkResult): ForkOutcome => ({ result, machineId, asked: false })+ if (!machineId) return refused({ ok: false, error: 'AGENT_NOT_FOUND', detail: 'The dial named an agent this daemon has never listed.' })let result: ForkResultif (this.isLocalAgent(agentId)) {- if (!this.local.forkAgent) return { ok: false, error: 'UNSUPPORTED', detail: 'This daemon cannot fork agents.' }+ if (!this.local.forkAgent) return refused({ 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' }+ if (!this.fleet?.forkAgent) return refused({ ok: false, error: 'UNSUPPORTED_ON_REMOTE' })try {result = { ok: true, agentId: await this.fleet.forkAgent(machineId, agentId) }} catch (err) {@@ -331,8 +329,41 @@ export class FleetRouter {}}if (result.ok) this.seenOn.set(result.agentId, machineId)- attempted?.(machineId, result)- return result+ return { result, machineId, asked: true }+ }++ // ── the lane, held while a dial is plugged in ───────────────────────────────────────────────────++ hasLane(): boolean {+ return !!this.fleet+ }++ /** Come online for a dial — see MachineFleet.online. A lane that will not open is an answer: the dial+ * says so in its log and carries on with this computer. */+ async online(): Promise<{ ok: true } | { ok: false; message: string }> {+ try {+ await this.fleet!.online()+ return { ok: true }+ } catch (err) {+ return { ok: false, message: (err as Error).message }+ }+ }++ /** Attach to a machine, which is also how the backend learns where the dial is. A refusal comes back with+ * the code the dial acts on and the words it shows; anything else unexpected reads as unreachable. */+ async select(machineId: string): Promise<SelectResult> {+ try {+ await this.fleet!.select(machineId)+ return { ok: true }+ } catch (err) {+ if (err instanceof FleetError) return { ok: false, code: err.code, message: err.message }+ return { ok: false, code: 'UNREACHABLE', message: (err as Error).message }+ }+ }++ /** Let go of what `select` acquired; `immediate` when the dial is gone — see MachineFleet.release. */+ release(immediate?: boolean): void {+ this.fleet?.release(immediate)}/**diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex f10d3faf5..f6e3b7dfc 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -247,13 +247,30 @@ The steps, each a pull request with its end-to-end proof:this computer's agents alone and never sees another machine's, so cross-machine ⌘K works today onlywith a dial plugged in. Opening the lane for ⌘K changes what the backend counts as a commanderwatching 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,- status and stop. The dial reaches the core through `CoreApi`: activity text, recent turns, sending- and stopping a turn, answering, the runtime profile and models, fork, the window frames (`dial_*`)- and the window bridges.-- **D2, the dial in its own process.** The serial ports belong to `harness __service dial`; the+- **D1, the dial behind the boundary, in process.** Its first part is done: the dial reaches the+ fleet's router through the core's port, never holding it. `ports.fleet` carries the router's whole+ routing contract (`FleetRouting`, `core/api.ts`): the agent lists, which machine an agent is on, the+ turn, stop, answer, model switch, recap and fork sent there, the person's last turn, and the lane+ (`hasLane`, `online`, `select`, `release`). The host reads the port at every call. It keeps a router+ of its own for this computer and asks it when the fleet cannot answer (off, or the call failed):+ the routing members FAIL rather than make an answer up. Refusals are answers, not throws, so they+ do not count against the fleet. ⌘K's send is `routeSend`; the dial hears remote cards through the+ port too. Still to do in D1: `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, status and stop. The dial reaches the core through `CoreApi`: activity text,+ recent turns, sending and stopping a turn, answering, the runtime profile and models, fork, the+ window frames (`dial_*`) and the window bridges.+- **D2, the dial in its own process.** Sized on 2026-10-05 against the viewers' process (#775): it+ is several times larger. Viewers cross the link in about five calls; the dial needs about fifteen+ from the core (the desk, swarms, unread, focus, seen, settings, status, the six kinds of turn and+ question card teed to it, the remote cards) and about twenty-five back (the local doors, seven+ window frames, seven window bridges that wait on a person, and the routing). About ten routing+ reads are synchronous today (which machine an agent is on, whether it is known, who it is, a+ send's answer, whether it can speak a question, the total, the lane), read by the session while it+ builds a frame. Over a socket they need a mirror the core keeps current, or the session made+ asynchronous where it reads them; the window's `dial_status` at handshake needs the same. The+ Wi-Fi device borrows the dial's focus walk and scroll, which would cross too. The serial ports belong to `harness __service dial`; thesame handlers answer. A crash in the native serial code then costs the dial alone, and the masterstarts it again. It is proven end to end with a fake dial on a pseudo-terminal, speaking the cableprotocol (the fake dial and the two-machine fleet from D0's proof are there to reuse).