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
Devices behind one port: the dial, its window bridges and the fleet as one service, still in the core's process (step 9, D1) (#918)
Deed86955364aad
diff --git a/cli/e2e/compat.e2e.ts b/cli/e2e/compat.e2e.tsindex 9e591a749..608bddf85 100644--- a/cli/e2e/compat.e2e.ts+++ b/cli/e2e/compat.e2e.ts@@ -101,6 +101,9 @@ function shape(frames: Frame[]): string[] {// When the activity is announced is timing, not an answer: one run's sequence had an extra// agent_activity before turn_started, or after turn_summary, on either build.if (frame.type === 'agent_activity') continue+ // A heartbeat comes every few seconds of an open turn: whether a question's turn lasts long enough for+ // one is timing too. Under load one run's question had an extra turn_heartbeat, on either build.+ if (frame.type === 'turn_heartbeat') continueconst keys = Object.keys(frame.payload ?? {}).sort().join(',')const line = `${frame.type} {${keys}}`if (out.at(-1) !== line) out.push(line)diff --git a/cli/e2e/deviceCompat.e2e.ts b/cli/e2e/deviceCompat.e2e.tsnew file mode 100644index 000000000..1dde3a70d--- /dev/null+++ b/cli/e2e/deviceCompat.e2e.ts@@ -0,0 +1,175 @@+/**+ * What the dial and the windows hear of the devices, compared with another build's. The dial's firmware+ * and hn's dial.rs were written against the frames a released daemon sends, and the devices moving out of+ * the core (docs/design/2026-10-06-core-boundary-next.md, step 9) must not change one of them. A daemon of+ * that build (`COMPAT_FROM`, its bundled `cli.js`) and one of this checkout's bundle run the same scenario+ * with a fake dial on a pseudo-terminal (harness/fakeDial.ts) and a window on the local socket: the dial+ * greets; the window opens a tab with an agent on it; a turn runs; the dial focuses, opens, scrolls,+ * picks the tab, sends a turn, answers a question and forks; the window lists the devices.+ *+ * Every frame the dial heard (but its keepalive) and every frame of the devices' a window heard (`dial_*`,+ * `harness_devices_changed`) is compared by type and by shape: the keys of each, all the way down, once+ * ids, times and counters are made comparable. A type or a key on one side and not the other is a+ * difference; one listed in CHANGED is on purpose, with why.+ *+ * Skipped unless COMPAT_FROM names a bundle, as e2e/compat.e2e.ts is. `COMPAT_REPORT=<file>` writes both+ * sides, for reading.+ */+import { mkdirSync, writeFileSync } 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 { IsolatedDaemon, until } from './harness/daemon.js'+import { FakeDial, type DialMessage } from './harness/fakeDial.js'++const FROM = process.env.COMPAT_FROM++/** Types or shapes that differ on purpose, each with why. */+const CHANGED: Record<string, string> = {}++/** Types that one run may hear and the other not, by timing alone, each with why. */+const TIMING: Record<string, string> = {+ // The working card's activity line is read from the pane's footer while a turn runs: a fast fake turn+ // can end before the first read.+ 'dial turn.activity': 'read from the pane while a turn runs; a fast turn can end first',+ // A summary's recap is cut when the turn ends; the dial redraws the tile from it when it lands.+ 'dial notif.replace': 'the drawer is replaced when the window says what is unread, which is timing',+ // The dial's own focus, said back to it when its session re-asserts the tile it wants in front: whether+ // that lands before the scenario ends is timing, in every build.+ 'dial focus': 'the dial\'s own focus said back as its session re-asserts it, which is timing',+}++/** A value's shape: its keys, all the way down; arrays as the shapes of their items. */+function shape(value: unknown): unknown {+ if (Array.isArray(value)) return [...new Set(value.map((item) => JSON.stringify(shape(item))))].sort()+ if (value && typeof value === 'object') {+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, shape((value as Record<string, unknown>)[key])]))+ }+ return typeof value+}++interface Heard {+ /** By `dial <t>` or `window <type>`: every shape it came in. */+ shapes: Map<string, Set<string>>+ /** What the scenario checked by value, as it found it. */+ values: Record<string, unknown>+}++function hear(into: Heard, key: string, value: unknown): void {+ const shapes = into.shapes.get(key) ?? new Set<string>()+ shapes.add(JSON.stringify(shape(value)))+ into.shapes.set(key, shapes)+}++/** One build's daemon, a dial and a window through the scenario; what both heard. */+async function scenario(scriptPath: string | undefined, label: string): Promise<Heard> {+ const dial = await FakeDial.open()+ const daemon = await IsolatedDaemon.create({ ...(scriptPath ? { scriptPath } : {}), env: { CABLE_DISABLE: 'false', HARNESSD_TEST_DIAL_PORT: dial.path } })+ onTestFailed(() => { console.log(`---- ${label} daemon log\n${daemon.log().split('\n').slice(-120).join('\n')}\n---- the dial heard\n${dial.messages.map((m) => m.t).join(' ')}`) })+ const heard: Heard = { shapes: new Map(), values: {} }+ try {+ await daemon.start()+ const window = await LocalClient.connect(daemon)+ const cwd = join(daemon.projectsDir, 'dial-compat')+ mkdirSync(cwd, { recursive: true })+ const created = await window.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 60_000)+ const agentId: string = created.agent.id+ await until('the agent to bind', async () => ((await window.request('agents_list', {})).agents as Array<Record<string, unknown>>)+ .find((agent) => agent.id === agentId)?.sessionId || null, 45_000, 500)+ // The window opens a tab with the agent on it, as the desktop does on every change.+ window.send('app_swarms', { active: 't1', swarms: [{ id: 't1', name: 'Tab', agentIds: [agentId], panes: 1 }, { id: 't2', name: 'Other', agentIds: [], panes: 0 }], tiles: [] })+ window.send('app_panes', { agentIds: [agentId], foreground: true })+ await dial.greet()+ await dial.next((m) => m.t === 'agents.end', 30_000, 'the agent list')+ // A turn from the window: the dial is told it started and ended, and its recap.+ window.send('message', { agentId, content: 'hello dial' })+ await dial.next((m) => m.t === 'summary' && m.agentId === agentId, 45_000, 'the turn\'s summary')+ // What a hand on the dial does, as the window hears it.+ dial.send({ t: 'focus', agentId })+ await window.waitFor((f) => f.type === 'dial_focus', 15_000, 'dial_focus')+ dial.send({ t: 'agent.open', agentId })+ await window.waitFor((f) => f.type === 'dial_open', 15_000, 'dial_open')+ dial.send({ t: 'scroll', phase: 'down', dy: 0, v: 0 })+ dial.send({ t: 'scroll', phase: 'up', dy: 0, v: 0 })+ await window.waitFor((f) => f.type === 'dial_scroll' && f.payload?.phase === 'up', 15_000, 'dial_scroll')+ dial.send({ t: 'swarm.select', swarmId: 't2' })+ await window.waitFor((f) => f.type === 'dial_swarm', 15_000, 'dial_swarm')+ dial.send({ t: 'machines.list' })+ dial.send({ t: 'swarms.list' })+ await dial.next((m) => m.t === 'machines.end', 15_000, 'the machine list')+ // A turn from the dial runs in the agent's pane.+ const since = window.frames.length+ dial.send({ t: 'turn.send', agentId, text: 'from the dial' })+ await window.waitFor((f) => f.type === 'turn_started' && f.agentId === agentId && f.payload?.userMessage === 'from the dial', 30_000, 'the dial\'s turn', since)+ await dial.next((m) => m.t === 'turn.done' && m.agentId === agentId, 45_000, 'the dial\'s turn ending', dial.messages.length - 1)+ // A question, answered on the dial.+ const asked = dial.messages.length+ window.send('message', { agentId, content: '!ask' })+ const question = await dial.next((m) => m.t === 'question' && m.agentId === agentId, 45_000, 'the question', asked)+ const q = (question.questions as Array<{ q: string; options: unknown[] }>)[0]+ dial.send({ t: 'question.read', agentId, requestId: 'read-1' })+ await dial.next((m) => m.t === 'question.state', 15_000, 'the question\'s state', asked)+ dial.send({ t: 'answer', agentId, requestId: question.id ?? question.requestId, answers: { [q.q]: 'Coffee' } })+ await dial.next((m) => m.t === 'question.close' && m.agentId === agentId, 45_000, 'the question closing', asked)+ // A fork from the dial: the window is told where it is.+ dial.send({ t: 'agent.fork', agentId })+ await window.waitFor((f) => f.type === 'dial_forked', 60_000, 'dial_forked')+ // The Devices tab.+ const listed = await window.request('harness_devices_list', {})+ hear(heard, 'reply harness_devices_list', { ...listed, requestId: 'r' })+ heard.values.devices = { protocol: listed.protocol, attached: listed.status?.attached, devices: (listed.status?.devices as unknown[] | undefined)?.length }+ // A window that connects now is told the dial is there.+ const late = await LocalClient.connect(daemon)+ const status = await late.waitFor((f) => f.type === 'dial_status', 15_000, 'dial_status at connect')+ heard.values.lateStatus = { attached: status.payload?.attached, fw: status.payload?.fw }+ late.close()+ await new Promise((resolve) => setTimeout(resolve, 1_500))+ for (const message of dial.messages as DialMessage[]) {+ if (message.t === 'ping') continue+ hear(heard, `dial ${message.t}`, message)+ }+ for (const frame of window.frames as Frame[]) {+ if (!frame.type.startsWith('dial_') && frame.type !== 'harness_devices_changed' && frame.type !== 'voice_route_request') continue+ hear(heard, `window ${frame.type}`, frame)+ }+ heard.values.welcome = { product: dial.messages.find((m) => m.t === 'welcome')?.product }+ heard.values.open = window.frames.find((f) => f.type === 'dial_open')?.payload+ heard.values.focus = window.frames.find((f) => f.type === 'dial_focus')?.payload+ heard.values.swarm = window.frames.find((f) => f.type === 'dial_swarm')?.payload+ window.close()+ for (const value of [heard.values.open, heard.values.focus] as Array<Record<string, unknown> | undefined>) {+ if (value?.agentId === agentId) value.agentId = 'AGENT'+ if (value?.machineId) value.machineId = 'MACHINE'+ }+ return heard+ } finally {+ await daemon.close()+ await dial.close()+ }+}++describe.skipIf(!FROM)('the devices\' frames, against another build\'s', () => {+ afterEach(() => {})++ it('the dial and the windows hear the same frames, in the same shapes', async () => {+ const before = await scenario(FROM, 'released')+ const after = await scenario(process.env.E2E_BUNDLE_PATH, 'this build')+ if (process.env.COMPAT_REPORT) {+ const side = (heard: Heard) => ({ shapes: Object.fromEntries([...heard.shapes].map(([key, set]) => [key, [...set].map((s) => JSON.parse(s))])), values: heard.values })+ writeFileSync(process.env.COMPAT_REPORT, JSON.stringify({ before: side(before), after: side(after) }, null, 2))+ }+ const differences: string[] = []+ for (const key of new Set([...before.shapes.keys(), ...after.shapes.keys()])) {+ if (CHANGED[key] || TIMING[key]) continue+ const was = before.shapes.get(key)+ const is = after.shapes.get(key)+ if (!was) { differences.push(`${key}: only in this build`); continue }+ if (!is) { differences.push(`${key}: not in this build`); continue }+ const lost = [...was].filter((s) => !is.has(s))+ const added = [...is].filter((s) => !was.has(s))+ if (lost.length || added.length) differences.push(`${key}: shapes ${JSON.stringify({ lost, added })}`)+ }+ expect(differences).toEqual([])+ expect(after.values).toEqual(before.values)+ })+})diff --git a/cli/e2e/fleet.e2e.ts b/cli/e2e/fleet.e2e.tsindex 3461af76f..e7fff10f5 100644--- a/cli/e2e/fleet.e2e.ts+++ b/cli/e2e/fleet.e2e.ts@@ -188,7 +188,7 @@ describe('two machines in one fleet', () => {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')+ expect(a.daemon.log()).toContain('[devices] 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 })@@ -225,7 +225,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.routeSend failed · injected fault: fleet.routeSend')+ expect(a.daemon.log()).toContain(faults === 'fleet' ? '[devices] fleet did not start · injected fault: fleet' : '[devices] fleet.routeSend failed · injected fault: fleet.routeSend')expect(a.daemon.coresStarted()).toBe(1)onA.close()onB.close()diff --git a/cli/e2e/robustness.e2e.ts b/cli/e2e/robustness.e2e.tsindex 04cd97c7f..b2a563ce0 100644--- a/cli/e2e/robustness.e2e.ts+++ b/cli/e2e/robustness.e2e.ts@@ -186,8 +186,8 @@ describe('what the daemon survives', () => {client.close()})- it('the dial, the window bridges and the device service failing on every call never disconnect the desktop', async () => {- const d = await fresh({ env: { HARNESSD_TEST_FAULTS: 'dial,window,devices' } })+ it('the dial, the window bridges and the Wi-Fi device service failing on every call never disconnect the desktop', async () => {+ const d = await fresh({ env: { HARNESSD_TEST_FAULTS: 'dial,window,wifi' } })await d.start()// The handshake itself asks the dial for its status.const desktop = await LocalClient.connect(d)@@ -207,7 +207,7 @@ describe('what the daemon survives', () => {expect(desktop.closed).toBe(false)expect(d.log()).toContain('[devices] dial failed · injected fault: dial')expect(d.log()).toContain('[devices] window failed · injected fault: window')- expect(d.log()).toContain('[devices] devices failed · injected fault: devices')+ expect(d.log()).toContain('[devices] wifi failed · injected fault: wifi')expect(d.log()).not.toContain('local dispatch failed')expect(d.coresStarted()).toBe(1)desktop.close()diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.tsindex ceb2fdd5c..467025d37 100644--- a/cli/e2e/services.e2e.ts+++ b/cli/e2e/services.e2e.ts@@ -338,8 +338,8 @@ 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.routeSend', 'the fleet service is unavailable', '[services] fleet.routeSend failed · injected fault: fleet.routeSend'],+ ['fleet', 'no agent list yet', '[devices] fleet did not start · injected fault: fleet · the devices run without it'],+ ['fleet.routeTask,fleet.routeSend', 'the fleet service is unavailable', '[devices] fleet.routeSend failed · injected fault: fleet.routeSend'],]) {daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: faults } })const d = daemon@@ -358,6 +358,37 @@ describe('a failing service never takes the core down', () => {}})+ it('with the devices not starting, or the Devices tab failing, the dial, ⌘K and the tab say so and the core runs on', async () => {+ for (const [faults, said] of [+ ['devices', '[services] devices did not start · injected fault: devices · the core runs without it'],+ ['devices.harness_devices_list', '[services] devices.harness_devices_list failed · injected fault: devices.harness_devices_list'],+ ]) {+ 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, `devices-${faults.length}`)+ if (faults === 'devices') {+ // ⌘K has no router without the devices: it says so, and sends nothing.+ expect(await routeTask(client, 'fix the parser')).toMatchObject({ agentId: '', reason: 'the devices service is unavailable', candidates: [] })+ expect(await client.request('route_send', { agentId, text: 'not delivered' })).toMatchObject({ ok: false, reason: 'the devices service is unavailable' })+ expect(await client.request('harness_devices_list', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'devices' })+ } else {+ expect(await client.request('harness_devices_list', {})).toMatchObject({ error: 'SERVICE_FAILED', service: 'devices' })+ // Its other request, and ⌘K, are the devices' own answers still.+ expect(await client.request('harness_device_settings', { id: 'dial-1', patch: { brightness: 3 } })).toMatchObject({ error: 'DEVICE_OFFLINE' })+ expect(await routeTask(client, 'fix the parser')).toMatchObject({ agentId, confidence: 1 })+ }+ 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()const d = daemondiff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex c6b908dc7..8d3b96f7e 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -146,13 +146,17 @@ const WALK_TIMEOUT_MS = 60_000** BACKEND_SOCKET_BUDGET came down again on 6 October (step 7): the Model Manager's grid commands, the grid* name it worked out and the model lists it built moved to the models service, 1,457 → 1,391 lines.+ *+ * Lowered to 2,230 the same day (step 9, D1): the dial's host, its window bridges and the fleet left+ * runForeground for the devices' own service (services/devices.ts), 2,375 lines to 2,213.*/-const RUN_FOREGROUND_BUDGET = 2_380+const RUN_FOREGROUND_BUDGET = 2_230/** Lowered from 2,180 when the relay and its E2EE left the socket for the gateway (step 10, R1: 1,440).* The Wi-Fi device's relay came back to it in R2, beside the device service it answers for, over the* gateway's sessions (lib/autonomous-device/overGateway.ts): 1,460. Models' grid commands, grid name and- * lists left it for the models service (step 7): 1,391. */-const BACKEND_SOCKET_BUDGET = 1_400+ * lists left it for the models service (step 7): 1,391. Then 1,200 when the Devices tab's requests+ * became the devices' own (step 9, D1), 1,207 → 1,194. */+const BACKEND_SOCKET_BUDGET = 1_200/** Exceptions, each with its reason. Keep this short. */const SERVICE_MAY_IMPORT: Record<string, string> = {@@ -245,7 +249,13 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {// identity store it signed with leave. Its welcomes are signed by the gateway (gateway/observerKey.ts), and// its observers' terminals are read by the core's read-only stream manager (core/terminalWatch.ts), which// stays with what the core keeps of Share (core/sharingLink.ts).-const CORE_CLOSURE_BUDGET = 87_570+//+// Grew to 87,941 in 389 (step 9, D1), from 87,476 in 387: the devices behind a port of their own, still in+// the core's process (services/devices.ts, services/devicesGuard.ts, the port and its `CoreApi` members in+// core/api.ts). runForeground lost their wiring and the pane writer lock came into the core+// (core/deviceInput.ts). D2 runs the devices in a process of their own, which takes them out: the dial,+// the window bridges, the fleet's router and lane, and the voice router, about 10,000 lines.+const CORE_CLOSURE_BUDGET = 88_040/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */const EDGE: RegExp[] = [@@ -270,30 +280,33 @@ const EDGE: RegExp[] = [* can carry an install's progress back to it, or it leaves with the device (step 10). */const STORE_BYPASS = 'step 10: the Wi-Fi device\'s own way into the Store, until it goes through the Store\'s process'+/** The devices run behind their port in the core's process (step 9, D1): their own process takes them out+ * (D2), the dial, its window bridges and the fleet's router and lane with them. */+const D2 = 'step 9, D2: the devices (the dial, the window bridges, the fleet), in a process of their own'+const CORE_MAY_REACH: Record<string, string> = {- 'cable/cableFleet.ts': 'step 9: the dial, in the devices process',- 'cable/cableFrame.ts': 'step 9: the dial, in the devices process',- 'cable/cableHost.ts': 'step 9: the dial, in the devices process',- 'cable/cableSession.ts': 'step 9: the dial, in the devices process',- 'cable/companionProtocol.ts': 'step 9: the dial, in the devices process',- 'cable/dialLog.ts': 'step 9: the dial, in the devices process',- 'cable/dialPortVerdicts.ts': 'step 9: the dial, in the devices process',- 'cable/fwPush.ts': 'step 9: the dial, in the devices process',- 'cable/machineFleet.ts': 'step 9: the dial, in the devices process',- 'cable/notificationRead.ts': 'step 9: the dial, in the devices process',- 'cable/passageCarry.ts': 'step 9: the dial, in the devices process',- 'cable/questionInbox.ts': 'step 9: the dial, in the devices process',- 'cable/serial.ts': 'step 9: the dial, in the devices process',- 'cable/terminalActivity.ts': 'step 9: the dial, in the devices process',- 'cable/usbConsoleUser.ts': 'step 9: the dial, in the devices process',- 'cable/voiceDraft.ts': 'step 9: the dial, in the devices process',- 'cable/windowForm.ts': 'step 9: the dial, in the devices process',- 'cable/windowRoute.ts': 'step 9: the dial, in the devices process',- 'cable/windowSelection.ts': 'step 9: the dial, in the devices process',- 'cable/windowVisit.ts': 'step 9: the dial, in the devices process',- 'device/deviceFleet.ts': 'step 9: the fleet, beside the dial',- 'device/deviceLink.ts': 'step 9: the fleet, beside the dial',- 'device/machineList.ts': 'step 9: the dial, in the devices process',+ 'cable/cableFleet.ts': D2,+ 'cable/cableFrame.ts': D2,+ 'cable/cableHost.ts': D2,+ 'cable/cableSession.ts': D2,+ 'cable/companionProtocol.ts': D2,+ 'cable/dialLog.ts': D2,+ 'cable/dialPortVerdicts.ts': D2,+ 'cable/fwPush.ts': D2,+ 'cable/machineFleet.ts': D2,+ 'cable/notificationRead.ts': D2,+ 'cable/passageCarry.ts': D2,+ 'cable/questionInbox.ts': D2,+ 'cable/serial.ts': D2,+ 'cable/usbConsoleUser.ts': D2,+ 'cable/voiceDraft.ts': D2,+ 'cable/windowForm.ts': D2,+ 'cable/windowRoute.ts': D2,+ 'cable/windowSelection.ts': D2,+ 'cable/windowVisit.ts': D2,+ 'device/deviceFleet.ts': D2,+ 'device/deviceLink.ts': D2,+ 'device/machineList.ts': 'the account\'s machine list, which /api/machines answers from and the trust group reads: with the account proxies (step 10)','dsh/builtins.ts': 'the bundled harnesses are put in place by the core\'s start, which cli.js carries them for anyway; in the Store\'s lean process they cost a second copy (core/main.ts)','dsh/catalog.ts': STORE_BYPASS,'dsh/install.ts': STORE_BYPASS,@@ -303,7 +316,6 @@ const CORE_MAY_REACH: Record<string, string> = {'dsh/update.ts': STORE_BYPASS,'dsh/updates.ts': STORE_BYPASS,'lib/autonomous-device/dump.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',- 'lib/autonomous-device/input.ts': 'step 9: the pane writer lock, into core/input.ts','lib/autonomous-device/localApi.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway','lib/autonomous-device/overGateway.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway','lib/autonomous-device/parts.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',@@ -321,8 +333,10 @@ const CORE_MAY_REACH: Record<string, string> = {'lib/sessionSearch/sessionTurns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads','lib/sessionSearch/transcript.ts': 'the readers of other engines\' sessions keep this helper: it moves beside them, out of search\'s folder','lib/sessionSearch/turns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads',- 'services/fleet.ts': 'step 9: the fleet, beside the dial',- 'services/fleetRouter.ts': 'step 9: the fleet, beside the dial',+ 'services/devices.ts': D2,+ 'services/devicesGuard.ts': D2,+ 'services/fleet.ts': D2,+ 'services/fleetRouter.ts': D2,'services/shell.ts': 'shell setup and launch receipts, in the edge host; only the argv launch stays in the core (#893)','sharing/viewer.ts': 'the windows\' interactive viewers capture with it (lib/interactiveViewer.ts): headless Chrome belongs with the viewers\' process (plan, "Sharing")',}diff --git a/cli/src/backendSocket.devices.spec.ts b/cli/src/backendSocket.devices.spec.tsindex a05fc8f0f..2a239f6a5 100644--- a/cli/src/backendSocket.devices.spec.ts+++ b/cli/src/backendSocket.devices.spec.ts@@ -1,32 +1,40 @@import { describe, expect, it, vi } from 'vitest'import { BackendSocket } from './backendSocket.js'+import { DEVICES_REQUESTS, type Asker } from './core/api.js'import { dispatchDown, gatewayOf, relaySocket } from './testing/relaySocket.js'+// The Devices tab's requests are the devices' own (services/devices.ts): the socket only routes them, with+// who asked as it established it, and the devices answer the owner alone.describe('Devices host ownership', () => {- it.each(['harness_devices_list', 'harness_device_settings'])('requires sealed owner requests for %s and replies to that connection', async type => {- const socket = relaySocket('fixture'), internals = socket as any- const status = vi.fn(() => ({ attached: true, devices: [{ id: 'usb', attached: true, settings: { brightness: 80 } }] }))- const set = vi.fn(async () => ({ ok: true }))- socket.harnessDevices = { status: status as any, set }+ it.each(DEVICES_REQUESTS)('routes %s to the devices only sealed from afar, saying who asked, and replies to that connection', async type => {+ const socket: BackendSocket = relaySocket('fixture')+ const routed: Asker[] = []+ socket.serviceRouter = (asked, _payload, asker, reply) => {+ if (asked !== type) return false+ routed.push(asker)+ reply({ ok: true, owner: asker.owner })+ return true+ }vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')const clear = { type, payload: { requestId: 'one', id: 'usb', patch: { brightness: 35 } } }vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(clear)const reply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: `${type}_result`, payload: { __e2e: 'sealed' } })+ // In the clear from afar: never routed.await dispatchDown(socket, clear, 'remote')- expect(status).not.toHaveBeenCalled()+ expect(routed).toEqual([])const sealed = { type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }+ // A device's session may ask, but not as the owner; the owner's own app may.role.mockReturnValue('device')await dispatchDown(socket, sealed, 'remote')- expect(status).not.toHaveBeenCalled()role.mockReturnValue('web')await dispatchDown(socket, sealed, 'remote')- expect(status).toHaveBeenCalled()- expect(reply).toHaveBeenLastCalledWith('remote', `${type}_result`, 'one', expect.objectContaining(type.endsWith('list') ? { protocol: 1 } : { ok: true }))- if (type.endsWith('settings')) expect(set).toHaveBeenCalledExactlyOnceWith('usb', { brightness: 35 })+ expect(routed).toEqual([{ local: false, owner: false, connection: 'remote', requestId: 'one' }, { local: false, owner: true, connection: 'remote', requestId: 'one' }])+ expect(reply).toHaveBeenLastCalledWith('remote', `${type}_result`, 'one', { ok: true, owner: true })const local: unknown[] = []socket.registerLocalClient('local:tool', { sendFrame: frame => { local.push(frame); return true }, sendBinary: () => true }, { tool: true })await dispatchDown(socket, clear, 'local:tool')+ expect(routed.at(-1)).toEqual({ local: true, owner: true, connection: 'local:tool', requestId: 'one' })expect(local).toContainEqual(expect.objectContaining({ type: `${type}_result`, payload: expect.objectContaining({ requestId: 'one' }) }))await socket.stop()})diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 7118f4b3a..427d21088 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -29,7 +29,6 @@ import { ApiConnectionError, ApiConnections } from './lib/apiConnections.js'import { resolveApiTarget } from './lib/apiModels.js'import { isApiLaunch, parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'import { probeEngines } from './lib/engineProbe.js'-import { harnessDevicesRequest, type HarnessDevicesService } from './lib/harnessDevices.js'import { engineInstallRecipe } from './lib/engineInstall.js'import { agentFrame, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'import { agentTokenUsage } from './lib/agentTokenUsage.js'@@ -61,7 +60,6 @@ export interface LocalClientSink {}export class BackendSocket {- harnessDevices: HarnessDevicesService | null = null/** This machine's name as Harness shows it (Machines), from the backend's `machine_meta`. Null* until the first one arrives. */private machineDisplayName: string | null = null@@ -1135,17 +1133,6 @@ export class BackendSocket {this.questionProvider?.(payload, answer)return- // Physical devices belong to this machine; only its owner or loopback tools may manage them.- case 'harness_devices_list':- case 'harness_device_settings': {- if (!owner) {- reply(type, requestId, { error: 'OWNER_REQUIRED' })- return- }- reply(type, requestId, await harnessDevicesRequest(this.harnessDevices, type, payload))- return- }-// The colours the desktop paints its panes with (core/terminals/requests.ts, bound by cli.ts).case 'theme_set':reply(type, requestId, this.themeProvider ? this.themeProvider(payload) : { error: 'UNSUPPORTED' })diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.tsindex d982d3967..7e64d7017 100644--- a/cli/src/cable/cableHost.spec.ts+++ b/cli/src/cable/cableHost.spec.ts@@ -3,21 +3,17 @@ 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 type { FleetRouting } from '../services/fleet.js'import { ServiceUnavailableError } from '../core/serviceHost.js'+import type { RegisteredSession } from '../lib/registry.js'const AGENTS: Array<{ agentId: string; registeredAt: number; active: boolean; terminalAvailable: boolean; engine: string }> = []-vi.mock('../lib/registry.js', () => ({- registry: {- list: () => AGENTS,- active: () => AGENTS.filter((a) => a.active),- advertised: () => AGENTS.filter((a) => a.terminalAvailable),- },- projectDisplayName: (s: { agentId: string }) => s.agentId,-}))function wiring(over: Partial<CableHostWiring> = {}): CableHostWiring {return {+ // The core's advertised agents and their names: what the router this host keeps for itself reads.+ sessions: () => AGENTS.filter((a) => a.terminalAvailable) as unknown as RegisteredSession[],+ displayName: (s) => s.agentId,machineName: () => 'MacbookPro.local',machineId: () => 'mine',computerId: () => 'abc-123',diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 8e80b8ba6..c9406bb38 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -18,13 +18,13 @@import { join } from 'node:path'import { notificationReadToken, type UnreadNotification } from './notificationRead.js'-import { AuthSessionManager, readAuthSession } from '../lib/authSession.js'-import { registry, projectDisplayName, type RegisteredSession } from '../lib/registry.js'+import type { RegisteredSession } from '../lib/registry.js'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 { FleetRouter } from '../services/fleetRouter.js'-import type { FleetRouting, ForkResult } from '../core/api.js'+import type { ForkResult } from '../core/api.js'+import type { FleetRouting } from '../services/fleet.js'import { ServiceUnavailableError } from '../core/serviceHost.js'import type { AppSwarms, CableAgent, CableHost, CableMachine, CableMachineSource, CableSwarm, CableTile, DialStatus, OpenReason, RouteDecision } from './cableSession.js'@@ -45,6 +45,10 @@ export interface RecentTurn {}export interface CableHostWiring {+ /** The live agents the apps are shown, and the name they show for each: the router this host keeps for+ * this computer reads them (the core's `agents.advertised` and `agents.displayName`). */+ sessions: () => RegisteredSession[]+ displayName: (session: RegisteredSession) => string/** Exact live terminal footer for a local agent; absent when no footer is visible. */activityText?: (agentId: string) => Promise<string | null>/** The person's own last questions to a LOCAL agent, newest first. */@@ -57,6 +61,14 @@ export interface CableHostWiring {/** Whether this computer holds an account. False → the dial serves THIS computer alone: the cloud* lane (the other machines, and voice) is what an account buys, and it is not dialled without one. */signedIn?: () => boolean+ /** The account's sign-in, for the transcriber: the core's (`account.accessToken`), never one of this+ * host's own. Absent, voice says to sign in. */+ accessToken?: (opts?: { force?: boolean; failedToken?: string }) => Promise<string>+ /** The account's environment, which the transcriber checks the upload against. */+ environment?: () => string+ /** A dial is on the wire on this computer, or none is any more: the core streams the turn cards and+ * makes the recaps for it, as for a device watching through the backend. */+ watching?: (on: boolean) => void/** Deliver text into an agent. The SAME path the web and the WiFi device use — see cli.ts. */sendTurn: (agentId: string, text: string) => voidstopTurn: (agentId: string) => void@@ -136,8 +148,8 @@ export class DaemonCableHost implements CableHost {this.local = new FleetRouter({...wiring,// The same set `agents_list` answers the apps with — see the router's localAgents.- sessions: () => registry.advertised(),- displayName: projectDisplayName,+ sessions: () => wiring.sessions(),+ displayName: (session) => wiring.displayName(session),desk: () => this.desk,}, fleet)}@@ -214,6 +226,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 {+ this.wiring.watching?.(true)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@@ -260,6 +273,7 @@ export class DaemonCableHost implements CableHost {* a screen that is not there.*/onDialGone(): void {+ this.wiring.watching?.(false)this.wiring.clearSelection?.()this.wiring.clearVisit?.()this.wiring.clearForm?.()@@ -706,12 +720,12 @@ export class DaemonCableHost implements CableHost {* sentence to a clock is the one failure the person cannot work around.*/async transcribe(pcm: Buffer, sampleRate: number, lang: string): Promise<string> {- const session = readAuthSession()// The text reaches the dial's glass as a toast, so it is addressed to the person holding it, not to// a terminal: signing in happens on the computer, and that is the one thing they need to know.- if (!session) throw new Error('Sign in on your computer to use voice')+ const accessToken = this.wiring.accessToken+ if (!accessToken || this.wiring.signedIn?.() === false) throw new Error('Sign in on your computer to use voice')+ const autonomousEnv = this.wiring.environment?.() ?? ''- const auth = new AuthSessionManager(this.backendHttpBase())const url = `${this.backendHttpBase()}${env.CABLE_STT_PATH}?lang=${encodeURIComponent(lang)}`// The WAV is built ONCE: it is the same bytes on a retry, and re-encoding megabytes to say the same// thing twice is time taken out of a person's turn.@@ -723,20 +737,20 @@ export class DaemonCableHost implements CableHost {method: 'POST',headers: {authorization: `Bearer ${token}`,- 'x-autonomous-env': session.autonomousEnv,+ 'x-autonomous-env': autonomousEnv,'content-type': `multipart/form-data; boundary=${boundary}`,},body,})- let token = await auth.accessToken()+ let token = await accessToken()let res = await post(token)if (res.status === 401) {// `failedToken` is what makes this one refresh rather than a loop: the manager only refreshes when// the token that failed is still the current one, so two callers racing a stale token do not each// burn a refresh.await res.body?.cancel()- token = await auth.accessToken({ force: true, failedToken: token })+ token = await accessToken({ force: true, failedToken: token })res = await post(token)}if (!res.ok) {diff --git a/cli/src/cable/cableVoice.spec.ts b/cli/src/cable/cableVoice.spec.tsindex 307c98a34..02d1e7fb8 100644--- a/cli/src/cable/cableVoice.spec.ts+++ b/cli/src/cable/cableVoice.spec.ts@@ -1,14 +1,10 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-const auth = vi.hoisted(() => ({+// The core's sign-in, as the host is handed it (`CoreApi.account`): the host holds none of its own.+const auth = {session: { autonomousEnv: 'prod' } as { autonomousEnv: string } | null,accessToken: vi.fn(),-}))-vi.mock('../lib/authSession.js', () => ({- readAuthSession: () => auth.session,- AuthSessionManager: class { accessToken = auth.accessToken },-}))-vi.mock('../lib/registry.js', () => ({ registry: {}, projectDisplayName: () => '' }))+}vi.mock('../lib/voiceRouter.js', () => ({ routeVoiceTask: vi.fn() }))vi.mock('../config/env.js', () => ({ env: {BACKEND_WS_URL: 'wss://api.example.test/', CABLE_STT_PATH: '/api/voice/stt',@@ -26,8 +22,11 @@ const rejected = (status: number, code: string, message = 'private response detafunction setup() {const log = vi.fn()- // Transcription needs only log; use the real method to exercise its fetch/retry behavior.- const host = new DaemonCableHost({ log } as unknown as CableHostWiring)+ // Transcription needs only the sign-in and log; use the real method to exercise its fetch/retry behavior.+ const host = new DaemonCableHost({+ log, accessToken: auth.accessToken, signedIn: () => auth.session !== null, environment: () => auth.session?.autonomousEnv ?? '',+ sessions: () => [], displayName: () => '',+ } as unknown as CableHostWiring)const fetchMock = vi.fn<typeof fetch>()vi.stubGlobal('fetch', fetchMock)return { host, log, fetchMock }diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.mdindex ca673c502..1e6d36acb 100644--- a/cli/src/core/AGENTS.md+++ b/cli/src/core/AGENTS.md@@ -29,6 +29,8 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE- `terminals/`: who controls a pane (the control lease).- `engines/`: the engines' hooks.- `input.ts`, `questions.ts`: messages into a pane; an agent's question and its answer.+ `deviceInput.ts`: the pane writer lock every write takes, and a device's queued turns behind it.+ `cardText.ts`: an engine's error, rewritten for a device's card.- `deliveries.ts`: delivered turns, the Wi-Fi device's, a team's and the orchestrator's: text written into anagent under a delivery id of its maker's, and what became of it, told back to that maker in its process.- `main.ts`: the core's entry (`harness __run`) and composition root, `runForeground`: it builds thesediff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.tsindex 6fcc80275..39269570a 100644--- a/cli/src/core/agents/bind.ts+++ b/cli/src/core/agents/bind.ts@@ -13,7 +13,7 @@ import { findCursorTranscript } from '../../engines/cursor/discovery.js'import { cursorDataDir } from '../../engines/cursor/home.js'import { findGrokTranscript } from '../../engines/grok/session.js'import type { CommanderMirror } from '../../lib/commander.js'-import type { AutonomousDeviceInput } from '../../lib/autonomous-device/input.js'+import type { AutonomousDeviceInput } from '../deviceInput.js'import { isRecentlyDeleted } from '../../lib/deletedSessions.js'import { transcriptIsFirstTurn } from '../../lib/firstTurnReplay.js'import { sid } from '../../lib/log.js'diff --git a/cli/src/core/agents/discovery.ts b/cli/src/core/agents/discovery.tsindex 5588a73b4..fd42ababd 100644--- a/cli/src/core/agents/discovery.ts+++ b/cli/src/core/agents/discovery.ts@@ -8,7 +8,7 @@* docs/design/2026-10-03-harnessd.md). The reconciler itself, with what it scans, stays there.*/import { isTerminalEngine } from '../../engines/types.js'-import type { AutonomousDeviceInput } from '../../lib/autonomous-device/input.js'+import type { AutonomousDeviceInput } from '../deviceInput.js'import type { QuestionWatcher } from '../../lib/askQuestion.js'import { sameGridAssignment } from '../../lib/gridAssignment.js'import { sid } from '../../lib/log.js'diff --git a/cli/src/core/agents/forget.ts b/cli/src/core/agents/forget.tsindex f4ddd1caa..dd44364ed 100644--- a/cli/src/core/agents/forget.ts+++ b/cli/src/core/agents/forget.ts@@ -8,7 +8,7 @@import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'import type { CursorTranscriptDiscovery } from '../../engines/cursor/discovery.js'import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'-import type { AutonomousDeviceInput } from '../../lib/autonomous-device/input.js'+import type { AutonomousDeviceInput } from '../deviceInput.js'import type { CommanderMirror } from '../../lib/commander.js'import { sid } from '../../lib/log.js'import type { registry } from '../../lib/registry.js'diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 3ba586387..c5a08956a 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from 'vitest'import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'-import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, FLEET_FALLBACKS, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, resolveAgent, SHARING_FALLBACKS, TEAMS_FALLBACKS, TERMINALS_OFF, type CoreApiDeps } from './api.js'-import { FAIL } from './serviceHost.js'+import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, DEVICES_FALLBACKS, emptyPorts, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, resolveAgent, SHARING_FALLBACKS, TEAMS_FALLBACKS, TERMINALS_OFF, type CoreApiDeps } from './api.js'+import { FAIL, readFallback } from './serviceHost.js'const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession@@ -29,8 +29,8 @@ describe('the core API services stand on', () => {expect(resolveAgent(agents, 'nobody')).toBeUndefined()})- it('lists every agent, live then stopped, and names them as the apps do', async () => {- const deps: CoreApiDeps = {+ /** The core's own pieces, as `createCoreApi` is handed them. */+ const coreDeps = (): CoreApiDeps => ({dataDir: '/data',registry: {list: vi.fn(() => [row('live')]),@@ -67,7 +67,21 @@ describe('the core API services stand on', () => {observer: vi.fn(() => true),turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(() => []), asks: vi.fn(() => []), deliver: vi.fn(), cancelDelivery: vi.fn(() => true), onDelivery: vi.fn(() => () => {}) },questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => true) },- }+ machine: { id: vi.fn(() => 'machine-1'), computerId: vi.fn(() => 'computer-1'), name: vi.fn(() => 'Studio') },+ activityText: vi.fn(async () => 'Reading 3 files'),+ signedIn: vi.fn(() => true),+ environment: vi.fn(() => 'prod'),+ machines: vi.fn(async () => ({ status: 200, body: {} })),+ sendLocal: vi.fn(),+ sendToWindow: vi.fn(() => true),+ hasWindow: vi.fn(() => true),+ devicesChanged: vi.fn(),+ dialWatching: vi.fn(),+ log: vi.fn(),+ })++ it('lists every agent, live then stopped, and names them as the apps do', async () => {+ const deps = coreDeps()const core = createCoreApi(deps)expect(core.dataDir).toBe('/data')expect(await core.terminals.open({ argv: ['/bin/zsh'], cwd: '/work' })).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })@@ -111,21 +125,50 @@ describe('the core API services stand on', () => {expect(core.daemon).toBe(deps.daemon)expect(core.turns).toBe(deps.turns)expect(core.questions).toBe(deps.questions)+ // What the devices ask of the core: this computer, the sign-in, a pane's footer, the windows.+ expect(core.machine).toBe(deps.machine)+ expect(core.agents.activityText).toBe(deps.activityText)+ expect(core.account.signedIn).toBe(deps.signedIn)+ expect(core.account.environment).toBe(deps.environment)+ expect(core.account.machines).toBe(deps.machines)+ expect(core.clients.hasWindow).toBe(deps.hasWindow)+ expect(core.clients.devicesChanged).toBe(deps.devicesChanged)+ expect(core.clients.dialWatching).toBe(deps.dialWatching)})- it('answers ⌘K, when the fleet fails, with no agent picked and nothing sent, saying why', () => {- 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('lets the devices put their own frames in front of the windows, and no other', () => {+ const deps = coreDeps()+ const core = createCoreApi(deps)+ core.clients.sendLocal({ type: 'dial_focus', payload: { agentId: 'a' } })+ expect(deps.sendLocal).toHaveBeenCalledWith({ type: 'dial_focus', payload: { agentId: 'a' } })+ expect(core.clients.sendToWindow('window-1', { type: 'dial_form', payload: {} })).toBe(true)+ expect(deps.sendToWindow).toHaveBeenCalledWith('window-1', { type: 'dial_form', payload: {} })+ // A devices process speaks as a service: what it may show a person is decided here, frame by frame.+ core.clients.sendLocal({ type: 'agent_deleted', payload: {} } as unknown as Parameters<typeof core.clients.sendLocal>[0])+ expect(core.clients.sendToWindow('window-1', { type: 'dial_focus', payload: {} } as unknown as Parameters<typeof core.clients.sendToWindow>[1])).toBe(false)+ core.clients.sendLocal(null as unknown as Parameters<typeof core.clients.sendLocal>[0])+ expect(deps.sendLocal).toHaveBeenCalledTimes(1)+ expect(deps.sendToWindow).toHaveBeenCalledTimes(1)+ expect(deps.log).toHaveBeenCalledWith('[services] the devices sent a window agent_deleted, which is not theirs to send')+ expect(deps.log).toHaveBeenCalledWith('[services] the devices sent a window dial_focus, which is not theirs to send')+ // Said to the console when the core gives no log of its own.+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ createCoreApi({ ...deps, log: undefined }).clients.sendLocal({ type: 'nothing' } as unknown as Parameters<typeof core.clients.sendLocal>[0])+ expect(warn).toHaveBeenCalledWith('[services] the devices sent a window nothing, which is not theirs to send')+ warn.mockRestore()})- 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('answers ⌘K, when the devices fail, with no agent picked and nothing sent, saying why', async () => {+ const reason = 'the devices service is unavailable'+ expect(await (readFallback(DEVICES_FALLBACKS.routeTask).value)).toMatchObject({ agentId: '', reason, candidates: [] })+ expect(readFallback(DEVICES_FALLBACKS.routeSend)).toEqual({ deferred: true, value: { ok: false, machine: '', reason } })+ // The Wi-Fi device finds no desk to walk; the dial and the window bridges hear nothing.+ expect(readFallback(DEVICES_FALLBACKS.stepFocus).value).toBe('no_agents')+ for (const member of ['card', 'desk', 'swarms', 'unread', 'appFocus', 'seen', 'settings', 'windowFocus', 'windowReply', 'voiceReply', 'windowGone', 'scroll', 'engines', 'commanders'] as const) {+ expect(DEVICES_FALLBACKS[member], member).toBeUndefined()}+ expect(readFallback(DEVICES_FALLBACKS.stop)).toEqual({ deferred: true, value: undefined })+ expect(FAIL).toBeTypeOf('symbol')})it('falls back, when the teams fail, to an undo that has nothing to undo, and holds no pane for a team', () => {@@ -135,7 +178,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, fleet: null, monitor: null, orchestrator: null, sharing: null })+ expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, monitor: null, orchestrator: null, sharing: null })expect(emptyPorts()).not.toBe(emptyPorts())})diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 548dd5b66..d8a9ecf06 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -11,10 +11,10 @@* 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 { CableAgent, CableMachine, CableMachineSource } from '../cable/cableSession.js'-import type { FleetEvent } from '../cable/machineFleet.js'-import type { AnswerReceipt, ReviewedAnswer } from '../cable/questionInbox.js'+import type { ReviewedAnswer } from '../cable/questionInbox.js'import type { AgentEngine } from '../engines/types.js'+import type { AppSwarms } from '../cable/cableSession.js'+import type { UnreadNotification } from '../cable/notificationRead.js'import type { AgentDshContext } from '../lib/agentFrame.js'import type { GridAccess } from '../lib/gridAttach.js'import type { createHarnessResourcesReader } from '../lib/harnessResources.js'@@ -27,16 +27,18 @@ import type { LiveEvent } from '../lib/normalize.js'import type { SessionInputDelivery } from '../lib/sessionInput.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'import type { TerminalBinaryClear } from '../lib/terminalBinary.js'import type { RouteAnswer } from '../localWsServer.js'import type { SwarmPromptScopes } from '../teams/promptScope.js'-import { FAIL, later, ServiceUnavailableError, type PortFallbacks } from './serviceHost.js'+import { FAIL, later, readFallback, ServiceUnavailableError, type PortFallbacks } from './serviceHost.js'export type { RouteAnswer }+/** What a service guards its own parts with, as the core guards a service (core/serviceHost.ts): the+ * devices keep a dial failing from costing ⌘K its routing (services/devices.ts). */+export { FAIL, later, readFallback, ServiceUnavailableError, type PortFallbacks }/** A service may open a terminal with a literal argv, never shell source. */export interface TerminalOpen {@@ -71,6 +73,15 @@ export interface CoreApi {/** The daemon's data folder; a service keeps its own files in it. */dataDir: stringterminals: TerminalsPort+ /** This computer, as the dial's wheel and the fleet name it. */+ machine: {+ /** The account's id for this machine, or '' until the daemon has one (signed out). */+ id(): string+ /** This computer's own durable id. */+ computerId(): string+ /** Its display name, else "This machine". */+ name(): string+ }agents: {/** Every agent on this machine: the live ones, then the stopped ones. */all(): RegisteredSession[]@@ -102,6 +113,9 @@ export interface CoreApi {create(request: AgentCreateRequest): Promise<{ ok: true; agentId: string } | { ok: false; error: string; detail?: string }>/** What a live agent's frame says about its harness: its name, its viewer and its verdict; null for none. */dsh(session: RegisteredSession): AgentDshContext | null+ /** What a live Claude Code or Codex agent's pane footer says it is doing ("Reading 3 files"), or null:+ * the dial's working card. The pane is read by the core; only the line leaves it. */+ activityText(agentId: string): Promise<string | null>}/** A device's or another machine's turns for an agent on this one: the doors the web and the hooks use. */turns: {@@ -147,15 +161,22 @@ export interface CoreApi {/** The account's private grid name, minted and remembered by the backend; null when an older* backend issues none. Bounded in time. */mintGridName(): Promise<string | null>- /** This machine's harness access token, for handing a sign-in to grid or dialling the fleet's lane.- * Rejects when signed out. `force` refreshes it (once, after a 401 for `failedToken`): the core's one- * session manager shares a refresh in flight with the backend link. */+ /** This machine's harness access token, for handing a sign-in to grid, dialling the fleet's lane or a+ * dial's spoken words to the transcriber. Rejects when signed out. `force` refreshes it (once, after a+ * 401 for `failedToken`): the core's one session manager shares a refresh in flight with the backend link. */accessToken(options?: { force?: boolean; failedToken?: string }): Promise<string>/** The fleet's lane to the owner's other machines, sealed by the gateway with this machine's E2EE* identity, which no service holds (`LaneSeal`). */lane: LaneSeal/** This machine's E2EE identity as Share's owner signs with it, held by the gateway (`ObserverKey`). */observerKey: ObserverKey+ /** Whether this computer holds an account: a sign-in or sign-out restarts the daemon. */+ signedIn(): boolean+ /** The account's environment (`prod`, …), which the backend checks every request against. */+ environment(): string+ /** The owner's machines, read from the backend now (`GET /api/machines`, or this computer alone signed+ * out), and kept as the core's own list for the windows and the trust group. Never rejects. */+ machines(): Promise<{ status: number; body: Record<string, unknown> }>/** The account's private grid as the backend named it (`machine_meta`), or as grid's set-up just* confirmed it; null before either. Working it out when neither has said is the models service's* (`lib/gridDerive.ts`). */@@ -186,6 +207,20 @@ export interface CoreApi {/** A frame for one of Share's observers, sealed by Share itself, to the relay through the gateway; false* when it could not be handed over. */observer(connId: string, type: string, payload: Record<string, unknown>): boolean+ /** A frame from the devices for every window on this computer, never the cloud: what a hand at this+ * desk did. Only `DEVICE_WINDOW_FRAMES`; the core drops any other. */+ sendLocal(frame: DeviceWindowFrame): void+ /** A window bridge's ask, to one window on this computer; false when it is gone. Only+ * `DEVICE_BRIDGE_FRAMES`. */+ sendToWindow(connId: string, frame: DeviceBridgeFrame): boolean+ /** Whether a window on this computer is attached. */+ hasWindow(): boolean+ /** The devices on this computer changed (`harness_devices_changed`): the windows and the owner's apps+ * show them. */+ devicesChanged(payload: Record<string, unknown>): void+ /** A dial on this computer is watching it, or no longer is: the core then makes the turn cards and+ * recaps for it, as for a device watching through the backend. */+ dialWatching(watching: boolean): void}/** How an agent's shell reaches this daemon: the command that runs this harness's CLI, the port the daemon* serves and the machine it serves as. An experiment writes them into the prompts of the agents it runs@@ -562,74 +597,99 @@ export type TeamsEvent = { seq: number; core: string; at: number; agentId: strinexport 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 }++/*+ * The devices (services/devices.ts): the dials on USB, the window bridges they speak through, and the+ * fleet's router every turn goes through, ⌘K's included (docs/design/2026-10-06-core-boundary-next.md,+ * "Devices", step 9). They answer the core through `DevicesPort` and reach it through `CoreApi`, so that+ * they can run in a process of their own: a device that fails, hangs or leaks costs the devices, never a+ * session.+ */++/** The frames the devices may send every window on this computer (`clients.sendLocal`): what a hand at+ * this desk did on a dial, and a spoken task offered to the window's palette. Never to the cloud. */+export const DEVICE_WINDOW_FRAMES = [+ 'dial_open', 'dial_notification_read', 'dial_forked', 'dial_focus', 'dial_swarm', 'dial_scroll', 'dial_status',+ 'voice_route_request',+] as const+export type DeviceWindowFrame = { type: (typeof DEVICE_WINDOW_FRAMES)[number]; payload: Record<string, unknown> }++/** The frames the devices may send one window (`clients.sendToWindow`): a window bridge's ask, to the+ * window that has the person's attention. */+export const DEVICE_BRIDGE_FRAMES = ['dial_selection', 'dial_visit', 'dial_form'] as const+export type DeviceBridgeFrame = { type: (typeof DEVICE_BRIDGE_FRAMES)[number]; payload: Record<string, unknown> }++/** Which window has the person's attention, as the local socket last heard (`app_focus` with a focus+ * revision): where a spoken selection or visit goes (`voice`), and a New Harness form (`form`). */+export interface WindowFocus {+ voice: { machineId: string; agentId: string; connId: string } | null+ form: { machineId: string; connId: string } | null+}++/** A window's answer to a spoken task it was offered (`voice_route_reply`). */+export type VoiceRouteReply = { t: 'taken' } | { t: 'sent'; agentId: string } | { t: 'cancelled' }++/** The Devices tab (services/devices.ts): the devices on this computer, and a device's settings. Only+ * the owner, on this computer or through the owner's own app, may manage them. */+export const DEVICES_REQUESTS = ['harness_devices_list', 'harness_device_settings'] as const/**- * 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.+ * The core's calls into the devices: what the windows on this computer said that the dial follows, the+ * cards every device is sent, ⌘K, and stopping. Every one is a notice or a request the core never waits+ * on in line: across a process, a hung devices process answers the fallbacks, never a frozen core.*/-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 — 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 {+export interface DevicesPort {+ /** A frame bound for the devices (`commander_event`, `commander_question`, `commander_question_close`):+ * every one the core sends the Wi-Fi devices, as it is sent, so a dial cannot drift from them. */+ card(frame: Record<string, unknown>): void+ /** The window's tiles on its active tab, in tile order, and whether the window is in front. */+ desk(agentIds: string[], foreground: boolean): void+ /** The window's tabs, or null once it has gone. */+ swarms(swarms: AppSwarms | null): void+ /** What the window still has unread, newest first. */+ unread(items: UnreadNotification[]): void+ /** The window moved to an agent. */+ appFocus(machineId: string, agentId: string): void+ /** The window looked at an agent. */+ seen(agentId: string, readToken?: string): void+ /** A window changing one device's settings. */+ settings(id: string, patch: Record<string, unknown>): void+ /** Which window has the person's attention now. */+ windowFocus(focus: WindowFocus): void+ /** A window's answer to a bridge's ask. */+ windowReply(kind: 'selection' | 'visit' | 'form', connId: string, machineId: string, payload: Record<string, unknown>): void+ /** A window's answer to a spoken task it was offered. */+ voiceReply(voiceId: string, reply: VoiceRouteReply): void+ /** A window left. */+ windowGone(connId: string): void+ /** ⌘K: which agent a typed task belongs to, on any of the owner's machines. */routeTask(text: string): Promise<RouteAnswer>- routeSend(agentId: string, text: string): SendResult- /** The other machines' cards, for the dial. Returns how to stop hearing them. */- onEvent(listener: (event: FleetEvent) => void): () => void- stop(): void+ /** ⌘K's send: the turn delivered on the agent's own machine, or refused with why. */+ routeSend(agentId: string, text: string): Promise<SendResult>+ /** The Wi-Fi device borrowing the dial's walk along the desk (until it joins the devices: step 10). */+ stepFocus(direction: 'next' | 'previous', currentAgentId?: string): Promise<{ machineId: string; agentId: string } | 'no_agents'>+ /** The Wi-Fi device borrowing the dial's stroke for the window's terminal. */+ scroll(phase: 'down' | 'move' | 'up', dy: number, velocity: number): void+ /** The engines the live agents run: the voice router's worker is one of them. */+ engines(engines: string[]): void+ /** Whether a device watches through the backend: the voice router keeps its worker warm meanwhile. */+ commanders(connected: boolean): void+ /** Let go of the serial ports and the lane, for a restart or a shutdown. */+ stop(): Promise<void>}-const FLEET_UNAVAILABLE = 'the fleet service is unavailable'+const DEVICES_UNAVAILABLE = 'the devices service is unavailable'/**- * 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.+ * What the core gets when the devices fail: the dial and the window bridges hear nothing, ⌘K says so,+ * picking no agent and sending nothing, the Wi-Fi device finds no desk to walk, 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: '' }),- 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,+export const DEVICES_FALLBACKS: PortFallbacks<DevicesPort> = {+ card: undefined, desk: undefined, swarms: undefined, unread: undefined, appFocus: undefined, seen: undefined,+ settings: undefined, windowFocus: undefined, windowReply: undefined, voiceReply: undefined, windowGone: undefined,+ routeTask: later({ agentId: '', machineId: '', name: '', confidence: 0, reason: DEVICES_UNAVAILABLE, candidates: [], weighed: 0, machines: 0, via: '' }),+ routeSend: later({ ok: false, machine: '', reason: DEVICES_UNAVAILABLE }),+ stepFocus: later('no_agents'), scroll: undefined, engines: undefined, commanders: undefined, stop: later(undefined),}/*@@ -901,14 +961,14 @@ export interface CorePorts {models: ModelsPort | nullworkspaces: WorkspacesPort | nullteams: TeamsPort | null- fleet: FleetPort | null+ devices: DevicesPort | nullmonitor: MonitorPort | nullorchestrator: OrchestratorPort | nullsharing: SharingPort | null}export function emptyPorts(): CorePorts {- return { search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null, orchestrator: null, sharing: null }+ return { search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, monitor: null, orchestrator: null, sharing: null }}export interface CoreApiDeps {@@ -943,16 +1003,36 @@ export interface CoreApiDeps {fork: CoreApi['agents']['fork']turns: CoreApi['turns']questions: CoreApi['questions']+ machine: CoreApi['machine']+ activityText: CoreApi['agents']['activityText']+ signedIn: CoreApi['account']['signedIn']+ environment: CoreApi['account']['environment']+ machines: CoreApi['account']['machines']+ /** Where the devices' frames go: every window on this computer, or one. Only the devices' own frame+ * types reach these (`createCoreApi`). */+ sendLocal(frame: { type: string; payload: Record<string, unknown> }): void+ sendToWindow(connId: string, frame: { type: string; payload: Record<string, unknown> }): boolean+ hasWindow: CoreApi['clients']['hasWindow']+ devicesChanged: CoreApi['clients']['devicesChanged']+ dialWatching: CoreApi['clients']['dialWatching']+ log?: (line: string) => void}export function createCoreApi({dataDir, registry, stoppedAgents, databaseHistory, externalSessions, openSessions, syncSession, runtimeModels, viewerChanged,gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, observerKey, observer, privateGridName, machineName, backend, onNotice,- runtimeProfile, setRuntime, fork, create, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF,+ runtimeProfile, setRuntime, fork, create, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF, machine, activityText,+ signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, log = (line) => console.warn(line),}: CoreApiDeps): CoreApi {+ // The devices reach the windows through these alone, and only with their own frames: a devices process+ // speaks to the core as a service, and what it may put in front of a person is decided here, not there.+ const windowFrames = new Set<string>(DEVICE_WINDOW_FRAMES)+ const bridgeFrames = new Set<string>(DEVICE_BRIDGE_FRAMES)+ const refused = (type: unknown): void => log(`[services] the devices sent a window ${String(type).slice(0, 40)}, which is not theirs to send`)return {dataDir,terminals,+ machine,agents: {all: () => [...registry.list(), ...stoppedAgents.list()],live: () => registry.list(),@@ -968,13 +1048,25 @@ export function createCoreApi({fork,create,dsh,+ activityText,},turns,questions,transcripts: { databaseHistory },external: { sessions: externalSessions, open: openSessions },- account: { mintGridName, accessToken, lane, observerKey, privateGridName, machineName, backend, onNotice },- clients: { viewerChanged, gridNamed, gridModelsChanged, dshInstallStatus, windows, observer },+ account: { mintGridName, accessToken, lane, observerKey, privateGridName, machineName, backend, onNotice, signedIn, environment, machines },+ clients: {+ viewerChanged, gridNamed, gridModelsChanged, dshInstallStatus, windows, observer, hasWindow, devicesChanged, dialWatching,+ sendLocal: (frame) => {+ if (windowFrames.has(frame?.type)) sendLocal(frame)+ else refused(frame?.type)+ },+ sendToWindow: (connId, frame) => {+ if (bridgeFrames.has(frame?.type)) return sendToWindow(connId, frame)+ refused(frame?.type)+ return false+ },+ },daemon,}}diff --git a/cli/src/lib/deviceErrors.spec.ts b/cli/src/core/cardText.spec.tssimilarity index 89%rename from cli/src/lib/deviceErrors.spec.tsrename to cli/src/core/cardText.spec.tsindex fe5ac7d8c..ef19f6a71 100644--- a/cli/src/lib/deviceErrors.spec.ts+++ b/cli/src/core/cardText.spec.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { deviceErrorText } from './deviceErrors.js'+import { deviceErrorText } from './cardText.js'describe('deviceErrorText', () => {it('makes Claude submit-verification failures device-friendly', () => {@@ -42,5 +42,7 @@ describe('deviceErrorText', () => {// A message with nothing to strip is passed through untouched.expect(deviceErrorText('This agent process is no longer running.', 'pi')).toBe('This agent process is no longer running.')+ // One that is nothing but a link keeps it: an empty card says less than a link nobody can follow.+ expect(deviceErrorText(' https://example.com/status', 'pi')).toBe(' https://example.com/status')})})diff --git a/cli/src/lib/deviceErrors.ts b/cli/src/core/cardText.tssimilarity index 91%rename from cli/src/lib/deviceErrors.tsrename to cli/src/core/cardText.tsindex 1f7edc548..7fa183359 100644--- a/cli/src/lib/deviceErrors.ts+++ b/cli/src/core/cardText.ts@@ -5,6 +5,9 @@* you to check the pane. None of that is actionable on a device — the reader cannot follow a URL, and a* long sentence pushes the one fact that matters off the card. So each rule here keeps the WHAT and the* WHEN and drops the rest, rather than truncating, which cuts the end — where the useful part usually is.+ *+ * The core writes these into the cards it sends every device (core/turns/funnel.ts, core/input.ts), so+ * the text is the core's: a device, in its own process, draws what it is sent.*/const AGENT_DID_NOT_ACCEPT = 'The agent did not accept the message. Please try again.'diff --git a/cli/src/core/deviceInput.edges.spec.ts b/cli/src/core/deviceInput.edges.spec.tsnew file mode 100644index 000000000..14af24f3e--- /dev/null+++ b/cli/src/core/deviceInput.edges.spec.ts@@ -0,0 +1,264 @@+/**+ * The pane writer lock's edges (core/deviceInput.ts): what happens when the agent goes, the queue fills,+ * a write is cancelled or fails part way, or the pane cannot be read. Each is a write into a person's+ * pane that must either happen once or be said not to have happened.+ */+import { afterEach, describe, expect, it, vi } from 'vitest'+import { AutonomousDeviceInput, type DeviceInputDeps } from './deviceInput.js'+import type { RegisteredSession } from '../lib/registry.js'+import type { TerminalActionResult } from '../lib/terminalTypes.js'++afterEach(() => vi.useRealTimers())++const claude = { agentId: 'agent', engine: 'claude' } as RegisteredSession+const codex = (cliVersion?: string) => ({ agentId: 'agent', engine: 'codex', cliVersion }) as RegisteredSession+const executed: TerminalActionResult = { state: 'succeeded', dispatch: 'executed' }++function lock(overrides: Partial<DeviceInputDeps> = {}) {+ const onDelivery = vi.fn()+ const onInputStatus = vi.fn()+ const device = new AutonomousDeviceInput({+ getSession: () => claude,+ validateRuntime: async () => true, inject: async () => executed, sendKey: async () => true,+ capture: async () => '› ', acquireControl: () => () => {}, legacySubmit: vi.fn(), legacyCancel: () => false,+ onDelivery, onInputStatus, ...overrides,+ })+ const states = (deliveryId: string) => onDelivery.mock.calls.map(([event]) => event).filter((event) => event.deliveryId === deliveryId)+ .map((event) => event.reason ? `${event.state}:${event.reason}` : event.state)+ return { device, onDelivery, onInputStatus, states }+}++/** A promise and the hand that settles it. */+function held<T>() {+ let resolve!: (value: T) => void+ let reject!: (error: unknown) => void+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no })+ return { promise, resolve, reject }+}++describe('the pane writer lock, at its edges', () => {+ it('refuses a turn for an agent that is gone, and a queue that is full by count or by size', async () => {+ const gone = lock({ getSession: () => undefined })+ gone.device.submit('agent', 'hello', 'd0')+ expect(gone.states('d0')).toEqual(['rejected:agent_gone'])++ // The pane never comes free, so every turn waits in the queue.+ const busy = lock({ acquireControl: () => null })+ for (let i = 1; i <= 9; i++) busy.device.submit('agent', `turn ${i}`, `d${i}`)+ expect(busy.states('d8')).toEqual(['queued'])+ expect(busy.states('d9')).toEqual(['rejected:queue_full'])+ const big = lock({ acquireControl: () => null })+ big.device.submit('agent', 'x'.repeat(20 * 1024), 'b1')+ big.device.submit('agent', 'y'.repeat(5 * 1024), 'b2')+ expect(big.states('b2')).toEqual(['rejected:queue_full'])+ busy.device.forget('agent')+ big.device.forget('agent')+ })++ it('lets a queued turn expire, and forgets an agent that went while its turn waited', async () => {+ vi.useFakeTimers()+ let session: RegisteredSession | undefined = claude+ let free = false+ const f = lock({ getSession: () => session, acquireControl: () => free ? () => {} : null })+ f.device.submit('agent', 'old', 'old')+ await vi.advanceTimersByTimeAsync(6 * 60_000)+ f.device.submit('agent', 'new', 'new')+ expect(f.states('old')).toEqual(['queued', 'rejected:queue_expired'])+ session = undefined+ free = true+ await vi.advanceTimersByTimeAsync(200)+ expect(f.states('new')).toEqual(['queued', 'rejected:agent_gone'])+ })++ it('waits for a write already in the pane, then writes', async () => {+ vi.useFakeTimers()+ const f = lock()+ const legacy = held<void>()+ const writing = f.device.legacyWrite('agent', () => legacy.promise)+ f.device.submit('agent', 'after the window', 'd1')+ await vi.advanceTimersByTimeAsync(150)+ expect(f.states('d1')).toEqual(['queued'])+ legacy.resolve()+ await writing+ await vi.advanceTimersByTimeAsync(150)+ expect(f.states('d1')).toEqual(['queued', 'delivered'])+ f.device.forget('agent')+ })++ it('refuses before it writes when the agent cannot be checked, or the turn was cancelled meanwhile', async () => {+ const dead = lock({ validateRuntime: async () => false })+ dead.device.submit('agent', 'hello', 'd1')+ await vi.waitFor(() => expect(dead.states('d1')).toEqual(['queued', 'rejected:runtime_gone_pre_paste']))++ const validating = held<boolean>()+ const cancelled = lock({ validateRuntime: () => validating.promise })+ cancelled.device.submit('agent', 'hello', 'd2')+ // Cancelled while it is checked: it is the active write, not yet dispatched, so it can still be withdrawn.+ expect(cancelled.device.cancelDelivery('d2')).toBe(true)+ validating.resolve(true)+ await vi.waitFor(() => expect(cancelled.states('d2')).toEqual(['queued', 'rejected:cancelled']))+ expect(cancelled.device.cancelDelivery('nothing')).toBe(false)++ const asking = held<boolean>()+ let looking = false+ const waiting = lock({ isAwaitingUser: () => { looking = true; return asking.promise } })+ waiting.device.submit('agent', 'hello', 'd3')+ await vi.waitFor(() => expect(looking).toBe(true))+ expect(waiting.device.cancelDelivery('d3')).toBe(true)+ asking.resolve(false)+ await vi.waitFor(() => expect(waiting.states('d3')).toEqual(['queued', 'rejected:cancelled']))++ // A throw while checking, before anything was written, is a refusal too.+ const thrown = lock({ validateRuntime: async () => { throw new Error('ps failed') } })+ thrown.device.submit('agent', 'hello', 'd4')+ await vi.waitFor(() => expect(thrown.states('d4')).toEqual(['queued', 'rejected:runtime_gone_pre_paste']))+ })++ it('writes a turn into a busy Codex as steering on 0.106 and later, and as plain input before it', async () => {+ for (const [version, mode] of [['0.105.2', 'native_input'], [undefined, 'native_input'], ['1.0.0', 'steering']] as const) {+ const f = lock({ getSession: () => codex(version) })+ f.device.onTurnStarted('agent', 'already working')+ f.device.submit('agent', 'and this', 'd1')+ await vi.waitFor(() => expect(f.onInputStatus).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'd1', mode, phase: 'submitted' })))+ f.device.forget('agent')+ }+ })++ it('finishes a write whose turn began while it was being typed', async () => {+ const typing = held<TerminalActionResult>()+ const f = lock({ inject: () => typing.promise })+ f.device.submit('agent', 'hello', 'd1')+ await vi.waitFor(() => expect(f.onInputStatus).toHaveBeenCalledTimes(1))+ f.device.onTurnStarted('agent', 'hello')+ typing.resolve(executed)+ await vi.waitFor(() => expect(f.states('d1')).toEqual(['queued', 'started']))+ // The next turn is not held behind it.+ f.device.submit('agent', 'next', 'd2')+ await vi.waitFor(() => expect(f.states('d2')).toContain('delivered'))+ f.device.forget('agent')+ })++ it('says a write that failed after typing began is unknown, and looks again', async () => {+ vi.useFakeTimers()+ const f = lock({ inject: async () => { throw new Error('tmux went away') }, capture: async () => null })+ f.device.submit('agent', 'hello', 'd1')+ await vi.advanceTimersByTimeAsync(0)+ expect(f.states('d1')).toEqual(['queued', 'unknown:dispatch_ambiguous'])+ // It looks at the pane again: unreadable, it keeps looking, then says it could not confirm.+ await vi.advanceTimersByTimeAsync(20_000)+ expect(f.onInputStatus).toHaveBeenLastCalledWith(expect.objectContaining({ deliveryId: 'd1', phase: 'unconfirmed' }))+ f.device.forget('agent')++ // A write that failed but whose turn started is simply finished.+ const late = lock({ inject: async () => { late.device.onTurnStarted('agent', 'hello'); throw new Error('late') } })+ late.device.submit('agent', 'hello', 'd2')+ await vi.advanceTimersByTimeAsync(0)+ expect(late.states('d2')).toEqual(['queued', 'started'])++ // Forgotten while it was being written: nothing more is said about it.+ const typing = held<TerminalActionResult>()+ const forgotten = lock({ inject: () => typing.promise })+ forgotten.device.submit('agent', 'hello', 'd3')+ await vi.advanceTimersByTimeAsync(0)+ forgotten.device.forget('agent')+ typing.reject(new Error('gone'))+ await vi.advanceTimersByTimeAsync(0)+ expect(forgotten.states('d3')).toEqual(['queued', 'unknown:agent_gone'])+ })++ it('keeps reading a pane that cannot be read, and gives up saying so', async () => {+ vi.useFakeTimers()+ const f = lock({ capture: async () => { throw new Error('capture failed') } })+ f.device.submit('agent', 'hello', 'd1')+ await vi.advanceTimersByTimeAsync(0)+ expect(f.states('d1')).toEqual(['queued', 'delivered', 'unknown:dispatch_ambiguous'])+ await vi.advanceTimersByTimeAsync(20_000)+ expect(f.onInputStatus).toHaveBeenLastCalledWith(expect.objectContaining({ deliveryId: 'd1', phase: 'unconfirmed' }))+ f.device.forget('agent')++ // Forgotten while its pane was being read: the read's answer is not acted on.+ const reading = held<string | null>()+ const gone = lock({ capture: () => reading.promise })+ gone.device.submit('agent', 'hello', 'd2')+ await vi.advanceTimersByTimeAsync(0)+ gone.device.forget('agent')+ reading.resolve('› hello')+ await vi.advanceTimersByTimeAsync(0)+ expect(gone.states('d2')).toEqual(['queued', 'delivered', 'unknown:agent_gone'])++ // A read that fails after the turn started says nothing more.+ const failing = held<string | null>()+ const started = lock({ capture: () => failing.promise })+ started.device.submit('agent', 'hello', 'd3')+ await vi.advanceTimersByTimeAsync(0)+ started.device.onTurnStarted('agent', 'hello')+ failing.reject(new Error('late'))+ await vi.advanceTimersByTimeAsync(0)+ expect(started.states('d3')).toEqual(['queued', 'delivered', 'started'])+ })++ it('does not press Enter again while a question holds the pane', async () => {+ vi.useFakeTimers()+ const sendKey = vi.fn(async () => true)+ let asking = false+ const f = lock({ capture: async () => '› hello', sendKey, isAwaitingUser: async () => asking })+ f.device.submit('agent', 'hello', 'd1')+ await vi.advanceTimersByTimeAsync(0)+ asking = true+ await vi.advanceTimersByTimeAsync(1_600)+ expect(sendKey).not.toHaveBeenCalled()+ f.device.forget('agent')++ // Forgotten while the question was being looked for.+ const looking = held<boolean>()+ let first = true+ const g = lock({ capture: async () => '› hello', sendKey, isAwaitingUser: () => first ? (first = false, Promise.resolve(false)) : looking.promise })+ g.device.submit('agent', 'hello', 'd2')+ await vi.advanceTimersByTimeAsync(1_600)+ g.device.forget('agent')+ looking.resolve(false)+ await vi.advanceTimersByTimeAsync(0)+ expect(sendKey).not.toHaveBeenCalled()+ })++ it('stops looking at a write once its turn starts', async () => {+ vi.useFakeTimers()+ const capture = vi.fn(async () => '› hello')+ const f = lock({ capture })+ f.device.submit('agent', 'hello', 'd1')+ await vi.advanceTimersByTimeAsync(0)+ // Still in the composer when looked at: it is looked at again, until the turn starts.+ const looked = capture.mock.calls.length+ f.device.onTurnStarted('agent', 'hello')+ await vi.advanceTimersByTimeAsync(5_000)+ expect(capture.mock.calls.length).toBe(looked)+ expect(f.states('d1')).toEqual(['queued', 'delivered', 'started'])+ f.device.forget('agent')+ })++ it('looks at a write again when its turn ends before it was seen to start', async () => {+ vi.useFakeTimers()+ const capture = vi.fn(async () => '› hello')+ const f = lock({ capture })+ f.device.onTurnStarted('agent', 'something else')+ f.device.submit('agent', 'hello', 'd1')+ await vi.advanceTimersByTimeAsync(0)+ const looked = capture.mock.calls.length+ f.device.onTurnEnded('agent')+ await vi.advanceTimersByTimeAsync(1_600)+ expect(capture.mock.calls.length).toBeGreaterThan(looked)+ f.device.forget('agent')+ })++ it('withdraws a queued turn, and hands any other to the window\'s queue', () => {+ const legacyCancel = vi.fn(() => true)+ const f = lock({ acquireControl: () => null, legacyCancel })+ f.device.submit('agent', 'first', 'd1')+ f.device.submit('agent', 'second', 'd2')+ expect(f.device.cancelDelivery('d2')).toBe(true)+ expect(f.states('d2')).toEqual(['queued', 'rejected:cancelled'])+ expect(f.device.cancelDelivery('elsewhere')).toBe(true)+ expect(legacyCancel).toHaveBeenCalledWith('elsewhere')+ f.device.forget('agent')+ })+})diff --git a/cli/src/lib/autonomous-device/input.spec.ts b/cli/src/core/deviceInput.spec.tssimilarity index 97%rename from cli/src/lib/autonomous-device/input.spec.tsrename to cli/src/core/deviceInput.spec.tsindex 1ff111878..94b5c0c81 100644--- a/cli/src/lib/autonomous-device/input.spec.ts+++ b/cli/src/core/deviceInput.spec.ts@@ -1,12 +1,12 @@-import { CodexNormalizer } from '../../engines/codex/normalizer.js'-import { lineToEvents, newTurnState, type LiveEvent } from '../normalize.js'+import { CodexNormalizer } from '../engines/codex/normalizer.js'+import { lineToEvents, newTurnState, type LiveEvent } from '../lib/normalize.js'import { randomUUID } from 'node:crypto'import { afterEach, describe, expect, it, vi } from 'vitest'-import { AutonomousDeviceInput, isDeviceInputBoundary, type DeviceInputDeps } from './input.js'-import { SessionInputController } from '../sessionInput.js'-import { AutonomousDeviceService } from './service.js'-import type { RegisteredSession } from '../registry.js'-import type { TerminalActionResult } from '../terminalTypes.js'+import { AutonomousDeviceInput, isDeviceInputBoundary, type DeviceInputDeps } from './deviceInput.js'+import { SessionInputController } from '../lib/sessionInput.js'+import { AutonomousDeviceService } from '../lib/autonomous-device/service.js'+import type { RegisteredSession } from '../lib/registry.js'+import type { TerminalActionResult } from '../lib/terminalTypes.js'function makeDevice(overrides: Partial<DeviceInputDeps>): AutonomousDeviceInput {return new AutonomousDeviceInput({diff --git a/cli/src/lib/autonomous-device/input.ts b/cli/src/core/deviceInput.tssimilarity index 94%rename from cli/src/lib/autonomous-device/input.tsrename to cli/src/core/deviceInput.tsindex 474385021..c6f5b8fa0 100644--- a/cli/src/lib/autonomous-device/input.ts+++ b/cli/src/core/deviceInput.ts@@ -1,9 +1,19 @@+/**+ * The pane writer lock, and the Wi-Fi device's queued turns behind it: one writer at a time into an+ * agent's pane, whoever is writing (a device's turn, a window's message, a team's), and a device turn+ * held until the pane can take it.+ *+ * The core's, not the device's: every write the core makes into a pane takes this lock (core/input.ts),+ * so it has to be where the writes are. It lived beside the Wi-Fi device (lib/autonomous-device/input.ts)+ * until the devices moved into a process of their own (docs/design/2026-10-06-core-boundary-next.md,+ * step 9): a lock that every pane write waits on cannot sit on the far side of a process boundary.+ */import { createHash } from 'node:crypto'-import type { RegisteredSession } from '../registry.js'-import type { SessionInputDelivery } from '../sessionInput.js'-import type { LiveEvent } from '../normalize.js'-import { isMessageHold } from '../messageHold.js'-import { enterWithheldReason, type TerminalActionResult } from '../terminalTypes.js'+import type { RegisteredSession } from '../lib/registry.js'+import type { SessionInputDelivery } from '../lib/sessionInput.js'+import type { LiveEvent } from '../lib/normalize.js'+import { isMessageHold } from '../lib/messageHold.js'+import { enterWithheldReason, type TerminalActionResult } from '../lib/terminalTypes.js'const NATIVE = new Set(['claude', 'codex'])const VERIFY_MS = 1500diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex c1857fc79..920247d1a 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -2,8 +2,8 @@ import { readdirSync, readFileSync } from 'node:fs'import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'import type { CommandCodeNormalizer } from '../engines/commandcode/normalizer.js'-import type { AutonomousDeviceInput } from '../lib/autonomous-device/input.js'-import { deviceErrorText } from '../lib/deviceErrors.js'+import type { AutonomousDeviceInput } from './deviceInput.js'+import { deviceErrorText } from './cardText.js'import type { RegisteredSession } from '../lib/registry.js'import type { SessionInputDelivery } from '../lib/sessionInput.js'import { TERMINAL_LEASE_REFUSED, type TerminalActionResult } from '../lib/terminalTypes.js'diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 04a13691d..15a607268 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -9,10 +9,10 @@* in. The two controllers' dependencies are built by `sessionInputDeps` and `deviceInputDeps`, each given* the other controller lazily: each one calls into the other.*/-import { AutonomousDeviceInput, type DeviceInputDeps } from '../lib/autonomous-device/input.js'+import { AutonomousDeviceInput, type DeviceInputDeps } from './deviceInput.js'import type { AutonomousDeviceService } from '../lib/autonomous-device/service.js'import type { CommandCodeNormalizer } from '../engines/commandcode/normalizer.js'-import { deviceErrorText } from '../lib/deviceErrors.js'+import { deviceErrorText } from './cardText.js'import { adaptSlashCommand } from '../lib/goalCommand.js'import { sid } from '../lib/log.js'import type { LiveEvent } from '../lib/normalize.js'diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex a8a3d5664..f33bbb66b 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -21,12 +21,9 @@ import { env } from '../config/env.js'import { VERSION } from '../version.js'import { sqlitePreflightMessage } from '../lib/sqliteAvailability.js'import { warmLoginShellEnvironment } from '../lib/loginShellEnv.js'-import { DialLog } from '../cable/dialLog.js'-import { CableSession } from '../cable/cableSession.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 type { AppSwarms } from '../cable/cableSession.js'+import type { UnreadNotification } from '../cable/notificationRead.js'+import { terminalActivity } from '../lib/terminalActivity.js'import { MachineListCache, withStaleMarker } from '../device/machineList.js'import { registry, projectDisplayName, validTranscriptPath, type RegisteredSession } from '../lib/registry.js'import { engineSessionTitle } from '../lib/sessionTitle.js'@@ -124,7 +121,7 @@ import { createAgentUpdate } from './agents/update.js'import { createEngineHooks, installEngineHooks } from './engines/hooks.js'import { createCursorTaskHooks } from './engines/cursorTasks.js'import { databaseHistory } from './transcripts/databaseHistory.js'-import { createCoreApi, emptyPorts, EXPERIMENTS, FLEET_FALLBACKS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type TeamsPort } from './api.js'+import { createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'import { createServiceHost, testFaults } from './serviceHost.js'import { startStalls } from './stall.js'import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'@@ -143,7 +140,7 @@ import { createOrchestratorLink } from './orchestratorLink.js'import { daemonCommand } from '../lib/daemonCommand.js'import { KNOWN_SERVICES, servicesTheMasterRuns } from '../harnessd/services.js'import { createTeamsLink, teamsOutOfProcess } from './teamsLink.js'-import { startFleet } from '../services/fleet.js'+import { startDevices } from '../services/devices.js'import { CORE_EXIT_STOP, CORE_EXIT_UPDATE, PROBE_COMMAND, PROBE_TIMEOUT_MS } from '../harnessd/protocol.js'import { localSocketPath, refuseServedDataFolder, type LocalSocketServer } from '../lib/localSocket.js'import { saveDaemonPort } from '../lib/daemonEndpoint.js'@@ -154,12 +151,7 @@ import { createGatewayLink, laneOf } from './gatewayLink.js'import { AutonomousDeviceService } from '../lib/autonomous-device/service.js'import { autonomousDeviceLocalRequest } from '../lib/autonomous-device/localApi.js'import { attachLocalWsServer, LOCAL_WS_PATH, LOCAL_WS_PROTOCOL_VERSION } from '../localWsServer.js'-import { createWindowRouter } from '../cable/windowRoute.js'-import { WindowSelection } from '../cable/windowSelection.js'-import { WindowVisit } from '../cable/windowVisit.js'-import { WindowForm } from '../cable/windowForm.js'import { TERMINAL_BINARY_VERSION } from '../lib/terminalBinary.js'-import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from '../lib/voiceRouter.js'import { isLoopbackRequest, loopbackHosts } from '../lib/loopbackRequest.js'import { startSelfUpdater, restore as restoreUpdate, DOWNLOAD_LIMITS, type Poller } from '../lib/selfUpdate.js'import { managedNodePath } from '../lib/nodeRuntime.js'@@ -198,14 +190,6 @@ 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.-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-/*** The window's tiles, in tile order, as last reported.*@@ -224,8 +208,14 @@ let appPaneAgents: string[] = []* booting (the app no longer waits for its first scan), and an `app_swarms` that lands before the* cable host exists was dropped — the dial then had no tab, drew "Choose a pane" and took no swipe* or voice until the window happened to send its tabs again (measured 2026-10-01: 80 s).+ *+ * Kept by the core, too, because the devices can restart where the windows do not: in a process of+ * their own (step 9), a devices process that starts again is told the desk, the tabs, what is unread+ * and which window has the person's attention, as they stand (services/devices.ts).*/-let appSwarmsLatest: Parameters<DaemonCableHost['setSwarms']>[0] = null+let appSwarmsLatest: AppSwarms | null = null+/** What the window still has unread, kept for the same reason. */+let appUnreadLatest: UnreadNotification[] = []// OpenCode's SQLite store — polled per session by OpencodeReader (no per-session transcript file).const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')@@ -581,11 +571,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {// runtime, replaces it immediately when PID/start-marker changed, and requires two successful misses// before removing it. Probe errors leave the registry untouched.// The voice router needs to know which engines the machine actually runs: a router warmed for an- // engine no agent uses is a worker nobody asked for.+ // engine no agent uses is a worker nobody asked for. It is the devices' (services/devices.ts), which are+ // told again as they start.const syncRecapPool = (): void => {- setVoiceRouterSessions(registry.active())+ ports.devices?.engines(registry.active().map((session) => session.engine))}- syncRecapPool()const runtimeProfiles = new RuntimeProfileManager()// An agent's Model/Effort choices, or every live agent's: what `models_list` answers (services/models.ts)// and the dial's picker reads, so neither can show a catalog the machine would not honour.@@ -617,9 +607,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {const externalEngines = externalProviders()const externalSessions = new ExternalSessions({ providers: externalEngines, excluded: [env.ADAPTER_DATA_DIR], log: (line) => console.warn(line) })const openSessions = new OpenSessions({ providers: externalEngines, log: (line) => console.warn(line) })- // The core's one session manager: the backend link, the gateway's dials and the fleet's lane all take- // their tokens from it, so a refresh in flight is shared rather than raced.+ // The core's one session manager: the backend link, the gateway's dials, the fleet's lane and the dial's+ // transcriber all take their tokens from it, so a refresh in flight is shared rather than raced.const auth = new AuthSessionManager(backendHttpBase())+ /** Whether a dial on this computer is watching it, as the devices last said (`clients.dialWatching`). */+ let dialWatching = false+ /** The last `dial_status` the devices sent the windows: a window that connects afterwards is told it. */+ let lastDialStatus: Record<string, unknown> = { attached: false }+ /** The local socket, once it exists: the window bridges ask one window through it. */+ let localWsServerRef: { sendToWindow(connId: string, frame: { type: string; payload: Record<string, unknown> }): boolean } | null = null// The core's side of the boundary its services stand on, and the ports it reaches them through (core/api.ts).// Delivered turns (core/deliveries.ts): text a feature writes into an agent under a delivery id of its// own, and what becomes of each, told back to whoever made it, in this process or in its own.@@ -665,8 +661,34 @@ async function runForeground(session: AuthSession | null): Promise<void> {},accessToken: (options) => auth.accessToken(options),// The fleet's lane's sessions are the gateway's, which holds this machine's E2EE identity; it starts- // below, before the fleet that seals through it.+ // below, before the devices whose fleet seals through it.lane: laneOf(() => gatewayOps.lane),+ signedIn: () => readAuthSession() !== null,+ environment: () => readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV,+ // Built further down, with the account proxies: read when the devices ask, never now.+ machines: () => machinesNow(),+ machine: {+ id: () => backendRef?.machineId ?? '',+ computerId: () => computerId(),+ name: () => dialMachineName(),+ },+ // The dial's working card: what a Claude Code or Codex pane's footer says, read here so the pane never+ // leaves the core.+ activityText: async (agentId) => {+ const session = registry.resolve(agentId)+ if (!session || (session.engine !== 'claude' && session.engine !== 'codex')) return null+ const screen = await terminals.capture(session, { mode: 'visible', ansi: false })+ return terminalActivity(session.engine, screen.state === 'succeeded' ? screen.value : null)+ },+ // The devices' frames for the windows on this computer, never the cloud (createCoreApi checks their types).+ sendLocal: (frame) => {+ if (frame.type === 'dial_status') lastDialStatus = frame.payload+ backendRef?.sendLocal(frame)+ },+ sendToWindow: (connId, frame) => localWsServerRef?.sendToWindow(connId, frame) ?? false,+ hasWindow: () => backendRef?.hasLocalClient() ?? false,+ devicesChanged: (payload) => backendRef?.send({ type: 'harness_devices_changed', payload }),+ dialWatching: (watching) => { dialWatching = watching },// 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),@@ -833,18 +855,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {let openPaneAgents = new Set<string>()/** Whether the window those tiles belong to is actually in front. See onAppPanes. */let appWindowForeground = true- /**- * Is this agent already in front of somebody at this desk?- *- * Both halves are needed and neither alone is enough: a tile on the tab says WHERE it is, the window- * being in front says whether anyone can see it. The dial used to be told the first half only, so it- * stayed quiet about a turn that finished while the window sat behind a browser — which is the one- * case a notification exists for — and the window, which checks both (`_visibleOnTab`), spoke up.- * Two screens, two answers, from one tab.- */- const alreadyOnScreen = (agentId: string): boolean =>- appWindowForeground && openPaneAgents.has(agentId)- const cableWatchingLocal = (): boolean => cableRef?.isConnected === true+ /** A dial plugged into this computer, as the devices said last (`clients.dialWatching`): kept here so+ * the cards are made for it in line, without asking the devices, which may be in another process. */+ const cableWatchingLocal = (): boolean => dialWatchingconst deviceIsWatching = (): boolean => backend.hasCommander() || cableWatchingLocal() || backend.autonomousDeviceConnected()/** Anyone who can DRAW a question: a device, a cabled dial, or a desktop window on this computer. */@@ -1488,6 +1501,20 @@ async function runForeground(session: AuthSession | null): Promise<void> {gatewayOps.reachable(source !== 'backend' ? null : machines.filter((m) => m.state !== 'offline').map((m) => m.machineId))})+ /**+ * The owner's machines as the devices read them (`CoreApi.account.machines`): this computer alone when+ * signed out, else the backend's answer now. The core's own list takes it first, as its own refresh would,+ * so the windows' fallback and the trust group stay as fresh as the dial's wheel.+ */+ async function machinesNow(): Promise<{ status: number; body: Record<string, unknown> }> {+ const guest = guestMachinesBody()+ if (guest) {+ machineListCache.adopt(guest)+ return { status: 200, body: guest }+ }+ return (await machineListCache.refresh()) ?? { status: 502, body: { error: { code: 'BACKEND_UNREACHABLE' } } }+ }+/*** `GET /api/machines` for local clients, answered from the last known-good list when the backend leg* is down.@@ -1726,119 +1753,76 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The device key log records which sign-in this machine is under: a session from before sign-in epochs// gets one first, adopted so it never starts the log over, and the gateway registers with it then.if (session?.machineId) void ensureSignInEpoch().catch(() => null).then(() => gatewayOps.account(account()))- // The dial, the window bridges and the WiFi device answer for themselves. A throw in any of them is- // logged — at most once a minute each, with a count of the rest (core/turns/funnel.ts) — and goes no- // further: the local socket closes a connection whose frame handler throws, so a device fault left- // unguarded here would disconnect the desktop, again on every pane change.- const devices = outsideConsumers({ prefix: 'devices', faults: testFaults(process.env.HARNESSD_TEST_FAULTS) })+ // The Wi-Fi device answers for itself. A throw in it is logged — at most once a minute, with a count of+ // the rest (core/turns/funnel.ts) — and goes no further: the local socket closes a connection whose frame+ // handler throws, so a device fault left unguarded here would disconnect the desktop, again on every pane+ // change. The dial and the window bridges are the devices' (services/devices.ts), behind their port.+ const wifi = outsideConsumers({ prefix: 'devices', faults: testFaults(process.env.HARNESSD_TEST_FAULTS) })+ /** Which window has the person's attention, as the devices are told it. */+ const windowFocus = (): WindowFocus => ({ voice: appVoiceFocus ?? null, form: appFormWindow ?? null })+ /** ⌘K's answer with no devices to route through. */+ const unrouted = (reason: string): RouteAnswer => ({ agentId: '', machineId: '', name: '', confidence: 0, reason, candidates: [], weighed: 0, machines: 0, via: '' })+ const DEVICES_OFF = 'the devices service is unavailable'- // Spoken tasks go to the WINDOW to be routed, not to the copy of the router in this process.- //- // Built here because both ends need it: the local socket hands it the window's replies, and the cable- // host (built much further down) asks through it. See cable/windowRoute.ts for the two-phase wait and- // why "no window" and "a person is still choosing" must not be the same answer.- const windowRouter = createWindowRouter({- hasWindow: () => backend.hasLocalClient(),- send: (voiceId, text, cmd) => {- // sendLocal, never send: this asks the window in front of the dial to open a palette. Fanning it- // out to the web audience would pop one open on a computer nobody is sitting at.- backend.sendLocal({ type: 'voice_route_request', payload: { voiceId, text, ...(cmd ? { cmd } : {}) } })- console.log(`[route] voice → the window · ${Buffer.byteLength(text, 'utf8')} bytes${cmd ? ` · /${cmd}` : ''}`)- },- log: (line) => console.log(`[cable] ${line}`),- })-- const windowSelection: WindowSelection = new WindowSelection({- focus: () => appVoiceFocus,- send: (connId, payload) => localWsServer.sendToWindow(connId, { type: 'dial_selection', payload }),- })- const windowForm = new WindowForm({- focus: () => appFormWindow,- send: (connId, payload) => localWsServer.sendToWindow(connId, { type: 'dial_form', payload }),- log: (line) => console.log(`[cable] ${line}`),- })- const windowVisit = new WindowVisit({- focus: () => appVoiceFocus,- send: (connId, payload) => localWsServer.sendToWindow(connId, { type: 'dial_visit', payload }),- })const localWsServer = attachLocalWsServer(hookServer, {localSocketServer: localSocket?.server ?? null,services: serviceLinks,- onSelectionReply: (connId, machineId, payload) => devices('window', () => windowSelection.reply(connId, machineId, payload)),- onVisitReply: (connId, machineId, payload) => devices('window', () => windowVisit.reply(connId, machineId, payload)),- onFormReply: (connId, machineId, payload) => devices('window', () => windowForm.reply(connId, machineId, payload)),+ // A window's answer to a bridge's ask, and its comings and goings: the window bridges are the devices'.+ onSelectionReply: (connId, machineId, payload) => ports.devices?.windowReply('selection', connId, machineId, payload),+ onVisitReply: (connId, machineId, payload) => ports.devices?.windowReply('visit', connId, machineId, payload),+ onFormReply: (connId, machineId, payload) => ports.devices?.windowReply('form', connId, machineId, payload),onAppDisconnect: (machineId, connId) => {if (appFormWindow?.connId === connId) appFormWindow = undefinedif (appVoiceFocus?.connId === connId) appVoiceFocus = undefined- devices('window', () => windowForm.disconnected(connId))- devices('window', () => windowSelection.focusChanged())- devices('devices', () => autonomousDeviceService?.appFocus(machineId, null, connId))+ ports.devices?.windowFocus(windowFocus())+ ports.devices?.windowGone(connId)+ wifi('wifi', () => autonomousDeviceService?.appFocus(machineId, null, connId))},// The window and the dial are one desk: opening an agent in the app brings the dial to it, switching// the dial's machine first when the app moved to another one.- onDevicePrepareOpened: (operationId, agentId) => devices('devices', () => deviceStoreRef?.acknowledgeReveal(operationId, agentId)),+ onDevicePrepareOpened: (operationId, agentId) => wifi('wifi', () => deviceStoreRef?.acknowledgeReveal(operationId, agentId)),onAppFocusState: (machineId, agentId, connId, expectedRevision) => {// A delayed automatic selection cannot replace a newer explicit user choice. A device service// that cannot say which choice is newest is one with no choice to protect: refused, as without one.let focusRevision: unknown- devices('devices', () => { focusRevision = autonomousDeviceService?.focusSnapshot().focusRevision })+ wifi('wifi', () => { focusRevision = autonomousDeviceService?.focusSnapshot().focusRevision })if (expectedRevision && focusRevision !== expectedRevision) return falseappFormWindow = { machineId, connId }if (agentId === null) {if (appVoiceFocus?.connId === connId) appVoiceFocus = undefined} else appVoiceFocus = { machineId, agentId, connId }- devices('window', () => windowSelection.focusChanged())- devices('devices', () => autonomousDeviceService?.appFocus(machineId, agentId, connId))+ ports.devices?.windowFocus(windowFocus())+ wifi('wifi', () => autonomousDeviceService?.appFocus(machineId, agentId, connId))},- onAppFocus: (machineId, agentId) => devices('dial', () => { void cableRef?.followApp(machineId, agentId) }),+ onAppFocus: (machineId, agentId) => ports.devices?.appFocus(machineId, agentId),// Everything the window still has unread. Held rather than acted on: the dial is handed it when a// cable attaches, which is the one moment its own drawer is known to be empty.- onAppUnread: (items) => devices('dial', () => { cableHostRef?.setUnread(items); void cableRef?.replaceNotifications(items) }),+ onAppUnread: (items) => {+ appUnreadLatest = items+ ports.devices?.unread(items)+ },// The window looked at a harness, so the dial's drawer row for it is stale.// The dial's own tap already reaches the window (`agent.open`); this is the// return leg, and the pair is what keeps the badge and the pill equal.- onAgentSeen: (agentId, readToken) => devices('dial', () => { void cableRef?.agentSeen(agentId, readToken) }),- // Agents the window has a tile for. A finished turn on one of these is- // already in front of the person, so the dial updates its tile in silence- // rather than beeping about something being looked at.- //- // An OPEN tile counts as seen, deliberately — not a focused one. With four- // tiles on a grid all four are on screen, and asking which one the eye is- // on is a question the window cannot answer honestly anyway.+ onAgentSeen: (agentId, readToken) => ports.devices?.seen(agentId, readToken),// The window's swarms. Relayed to the dial as its own list — the dial names the one on screen above// the agent and offers the rest — and, through setSwarms, what makes the desk strict: a present// window with an empty swarm is an empty carousel, not the whole machine.onAppSwarms: (swarms) => {appSwarmsLatest = swarms- devices('dial', () => {- cableHostRef?.setSwarms(swarms)- void cableRef?.syncSwarms()- void cableRef?.syncAgents()- })+ ports.devices?.swarms(swarms)},onAppTabAgents: (connection, ids) => cleanupTabs.updateWindow(connection, ids),+ // Agents the window has a tile for, in tile order: the dial's ring (services/devices.ts). A finished turn+ // on one of these is already in front of the person, so the dial updates its tile in silence rather+ // than beeping about something being looked at. An OPEN tile counts as seen, deliberately — not a+ // focused one: with four tiles on a grid all four are on screen.onAppPanes: (agentIds, foreground) => {- // ORDER matters here, not just membership. The dial's carousel is built- // around these — tiles first, in tile order — so the thumb walks the same- // grid the eyes are on. `openPaneAgents` below only ever asks "is this- // one on screen", which is why it can stay a set.- //- // THE RING IS A FUNCTION OF THIS LIST, so a change here is a new ring and has to be pushed at once.- // Leaving it to the next tick opened a one-second window with a real failure in it: clicking a rail- // agent that has NO tile yet changes the desk and then immediately follows with the focus, and a- // focus for an agent the dial's CURRENT ring does not walk is dropped on the device — it has no- // column to centre on. The window moved, the dial did not, and nothing anywhere said why.- const deskChanged = agentIds.length !== appPaneAgents.length- || agentIds.some((id, at) => id !== appPaneAgents[at])appPaneAgents = agentIds- // A tile behind a browser is not a tile anybody is looking at. The roster- // does not change when the window loses focus, so without this the dial- // went quiet about work nobody could see — the one case the notification- // is for — while the window, which does check, spoke up. `openPaneAgents`- // below is what `quiet` is read from, so emptying it is how both screens- // come to the same answer.+ // A tile behind a browser is not a tile anybody is looking at: the roster does not change when the+ // window loses focus, so without this the dial went quiet about work nobody could see.appWindowForeground = foreground- devices('dial', () => cableHostRef?.setDesk(agentIds))+ ports.devices?.desk(agentIds, foreground)const next = new Set(agentIds)// Logged on CHANGE only. It fires on every pane add, close and reconnect,// and it is the one place the whole feature is observable from — without@@ -1846,20 +1830,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {const changed = next.size !== openPaneAgents.size || [...next].some((id) => !openPaneAgents.has(id))openPaneAgents = nextif (changed) console.log(`[cable] window tiles: ${next.size ? [...next].map(sid).join(' ') : '(none)'}`)- // 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, 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- devices('dial', () => { status = cableHostRef?.currentDialStatus() })- return status ?? { attached: false }- },+ // fleet's to answer, beside the dial in the devices (services/fleet.ts routeTask), so it answers with+ // the dial absent or off.+ onRouteTask: backend.ownerCommands.onRouteTask = async (text) => ports.devices ? ports.devices.routeTask(text) : unrouted(DEVICES_OFF),+ // A window that connects after the dial did has missed the `dial_status` that announced it: the last one+ // the devices sent, kept here.+ dialStatus: () => lastDialStatus,/** A window changing a device's settings. Addressed by the fleet's id, so a second robot on the same* desk is not dragged along — every other cable command broadcasts on purpose (they all show the@@ -1868,28 +1846,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {* Nothing is answered here. The device replies to its own `settings.set` with the values it now* holds, and that reaches the window as an ordinary `dial_status`.*/- onDialSettings: (id, patch) => devices('dial', () => {- void cableRef?.setSettings(id, patch as Parameters<NonNullable<typeof cableRef>['setSettings']>[1])- .then(result => {- if (!result.ok) console.log(`[cable] settings for ${id || 'no device'}: ${result.error}`)- })- }),+ onDialSettings: (id, patch) => ports.devices?.settings(id, patch),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 = 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- },- onVoiceRouteReply: (voiceId, reply) => devices('window', () => windowRouter.reply(voiceId, reply)),+ // backend.onMessage: that resolves the id against THIS computer's registry, so a remote agent would land+ // as "This harness is no longer available", an error about an agent alive on another machine.+ onRouteSend: backend.ownerCommands.onRouteSend = async (agentId, text) =>+ ports.devices ? ports.devices.routeSend(agentId, text) : { ok: false, machine: '', reason: DEVICES_OFF },+ onVoiceRouteReply: (voiceId, reply) => ports.devices?.voiceReply(voiceId, reply),machineId: backend.machineId,backend,relayPool: gateway.windowRelay,@@ -1899,6 +1863,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Cut to the wire's limit here rather than let the far daemon drop the whole claim over a long name.localClient: () => ({ kind: 'desktop', name: terminalHintMachineName().slice(0, 64), machineId: backend.machineId }),})+ localWsServerRef = localWsServer// Every engine's hooks, pointed at the port the local server actually bound (core/engines/hooks.ts).if (!env.DISABLE_HOOK_INSTALL) installEngineHooks(hookPort, { only: env.HOOK_INSTALL_ENGINES, loginShell: loginShellEnvPromise })gatewayOps.dashboardPort(hookPort) // surfaced to the web (e2e_status) so it can link here to approve@@ -2190,8 +2155,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// A device joined mid-turn (count rise or join generation; no adapter heartbeat) → replay live state.backend.onCommanderJoin = () => { mirror.replayAll(); questionWatcher.reset() } // re-announce an open questionbackend.onCommanderPresenceChanged = (connected) => {- // Warm the voice-router worker while a device is connected.- setVoiceRouterDeviceConnected(connected)+ // Warm the voice-router worker while a device is connected (services/devices.ts).+ ports.devices?.commanders(connected)}// Cancelling a turn (core/turns/cancel.ts).@@ -2440,7 +2405,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {['Share', () => ports.sharing?.stop()],['the local websocket', () => localWsServer.close()], ['the hook server', () => hookServer.close()],['the local socket', () => localSocket?.close()], ['Codex activity', () => codexActivity.close()],- ['the voice router', () => shutdownVoiceRouter()],+ // The serial ports, the lane and the voice router's worker: a port held through the handoff makes the+ // next daemon's dial, and esptool, fail as if the hardware had died.+ ['the devices', () => ports.devices?.stop()],// The successor starts its own viewers for the agents it restores; ours must not hold the ports.['the viewers', () => ports.viewers?.stop()], ['the gateway', () => gateway.stop()],// A graceful close releases the backend's one-machine claim, given a moment before the reclaim.@@ -2460,8 +2427,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()- ports.fleet?.stop()+ void ports.devices?.stop()daemonBoot.updater?.stop()daemonBoot.tuiUpdater?.stop()agentReconciler.stop()@@ -2482,7 +2448,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {await localWsServer.close()hookServer.close()codexActivity.close()- shutdownVoiceRouter()await ports.viewers?.stop()await gateway.stop()await backend.stop()@@ -2494,7 +2459,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {// A core whose master is gone stops, so nothing is left holding the port for a master that is not// there to restart it.coreLink.onMasterGone(() => void shutdown('the harnessd master is gone'))- process.on('exit', () => { shutdownVoiceRouter() })// A machine revocation or invalid SSO refresh ends this adapter session permanently.backend.onRevoked = () => {@@ -2522,111 +2486,26 @@ async function runForeground(session: AuthSession | null): Promise<void> {void shutdown('busy')}- // ── the owner's OTHER machines (services/fleet.ts) ──────────────────────────────────────────────────+ // ── the devices (services/devices.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.- serviceHost.start('fleet', (core, started) => {- startFleet(core, started, {- machines: machineListCache, guestMachines: guestMachinesBody, computerId, machineId: () => backend.machineId,- machineName: dialMachineName, desk: () => appPaneAgents,- autonomousEnv: readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV,- })- }, 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- // pairing, no E2EE, no credential on the device. Everything it can ask for is answered by the machinery- // above — the same registry, the same delivery path, the same router — because a second implementation- // 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.- let devicesStatusRevision = 0- const cableHost = new DaemonCableHost({- activityText: async (agentId) => {- const session = registry.resolve(agentId)- if (!session || (session.engine !== 'claude' && session.engine !== 'codex')) return null- const screen = await terminals.capture(session, { mode: 'visible', ansi: false })- return terminalActivity(session.engine, screen.state === 'succeeded' ? screen.value : null)- },- machineName: dialMachineName,- machineId: () => backend.machineId,- computerId: () => computerId(),- signedIn: () => readAuthSession() !== null,- // 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.- // A notification tap, which asks for a tile of its OWN — see CableHost.openAgent. `reason` rides- // along only when the dial gave one ('question'): the window then brings the agent forward rather- // than opening a tab, and an older window that does not know the field opens one as before.- opened: (machineId, agentId, reason) =>- backend.sendLocal({ type: 'dial_open', payload: { machineId, agentId, ...(reason ? { reason } : {}) } }),- notificationRead: (machineId, agentId, readToken) =>- 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: 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) =>- backend.sendLocal({ type: 'dial_focus', payload: { machineId, agentId } }),- // The dial's swarm pick. Local-only like the two above: a tab is a thing THIS window has.- swarmSelected: (swarmId) => backend.sendLocal({ type: 'dial_swarm', payload: { swarmId } }),- scrolled: (phase, dy, velocity) => backend.sendLocal({ type: 'dial_scroll', payload: { phase, dy, velocity } }),- // Gestures remain local. Device inventory/settings also reach the owner's- // other machines through the encrypted device-management event.- dialStatus: (status) => {- devicesStatusRevision++- backend.sendLocal({ type: 'dial_status', payload: status })- backend.send({ type: 'harness_devices_changed', payload: { status, revision: devicesStatusRevision } })- },- // Words spoken on the overview belong to whichever agent the window's palette picks.- routeInWindow: (text, cmd) => windowRouter.ask(text, cmd),- selectPassage: command => windowSelection.command(command),- clearSelection: () => windowSelection.cancel(),- visit: command => windowVisit.command(command),- clearVisit: () => windowVisit.cancel(),- form: command => windowForm.command(command),- clearForm: () => windowForm.clear(),- log: (line) => console.log(`[cable] ${line}`),- // Which machine an agent is on, and getting there: the fleet's router, through its port (D1).- fleet: () => ports.fleet,- })- cableHostRef = cableHost- backend.harnessDevices = {- status: () => cableHost.currentDialStatus(),- revision: () => devicesStatusRevision,- set: async (id, patch) => cableRef- ? cableRef.setSettings(id, patch)- : { ok: false, error: 'Device service unavailable' },- }- // Anything the window said while this was still being built.- cableHost.setDesk(appPaneAgents)- cableHost.setSwarms(appSwarmsLatest)- // The dial's log now lives with the app's, one file a day — see dialLog.ts. The old unbounded- // `cli/data/dial.log` is cut down to a pointer, for anyone with a bookmark.- const legacyDialLog = join(env.ADAPTER_DATA_DIR, 'dial.log')- if (existsSync(legacyDialLog)) {- try { writeFileSync(legacyDialLog, `moved to ${join(env.HARNESS_LOGS_DIR, 'dial-YYYYMMDD.log')}\n`) } catch { /* best effort */ }- }- 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')), ...testDialDiscovery(process.env.HARNESSD_TEST_DIAL_PORT) })- cableRef = cable+ // The dials on USB, the window bridges they speak through, the fleet's router every turn goes through+ // (⌘K's too) with the lane to the owner's other machines, the voice router and the Devices tab. Behind+ // their port: a device that fails costs the devices, never a session. Deliberately not fatal and not+ // blocking: an unplugged cable is this daemon's ordinary state.+ serviceHost.start('devices', (core, started) => startDevices(core, started, {+ logsDir: env.HARNESS_LOGS_DIR,+ dialSerials: process.env.HARNESS_DIAL_SERIALS?.split(',').map((serial) => serial.trim()).filter(Boolean),+ testDialPort: process.env.HARNESSD_TEST_DIAL_PORT,+ cableDisabled: env.CABLE_DISABLE,+ faults: testFaults(process.env.HARNESSD_TEST_FAULTS),+ }), coreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS)+ // Everything the windows said while the devices were being built, and what the machine runs.+ ports.devices?.desk(appPaneAgents, appWindowForeground)+ ports.devices?.swarms(appSwarmsLatest)+ ports.devices?.unread(appUnreadLatest)+ ports.devices?.windowFocus(windowFocus())+ ports.devices?.engines(registry.active().map((agent) => agent.engine))+ ports.devices?.commanders(backend.hasCommander())const deviceStore = createDeviceStore({ dataDir: env.ADAPTER_DATA_DIR, machineId: backend.machineId,create: input => backend.onCreateAgent!(input),@@ -2642,11 +2521,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {requestAppFocus: (agentId, expiresAt, focusRevision) => backend.sendFirstLocal({type: 'device_focus', payload: { machineId: backend.machineId, agentId, expiresAt, focusRevision },}),- // The dial's own carousel tick, borrowed: ring order and wrap from the cable host, `dial_focus` to- // the window, `app_focus` back. Without a window the forward is a no-op, so say so up front.- stepFocus: (direction, currentAgentId) => backend.hasLocalClient() ? cableHost.stepFocus(direction, currentAgentId) : Promise.resolve('no_app'),+ // The dial's own carousel tick, borrowed from the devices: ring order and wrap from the dial's host,+ // `dial_focus` to the window, `app_focus` back. Without a window the forward is a no-op, so say so up+ // front; without the devices there is no desk to walk.+ stepFocus: (direction, currentAgentId) => !backend.hasLocalClient() ? Promise.resolve('no_app')+ : ports.devices ? ports.devices.stepFocus(direction, currentAgentId) : Promise.resolve('no_agents'),// The dial's touchpad stroke, borrowed the same way: `dial_scroll` to the window's focused terminal.- scroll: (phase, dy, velocity) => { if (!backend.hasLocalClient()) return false; cableHost.scrolled(phase, dy, velocity); return true },+ scroll: (phase, dy, velocity) => { if (!backend.hasLocalClient()) return false; ports.devices?.scroll(phase, dy, velocity); return true },agents: () => {const evidence = new Map(deviceStoreAgents(backend.machineId).map(a => [a.agentId, a]))return registry.advertised().map(s => ({ agentId: s.agentId, name: projectDisplayName(s), engine: s.engine,@@ -2682,69 +2563,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {setInterval(() => ports.workspaces?.sweepUnused(), 12 * 3600_000).unref()- // Every card bound for the WiFi device goes down the cable too, translated once. Teeing beats emitting- // again at each call site: a new event kind reaches the dial the day it reaches the socket.- // The tee runs before the frame is queued for the WiFi device (BackendSocket.sendCommander): a dial- // fault here must cost neither that frame nor whoever is sending it.- backend.onOutboundCommander = (frame) => devices('dial', () => {- autonomousDeviceService?.commander(frame as Record<string, unknown>)- // THIS COMPUTER'S cards, by definition — and every one of them belongs to a tile that is on the- // carousel, because the carousel now spans machines. The old guard dropped them whenever the wheel- // was pointed elsewhere, which would now silence this machine's own agents.- const close = cableQuestionCloseFor(frame as { type?: string; agentId?: string; payload?: { requestId?: string } })- if (close) { void cable.questionClose(close.agentId, close.requestId); return }- const question = cableQuestionFor--(frame as { type?: string; agentId?: string; payload?: { requestId?: string; questions?: unknown } })- if (question) { void cable.question(question.agentId, question.requestId, question.questions); return }- const event = cableEventFor(frame as { type?: string; agentId?: string; payload?: { kind?: string; text?: string; recap?: string } })- // Logged at the fork, not at the send: this is the one place that can answer "did the daemon even- // decide to tell the dial", which is a different question from "did the wire carry it" and was the- // question nobody could answer when the tile stayed idle through a whole turn.- if (env.LOG_FRAMES && frame?.type === 'commander_event') {- console.log(`[cable] tee ${(frame as { payload?: { kind?: string } }).payload?.kind ?? '?'} → ${event ? 'sent' : 'ignored'}`)- }- if (!event) return- if (event.kind === 'processing') void cable.turnStarted(event.agentId, event.text)- else if (event.kind === 'done') void cable.turnDone(event.agentId)- else if (event.kind === 'summary') {- // Quiet when the window already has this agent on screen; silent when the- // turn was a sub-agent's. The tile still updates — the recap is what it- // draws — only the beep and the drawer entry are withheld.- void cable.summary(event.agentId, event.recap || event.text, event.text, alreadyOnScreen(event.agentId), event.subagent)- }- else void cable.turnError(event.agentId, event.text)- })-- // 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.- // 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.- 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.- if (event.kind === 'state') { void cable.syncMachines(); return }- // 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.-- if (event.kind === 'questionClosed') { void cable.questionClose(event.agentId, event.requestId); return }- if (event.kind === 'question') { void cable.question(event.agentId, event.requestId, event.questions); return }- if (event.kind === 'processing') void cable.turnStarted(event.agentId, event.text)- else if (event.kind === 'done') void cable.turnDone(event.agentId)- else if (event.kind === 'summary') {- // Quiet when the window already has this agent on screen; silent when the- // turn was a sub-agent's (decided on its own machine). The tile still- // updates — the recap is what it draws — only the beep and the drawer- // entry are withheld.- void cable.summary(event.agentId, event.recap || event.text, event.text, alreadyOnScreen(event.agentId), event.subagent === true)- }- else void cable.turnError(event.agentId, event.text)- })+ // Every card bound for the Wi-Fi device goes to the devices too: the dial is told what the Wi-Fi device is,+ // in the same order, so the two device surfaces cannot drift. Teeing beats emitting again at each call+ // site: a new kind of card reaches the dial the day it reaches the socket. The tee runs before the frame+ // is queued for the Wi-Fi device (BackendSocket.sendCommander): a device fault here must cost neither+ // that frame nor whoever is sending it, which the guards and the devices' port see to.+ backend.onOutboundCommander = (frame) => {+ wifi('wifi', () => autonomousDeviceService?.commander(frame as Record<string, unknown>))+ ports.devices?.card(frame as Record<string, unknown>)+ }- if (env.CABLE_DISABLE) console.log('[cable] disabled (CABLE_DISABLE=true) — the serial port is left alone')- else cable.start()// Last: every handler is wired and the restored agents are confirmed, so requests that arrived while// starting — a client reconnecting the moment the port answered, the backend's first frames — are// answered now, in order, by the handlers meant to answer them (see BackendSocket.openRequests).diff --git a/cli/src/core/questions.ts b/cli/src/core/questions.tsindex f1305ddcf..95cd658d9 100644--- a/cli/src/core/questions.ts+++ b/cli/src/core/questions.ts@@ -9,7 +9,7 @@*/import { AgentNotifications } from '../lib/agentNotifications.js'import { AskQuestionController, QuestionWatcher, type QuestionAnswerPayload, type QuestionAnswerResult } from '../lib/askQuestion.js'-import type { AutonomousDeviceInput } from '../lib/autonomous-device/input.js'+import type { AutonomousDeviceInput } from './deviceInput.js'import { preview, sid } from '../lib/log.js'import type { RegisteredSession } from '../lib/registry.js'import type { TerminalControl } from './terminals/control.js'diff --git a/cli/src/core/serviceHost.ts b/cli/src/core/serviceHost.tsindex db30d13f0..8cad8a9aa 100644--- a/cli/src/core/serviceHost.ts+++ b/cli/src/core/serviceHost.ts@@ -34,6 +34,14 @@ export function later<T>(value: T): Later<T> {return { [LATER]: value }}+/** A fallback read: whether its member returns a promise (`later`), and what it answers. A service that+ * guards parts of its own the way this host guards services reads its fallbacks with this+ * (services/devicesGuard.ts). */+export function readFallback(fallback: unknown): { deferred: boolean; value: unknown } {+ const deferred = typeof fallback === 'object' && fallback !== null && LATER in fallback+ return { deferred, value: deferred ? (fallback as Later<unknown>)[LATER] : fallback }+}+/** For every member of a port, what the core gets when that member fails or its service is off. */export type PortFallbacks<P> = {[K in keyof P]-?: P[K] extends (...args: never[]) => infer R@@ -112,8 +120,7 @@ export function createServiceHost(ports: CorePorts, options: ServiceHostOptionsconst guard = <K extends PortName>(name: K, port: Port<K>, fallbacks: PortFallbacks<Port<K>>): Port<K> => {const guarded: Record<string, Member> = {}for (const [member, fallback] of Object.entries(fallbacks) as Array<[string, unknown]>) {- const deferred = typeof fallback === 'object' && fallback !== null && LATER in fallback- const value = deferred ? (fallback as Later<unknown>)[LATER] : fallback+ const { deferred, value } = readFallback(fallback)const answer = (cause?: unknown): unknown => {if (value === FAIL) {const error = new ServiceUnavailableError(name, cause)diff --git a/cli/src/core/turns/funnel.spec.ts b/cli/src/core/turns/funnel.spec.tsindex a33e2c5a8..ed1b72d15 100644--- a/cli/src/core/turns/funnel.spec.ts+++ b/cli/src/core/turns/funnel.spec.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { deviceErrorText } from '../../lib/deviceErrors.js'+import { deviceErrorText } from '../cardText.js'import type { RegisteredSession } from '../../lib/registry.js'import { createEventFunnel, funnelFor, outsideConsumers, type FunnelDeps } from './funnel.js'diff --git a/cli/src/core/turns/funnel.ts b/cli/src/core/turns/funnel.tsindex 09868a747..0d2e5e280 100644--- a/cli/src/core/turns/funnel.ts+++ b/cli/src/core/turns/funnel.ts@@ -11,11 +11,11 @@* Moved verbatim out of `runForeground` (the core boundary, step 8: docs/design/2026-10-03-harnessd.md).*/import { correlateAgentEvent } from '../../lib/agentEvent.js'-import type { AutonomousDeviceInput } from '../../lib/autonomous-device/input.js'-import { isDeviceInputBoundary } from '../../lib/autonomous-device/input.js'+import type { AutonomousDeviceInput } from '../deviceInput.js'+import { isDeviceInputBoundary } from '../deviceInput.js'import type { AutonomousDeviceService } from '../../lib/autonomous-device/service.js'import type { CommanderMirror } from '../../lib/commander.js'-import { deviceErrorText } from '../../lib/deviceErrors.js'+import { deviceErrorText } from '../cardText.js'import { preview, sid } from '../../lib/log.js'import type { CursorNormalizer } from '../../engines/cursor/normalizer.js'import type { QuestionWatcher } from '../../lib/askQuestion.js'diff --git a/cli/src/device/machineList.spec.ts b/cli/src/device/machineList.spec.tsindex ee9f09c9f..c842e2308 100644--- a/cli/src/device/machineList.spec.ts+++ b/cli/src/device/machineList.spec.ts@@ -3,7 +3,7 @@// `local` is derived, not declared, and getting it wrong is invisible: every machine — including this// computer's own — silently reads as remote, so the dial's own row goes missing and the daemon opens a// cloud socket to reach agents that are in this very process.-import { mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs'+import { existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { describe, expect, it, vi } from 'vitest'@@ -130,8 +130,20 @@ describe('MachineListCache', () => {it('does not reject when the response is nonsense', async () => {const log = vi.fn()const cache = new MachineListCache(async () => ({ status: 200, body: { nope: true } }), () => 'z', log, DIR())- await expect(cache.refresh()).resolves.toBeUndefined()+ // It says what it read, as it read it (the devices' copy reads the core's this way), and keeps its rows.+ await expect(cache.refresh()).resolves.toEqual({ status: 200, body: { nope: true } })expect(cache.list().source).toBe('local')+ // A read that threw has nothing to say.+ const down = new MachineListCache(async () => { throw new Error('offline') }, () => 'z', log, DIR())+ await expect(down.refresh()).resolves.toBeNull()+ })++ it('writes no file when it is a copy of another list', async () => {+ const dir = DIR()+ const copy = new MachineListCache(async () => ({ status: 200, body: { machines: [{ machineId: 'm1', name: 'Mine' }] } }), () => 'z', vi.fn(), dir, () => null, false)+ await copy.refresh()+ expect(copy.list().machines).toHaveLength(1)+ expect(existsSync(join(dir, 'machines.json'))).toBe(false)})})diff --git a/cli/src/device/machineList.ts b/cli/src/device/machineList.tsindex a25262295..1dffd0027 100644--- a/cli/src/device/machineList.ts+++ b/cli/src/device/machineList.ts@@ -97,6 +97,9 @@ export class MachineListCache {/** The machine row this session belongs to. A machine row is per (user, computer), so it is the one* local fact that tells two ACCOUNTS on this computer apart — see `lastResponse`. */private readonly owner: () => string | null = () => null,+ /** Whether it writes `machines.json`. The core's list does; the devices' own copy reads the file at+ * start, to draw the wheel offline, and leaves writing it to the core, so one file has one writer. */+ private readonly persist = true,) {this.path = machineListCachePath(dataDir)this.loadCache()@@ -148,17 +151,19 @@ export class MachineListCache {* one on the other end of the cable — so an outage downgrades `source` and keeps the last known rows* rather than emptying the wheel.*/- async refresh(): Promise<void> {+ async refresh(): Promise<{ status: number; body: Record<string, unknown> } | null> {let res: { status: number; body: Record<string, unknown> }try {res = await this.fetchMachines()} catch (err) {this.degrade(`unreachable (${(err as Error).message})`)- return+ return null}- if (res.status === 401 || res.status === 403) { this.signedOut(); return }- if (res.status >= 400) { this.degrade(`HTTP ${res.status}`); return }- if (!this.adopt(res.body)) this.degrade('no machines in the response')+ if (res.status === 401 || res.status === 403) this.signedOut()+ else if (res.status >= 400) this.degrade(`HTTP ${res.status}`)+ else if (!this.adopt(res.body)) this.degrade('no machines in the response')+ // What was read, as it was read: the devices' own copy of the list reads it from the core's.+ return res}/**@@ -272,6 +277,7 @@ export class MachineListCache {}private saveCache(): void {+ if (!this.persist) return// `adopt` now runs on every local `/api/machines` too, not just the 60s poll, and this is a// synchronous write on the event loop of a daemon that is streaming terminals. An unchanged list is// the common case, so skip those. `fetchedAt` is deliberately NOT part of the comparison — it movesdiff --git a/cli/src/lib/autonomous-device/service.ts b/cli/src/lib/autonomous-device/service.tsindex 7237431f6..d1e09d88c 100644--- a/cli/src/lib/autonomous-device/service.ts+++ b/cli/src/lib/autonomous-device/service.ts@@ -1,7 +1,7 @@import { DeviceResultPayloadSchema } from './resultContract.js'import { DeviceResultEvidence, inputHash, type ResultEvidence } from './resultEvidence.js'import type { DeviceResultJournal } from './resultJournal.js'-import type { DeviceInputStatus } from './input.js'+import type { DeviceInputStatus } from '../../core/deviceInput.js'import type { AutonomousDeviceStore } from './store.js'import { DEVICE_STORE_CAPABILITIES, DeviceStoreError } from './storeContract.js'import { createHash, randomUUID } from 'node:crypto'diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.tsindex d72f68fd9..d899f6043 100644--- a/cli/src/lib/closeAgentService.ts+++ b/cli/src/lib/closeAgentService.ts@@ -2,7 +2,7 @@import { stripVTControlCharacters } from 'node:util'import { randomUUID } from 'node:crypto'import { teamWriteHold } from './teamWriteHold.js'-import { terminalActivity } from '../cable/terminalActivity.js'+import { terminalActivity } from './terminalActivity.js'import type { RegisteredSession, registry as liveRegistry } from './registry.js'import { terminalRouteKey } from './terminalRuntime.js'import type { StopAgentOptions } from './stopAgentService.js'diff --git a/cli/src/lib/ownerCommands.ts b/cli/src/lib/ownerCommands.tsindex 7a8cd33b7..41cc020fe 100644--- a/cli/src/lib/ownerCommands.ts+++ b/cli/src/lib/ownerCommands.ts@@ -27,7 +27,7 @@ export class OwnerCommands {const agentId = payload.agentIdif (typeof agentId !== 'string' || !agentId.length || agentId.length > 160) return { error: 'INVALID_REQUEST' }if (!this.onRouteSend) return { error: 'UNSUPPORTED' }- return this.onRouteSend(agentId, text)+ return await this.onRouteSend(agentId, text)} catch (error) {return error instanceof CommandBarError? { error: error.code, detail: error.message }diff --git a/cli/src/lib/runtimeActivity.ts b/cli/src/lib/runtimeActivity.tsindex f5135d56c..a69c8eac8 100644--- a/cli/src/lib/runtimeActivity.ts+++ b/cli/src/lib/runtimeActivity.ts@@ -1,6 +1,6 @@import { basename } from 'node:path'import { sessionCodexHome } from './engineHomes.js'-import { terminalActivityReading } from '../cable/terminalActivity.js'+import { terminalActivityReading } from './terminalActivity.js'import { connectCodexControl, type CodexControl } from './codexSessionLifecycle.js'import { codexStoppedGoal } from './codexTurnRecovery.js'import { argvTokens, processRows, type ProcessRow } from './tmux.js'diff --git a/cli/src/cable/terminalActivity.spec.ts b/cli/src/lib/terminalActivity.spec.tssimilarity index 100%rename from cli/src/cable/terminalActivity.spec.tsrename to cli/src/lib/terminalActivity.spec.tsdiff --git a/cli/src/cable/terminalActivity.ts b/cli/src/lib/terminalActivity.tssimilarity index 100%rename from cli/src/cable/terminalActivity.tsrename to cli/src/lib/terminalActivity.tsdiff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.tsindex 1aab0fd61..10e0349b8 100644--- a/cli/src/localWsServer.spec.ts+++ b/cli/src/localWsServer.spec.ts@@ -303,7 +303,7 @@ describe('local CLI WebSocket', () => {ws.close()})- it.each(['local binary', 'remote JSON', 'remote binary', 'route task'] as const)(+ it.each(['local binary', 'remote JSON', 'remote binary'] as const)('keeps later messages behind an unfinished %s operation', async (kind) => {const backend = new FakeBackend(), pending = gate(), entered = gate()const trace: string[] = []@@ -332,11 +332,6 @@ describe('local CLI WebSocket', () => {return relay},} as unknown as LocalWsServerOptions['relayPool'],- async onRouteTask(this: LocalWsServerOptions) {- expect(this.machineId).toBe(machineId)- await first()- return { agentId: '', machineId: '', name: '', confidence: 0, reason: '', candidates: [], weighed: 0, machines: 0, via: '' }- },}))await onceOpen(ws)const connected = onceMessage(ws)@@ -345,7 +340,7 @@ describe('local CLI WebSocket', () => {if (kind.endsWith('binary')) {ws.send(encodeTerminalLocal({ kind: TerminalBinaryKind.input, streamId, seq: 1, bytes: new Uint8Array([97]), compressed: false })!)} else {- ws.send(JSON.stringify({ type: kind === 'route task' ? 'route_task' : 'agents_list', payload: { requestId: 'first', text: 'route me' } }))+ ws.send(JSON.stringify({ type: 'agents_list', payload: { requestId: 'first', text: 'route me' } }))}ws.send(JSON.stringify({ type: 'agents_list', payload: { requestId: 'second' } }))await entered.promise@@ -358,6 +353,43 @@ describe('local CLI WebSocket', () => {},)+ it.each(['route_task', 'route_send'] as const)('answers %s off the ordered chain: a window\'s later frames are never held behind it', async (type) => {+ // The answer is the devices' (the fleet's router), which may be in a process of their own: one that+ // hangs must not hold the window's typing until the request times out.+ const backend = new FakeBackend(), pending = gate(), entered = gate()+ const trace: string[] = []+ const held = async () => { trace.push('route started'); entered.resolve(); await pending.promise; trace.push('route answered') }+ backend.handleLocalFrame = () => { trace.push('next') }+ const ws = new WebSocket(await start(backend, {+ async onRouteTask(this: LocalWsServerOptions) {+ expect(this.machineId).toBe(machineId)+ await held()+ return { agentId: '', machineId: '', name: '', confidence: 0, reason: '', candidates: [], weighed: 0, machines: 0, via: '' }+ },+ async onRouteSend(this: LocalWsServerOptions) {+ expect(this.machineId).toBe(machineId)+ await held()+ return { ok: true as const }+ },+ }))+ await onceOpen(ws)+ const connected = onceMessage(ws)+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))+ await connected+ const answered = new Promise<Frame>((resolve) => ws.on('message', (raw) => {+ const frame = JSON.parse(raw.toString()) as Frame+ if (frame.type === (type === 'route_task' ? 'route_result' : 'route_send_result')) resolve(frame)+ }))+ ws.send(JSON.stringify({ type, payload: { requestId: 'first', agentId: 'a1', text: 'route me' } }))+ ws.send(JSON.stringify({ type: 'agents_list', payload: { requestId: 'second' } }))+ await entered.promise+ await vi.waitFor(() => expect(trace).toEqual(['route started', 'next']))+ pending.resolve()+ expect((await answered).payload).toMatchObject({ requestId: 'first' })+ expect(trace).toEqual(['route started', 'next', 'route answered'])+ ws.close()+ })+it.each(['local JSON', 'local binary', 'remote JSON', 'remote binary'] as const)('closes the socket when %s dispatch fails', async (kind) => {const backend = new FakeBackend()@@ -1004,7 +1036,7 @@ describe('local CLI WebSocket', () => {local = attachLocalWsServer(server, {machineId,backend,- onRouteSend: (agentId, text) => {+ onRouteSend: async (agentId, text) => {sent.push({ agentId, text })return { ok: true as const }},@@ -1042,7 +1074,7 @@ describe('local CLI WebSocket', () => {local = attachLocalWsServer(server, {machineId,backend,- onRouteSend: () => ({ ok: false as const, machine: 'mac-mini', reason: 'the last request to it did not come back' }),+ onRouteSend: async () => ({ ok: false as const, machine: 'mac-mini', reason: 'the last request to it did not come back' }),})await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))const url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/local-ws`diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.tsindex 6fa665c12..9efa4f335 100644--- a/cli/src/localWsServer.ts+++ b/cli/src/localWsServer.ts@@ -97,10 +97,13 @@ export interface LocalWsServerOptions {* It answers for the same reason `route_task` does. The remote leg carries no ack of its own, so a* machine that has gone deaf takes the turn and nothing comes back; with the palette closing silently* on a confident route, that is a spoken instruction that vanishes with no mark anywhere.+ *+ * Answered when the fleet's router has decided, which is beside the dial in the devices: in a process of+ * their own that is a hop, so the answer is awaited off this connection's ordered chain.*/- onRouteSend?: (agentId: string, text: string) => { ok: true } | { ok: false; machine: string; reason: string }+ onRouteSend?: (agentId: string, text: string) => Promise<{ ok: true } | { ok: false; machine: string; reason: string }>/** The dial right now, sent to a window the moment it connects — it may have missed the announcement. */- dialStatus?: () => { attached: boolean; fw?: string; updating?: string }+ dialStatus?: () => Record<string, unknown>/*** A window changed a device's settings. `id` names which device on this desk; the rest of the payload* is the patch, and an absent field is a setting the window is not changing.@@ -590,10 +593,15 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO//// Consumed here like app_focus: it describes a hand at this desk, not anything the machine could// act on.+ //+ // Answered OFF this connection's ordered chain, which carries the terminal's keystrokes: the answer+ // is the devices' (the fleet's router), which may be in a process of their own, and one that hangs+ // must not hold a window's typing until the request times out. Nothing orders on the answer but its+ // request id.if (!isBinary && (options.onRouteTask || options.onRouteSend || options.onVoiceRouteReply)) {if (parsed?.type === 'route_task' && options.onRouteTask) {const onRouteTask = options.onRouteTask- return (async () => {+ void (async () => {const payload = parsed.payload as Record<string, unknown> | undefinedconst requestId = typeof payload?.requestId === 'string' ? payload.requestId : ''const text = typeof payload?.text === 'string' ? payload.text.trim() : ''@@ -608,8 +616,8 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO}}sink.sendFrame({ type: 'route_result', payload: { requestId, ...answer } })- return})()+ return}if (parsed?.type === 'voice_route_reply' && options.onVoiceRouteReply) {const payload = parsed.payload as Record<string, unknown> | undefined@@ -626,25 +634,28 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerOreturn}if (parsed?.type === 'route_send' && options.onRouteSend) {- const payload = parsed.payload as Record<string, unknown> | undefined- const requestId = typeof payload?.requestId === 'string' ? payload.requestId : ''- const agentId = typeof payload?.agentId === 'string' ? payload.agentId : ''- const text = typeof payload?.text === 'string' ? payload.text : ''- let sent: { ok: true } | { ok: false; machine: string; reason: string } =- { ok: false, machine: '', reason: 'nothing to send' }- if (agentId && text) {- try {- sent = options.onRouteSend(agentId, text)- } catch (err) {- sent = { ok: false, machine: '', reason: (err as Error).message.slice(0, 120) }+ const onRouteSend = options.onRouteSend+ void (async () => {+ const payload = parsed.payload as Record<string, unknown> | undefined+ const requestId = typeof payload?.requestId === 'string' ? payload.requestId : ''+ const agentId = typeof payload?.agentId === 'string' ? payload.agentId : ''+ const text = typeof payload?.text === 'string' ? payload.text : ''+ let sent: { ok: true } | { ok: false; machine: string; reason: string } =+ { ok: false, machine: '', reason: 'nothing to send' }+ if (agentId && text) {+ try {+ sent = await onRouteSend.call(options, agentId, text)+ } catch (err) {+ sent = { ok: false, machine: '', reason: (err as Error).message.slice(0, 120) }+ }}- }- sink.sendFrame({- type: 'route_send_result',- payload: sent.ok- ? { requestId, ok: true }- : { requestId, ok: false, machine: sent.machine, reason: sent.reason },- })+ sink.sendFrame({+ type: 'route_send_result',+ payload: sent.ok+ ? { requestId, ok: true }+ : { requestId, ok: false, machine: sent.machine, reason: sent.reason },+ })+ })()return}}diff --git a/cli/src/services/devices.spec.ts b/cli/src/services/devices.spec.tsnew file mode 100644index 000000000..5695202ee--- /dev/null+++ b/cli/src/services/devices.spec.ts@@ -0,0 +1,486 @@+// The devices (services/devices.ts): what the core tells them reaches the dial and the window bridges, what+// they say reaches the core through its API alone, and the fleet failing costs the dial nothing.+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { CableHostWiring } from '../cable/cableHost.js'+import { env } from '../config/env.js'+import { emptyPorts, ServiceUnavailableError, type CoreApi, type CorePorts, type DevicesPort } from '../core/api.js'+import type { FleetEvent } from '../cable/machineFleet.js'+import type { RegisteredSession } from '../lib/registry.js'+import { fakeCore } from '../testing/fakeCore.js'+import type { Fleet, FleetDeps } from './fleet.js'++const seen = vi.hoisted(() => ({+ host: null as unknown as CableHostWiring,+ dial: null as unknown as { onDialStatus(status: unknown): void },+ cable: null as unknown as { args: unknown[]; calls: Array<[string, unknown[]]>; setSettings: (id: string, patch: unknown) => Promise<{ ok: boolean; error?: string }> },+ bridges: {} as Record<string, { wiring: Record<string, (...args: unknown[]) => unknown>; calls: Array<[string, unknown[]]> }>,+ fleet: null as null | { deps: FleetDeps; events: ((event: FleetEvent) => void) | null; fail: boolean },+ voice: { sessions: vi.fn(), connected: vi.fn(), shutdown: vi.fn() },+}))++vi.mock('../cable/cableHost.js', async (real) => {+ const actual = await real<typeof import('../cable/cableHost.js')>()+ return {+ ...actual,+ DaemonCableHost: class extends actual.DaemonCableHost {+ constructor(wiring: CableHostWiring) { super(wiring); seen.host = wiring; seen.dial = this }+ },+ }+})+vi.mock('../cable/cableFleet.js', async (real) => {+ const actual = await real<typeof import('../cable/cableFleet.js')>()+ const recorder = (name: string) => function (this: { calls: Array<[string, unknown[]]> }, ...args: unknown[]) { this.calls.push([name, args]); return Promise.resolve() }+ class FakeCable {+ calls: Array<[string, unknown[]]> = []+ args: unknown[]+ constructor(...args: unknown[]) { this.args = args; seen.cable = this as never }+ start = recorder('start')+ stop = recorder('stop')+ syncAgents = recorder('syncAgents')+ syncSwarms = recorder('syncSwarms')+ syncMachines = recorder('syncMachines')+ followApp = recorder('followApp')+ replaceNotifications = recorder('replaceNotifications')+ agentSeen = recorder('agentSeen')+ question = recorder('question')+ questionClose = recorder('questionClose')+ turnStarted = recorder('turnStarted')+ turnDone = recorder('turnDone')+ summary = recorder('summary')+ turnError = recorder('turnError')+ setSettings = vi.fn(async (id: string, _patch: unknown) => (id === 'usb' ? { ok: true } : { ok: false, error: 'That device is not plugged into this computer.' }))+ }+ return { ...actual, CableFleet: FakeCable }+})+// The window bridges: their wiring is what the devices give them; their own behaviour has its own specs.+for (const [path, name] of [['../cable/windowSelection.js', 'WindowSelection'], ['../cable/windowVisit.js', 'WindowVisit'], ['../cable/windowForm.js', 'WindowForm']] as const) {+ vi.doMock(path, () => ({+ [name]: class {+ calls: Array<[string, unknown[]]> = []+ constructor(wiring: Record<string, (...args: unknown[]) => unknown>) { seen.bridges[name] = { wiring, calls: this.calls } }+ command(...args: unknown[]) { this.calls.push(['command', args]); return Promise.resolve({ ok: true }) }+ cancel(...args: unknown[]) { this.calls.push(['cancel', args]) }+ clear(...args: unknown[]) { this.calls.push(['clear', args]) }+ reply(...args: unknown[]) { this.calls.push(['reply', args]) }+ focusChanged(...args: unknown[]) { this.calls.push(['focusChanged', args]) }+ disconnected(...args: unknown[]) { this.calls.push(['disconnected', args]) }+ },+ }))+}+vi.mock('../cable/windowRoute.js', () => ({+ createWindowRouter: (wiring: Record<string, (...args: unknown[]) => unknown>) => {+ const calls: Array<[string, unknown[]]> = []+ seen.bridges.WindowRouter = { wiring, calls }+ return {+ ask: (...args: unknown[]) => { calls.push(['ask', args]); return Promise.resolve({ t: 'unavailable' }) },+ reply: (...args: unknown[]) => { calls.push(['reply', args]) },+ }+ },+}))+vi.mock('./fleet.js', async (real) => {+ const actual = await real<typeof import('./fleet.js')>()+ return {+ ...actual,+ startFleet: (_core: CoreApi, deps: FleetDeps) => {+ const state = { deps, events: null as ((event: FleetEvent) => void) | null, fail: false }+ seen.fleet = state+ const fleet = new Proxy({} as Fleet, {+ get: (_t, key) => {+ if (key === 'onEvent') return (listener: (event: FleetEvent) => void) => { state.events = listener; return () => {} }+ if (key === 'routeTask') return async (text: string) => ({ agentId: 'a1', machineId: 'm1', name: 'api', confidence: 1, reason: text, candidates: [], weighed: 1, machines: 1, via: 'model' })+ if (key === 'routeSend') return (agentId: string) => agentId === 'far' ? { ok: false, machine: 'mac-mini', reason: 'the last request to it did not come back' }+ : agentId === 'nameless' ? { ok: false, machine: '', reason: 'no such agent' } : { ok: true }+ if (key === 'knows') return () => { if (state.fail) throw new Error('lost'); return true }+ if (key === 'stop') return vi.fn()+ // Any other routing member: unanswered here, and failing once the test says the fleet fails.+ return () => { if (state.fail) throw new Error('lost') }+ },+ })+ return { fleet, router: null }+ },+ }+})+vi.mock('../lib/voiceRouter.js', () => ({+ setVoiceRouterSessions: seen.voice.sessions,+ setVoiceRouterDeviceConnected: seen.voice.connected,+ shutdownVoiceRouter: seen.voice.shutdown,+ routeVoiceTask: vi.fn(),+}))++const { startDevices } = await import('./devices.js')++let dataDir: string+let logs: string[]+beforeEach(() => {+ dataDir = mkdtempSync(join(tmpdir(), 'devices-'))+ logs = []+ seen.bridges = {}+ seen.fleet = null+ vi.clearAllMocks()+})+afterEach(() => {+ rmSync(dataDir, { recursive: true, force: true })+ vi.restoreAllMocks()+})++function start(over: { core?: CoreApi; faults?: string[]; cableDisabled?: boolean; testDialPort?: string } = {}) {+ const core = over.core ?? fakeCore({ dataDir })+ const ports: CorePorts = emptyPorts()+ const onExit = vi.fn()+ const requests = startDevices(core, ports, {+ logsDir: join(dataDir, 'logs'),+ dialSerials: ['E2E'],+ testDialPort: over.testDialPort,+ cableDisabled: over.cableDisabled,+ faults: new Set(over.faults ?? []),+ log: (line) => { logs.push(line) },+ onExit,+ })+ return { core, ports, port: ports.devices as DevicesPort, requests, onExit }+}++const calls = (name: string) => seen.cable.calls.filter(([called]) => called === name).map(([, args]) => args)++describe('the devices, as the core starts them', () => {+ it('fill the devices port, start the dial, and stop the voice router\'s worker with the process', () => {+ const { ports, onExit } = start()+ expect(ports.devices).not.toBeNull()+ expect(calls('start')).toHaveLength(1)+ expect(seen.cable.args[2]).toBe(join(dataDir, 'logs'))+ expect(seen.cable.args[4]).toMatchObject({ serials: ['E2E'] })+ onExit.mock.calls[0][0]()+ expect(seen.voice.shutdown).toHaveBeenCalled()+ })++ it('leave the serial ports alone when told to, and find the end-to-end suite\'s dial where it says', async () => {+ start({ cableDisabled: true, testDialPort: '/dev/ttys042' })+ expect(calls('start')).toHaveLength(0)+ expect(logs).toContain('[cable] disabled (CABLE_DISABLE=true) — the serial port is left alone')+ const options = seen.cable.args[4] as { discover: () => Promise<unknown[]> }+ expect(await options.discover()).toEqual([expect.objectContaining({ path: '/dev/ttys042' })])+ })++ it('cut an old dial log down to a pointer, and carry on when it cannot be written', () => {+ writeFileSync(join(dataDir, 'dial.log'), 'years of lines')+ start()+ expect(readFileSync(join(dataDir, 'dial.log'), 'utf8')).toBe(`moved to ${join(dataDir, 'logs', 'dial-YYYYMMDD.log')}\n`)+ rmSync(join(dataDir, 'dial.log'))+ mkdirSync(join(dataDir, 'dial.log'))+ expect(() => start()).not.toThrow()+ })++ it('log to the console by default, and register the worker\'s stop on the process\'s exit', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const once = vi.spyOn(process, 'once').mockImplementation(() => process)+ startDevices(fakeCore({ dataDir }), emptyPorts(), { logsDir: dataDir, cableDisabled: true })+ expect(log).toHaveBeenCalledWith('[cable] disabled (CABLE_DISABLE=true) — the serial port is left alone')+ expect(once).toHaveBeenCalledWith('exit', expect.any(Function))+ })+})++describe('the dial\'s host, wired to the core', () => {+ it('reads the agents, this computer and the sign-in from the core, and reports a dial attached', async () => {+ const agent = { agentId: 'a1', engine: 'claude' } as RegisteredSession+ const core = fakeCore({ dataDir, agents: { advertised: vi.fn(() => [agent]), displayName: vi.fn(() => 'api'), activityText: vi.fn(async () => 'Reading'), runtimeProfile: vi.fn(() => 'p') } })+ start({ core })+ const w = seen.host+ expect(w.sessions()).toEqual([agent])+ expect(w.displayName(agent)).toBe('api')+ expect(await w.activityText!('a1')).toBe('Reading')+ expect(w.machineName()).toBe('This machine')+ expect(w.machineId()).toBe('machine-1')+ expect(w.computerId()).toBe('computer-1')+ expect(w.signedIn!()).toBe(true)+ expect(await w.accessToken!({ force: true })).toBe('token')+ expect(core.account.accessToken).toHaveBeenCalledWith({ force: true })+ expect(w.environment!()).toBe('prod')+ w.watching!(true)+ expect(core.clients.dialWatching).toHaveBeenCalledWith(true)+ expect(w.runtimeProfile!(agent)).toBe('p')+ w.log('cable: hello')+ expect(logs).toContain('[cable] cable: hello')+ })++ it('reaches an agent here through the core\'s own doors', async () => {+ const { core } = start()+ const w = seen.host+ w.sendTurn('a1', 'hello')+ w.stopTurn('a1')+ w.answer('a1', 'r1', { q: 'Coffee' })+ await w.answerReviewed!({ agentId: 'a1' } as never)+ w.recent('a1', 3)+ w.recentAsks('a1')+ w.updateAgent!('a1', 'opus', 'high')+ await w.listModels!('a1')+ await w.forkAgent!('a1')+ expect(core.turns.send).toHaveBeenCalledWith('a1', 'hello')+ expect(core.turns.stop).toHaveBeenCalledWith('a1')+ expect(core.questions.answer).toHaveBeenCalledWith('a1', 'r1', { q: 'Coffee' })+ expect(core.questions.answerReviewed).toHaveBeenCalledWith({ agentId: 'a1' })+ expect(core.turns.recent).toHaveBeenCalledWith('a1', 3)+ expect(core.turns.asks).toHaveBeenCalledWith('a1')+ expect(core.agents.setRuntime).toHaveBeenCalledWith('a1', 'opus', 'high')+ expect(core.agents.runtimeModels).toHaveBeenCalledWith('a1')+ expect(core.agents.fork).toHaveBeenCalledWith('a1')+ })++ it('tells the windows on this computer what a hand at this desk did, and the owner\'s apps the device status', () => {+ const { core } = start()+ const w = seen.host+ w.opened!('m1', 'a1')+ w.opened!('m1', 'a1', 'question')+ w.notificationRead!('m1', 'a1', 'tok')+ w.forked!('m1', 'a2', 'a1')+ w.focused!('m1', 'a1')+ w.swarmSelected!('t2')+ w.scrolled!('move', 4, 120)+ w.dialStatus!({ attached: true, fw: '1.2.3' })+ w.dialStatus!({ attached: false })+ expect(vi.mocked(core.clients.sendLocal).mock.calls.map(([frame]) => frame)).toEqual([+ { type: 'dial_open', payload: { machineId: 'm1', agentId: 'a1' } },+ { type: 'dial_open', payload: { machineId: 'm1', agentId: 'a1', reason: 'question' } },+ { type: 'dial_notification_read', payload: { machineId: 'm1', agentId: 'a1', readToken: 'tok' } },+ { type: 'dial_forked', payload: { machineId: 'm1', agentId: 'a2', sourceAgentId: 'a1' } },+ { type: 'dial_focus', payload: { machineId: 'm1', agentId: 'a1' } },+ { type: 'dial_swarm', payload: { swarmId: 't2' } },+ { type: 'dial_scroll', payload: { phase: 'move', dy: 4, velocity: 120 } },+ { type: 'dial_status', payload: { attached: true, fw: '1.2.3' } },+ { type: 'dial_status', payload: { attached: false } },+ ])+ expect(vi.mocked(core.clients.devicesChanged).mock.calls).toEqual([+ [{ status: { attached: true, fw: '1.2.3' }, revision: 1 }],+ [{ status: { attached: false }, revision: 2 }],+ ])+ })++ it('speaks to the window through its bridges, and routes through the fleet', async () => {+ const { core } = start()+ const w = seen.host+ await w.routeInWindow!('fix it', 'review')+ await w.selectPassage!({ agentId: 'a1', op: 'begin' })+ w.clearSelection!()+ await w.visit!({ agentId: 'a1', op: 'open' } as never)+ w.clearVisit!()+ await w.form!({ op: 'open' } as never)+ w.clearForm!()+ expect(seen.bridges.WindowRouter.calls).toEqual([['ask', ['fix it', 'review']]])+ expect(seen.bridges.WindowSelection.calls.map(([name]) => name)).toEqual(['command', 'cancel'])+ expect(seen.bridges.WindowVisit.calls.map(([name]) => name)).toEqual(['command', 'cancel'])+ expect(seen.bridges.WindowForm.calls.map(([name]) => name)).toEqual(['command', 'clear'])+ expect(w.fleet!()).not.toBeNull()+ void core+ })+})++describe('the window bridges, wired to the core', () => {+ it('ask the window with the focus the core last gave, one window at a time', () => {+ const { core, port } = start()+ const { WindowSelection: selection, WindowVisit: visit, WindowForm: form, WindowRouter: router } = seen.bridges+ expect(selection.wiring.focus()).toBeUndefined()+ expect(visit.wiring.focus()).toBeUndefined()+ expect(form.wiring.focus()).toBeUndefined()+ port.windowFocus({ voice: { machineId: 'm1', agentId: 'a1', connId: 'w1' }, form: { machineId: 'm1', connId: 'w1' } })+ expect(selection.wiring.focus()).toEqual({ machineId: 'm1', agentId: 'a1', connId: 'w1' })+ expect(visit.wiring.focus()).toEqual({ machineId: 'm1', agentId: 'a1', connId: 'w1' })+ expect(form.wiring.focus()).toEqual({ machineId: 'm1', connId: 'w1' })+ selection.wiring.send('w1', { op: 'begin' })+ visit.wiring.send('w1', { op: 'open' })+ form.wiring.send('w1', { op: 'open' })+ expect(vi.mocked(core.clients.sendToWindow).mock.calls).toEqual([+ ['w1', { type: 'dial_selection', payload: { op: 'begin' } }],+ ['w1', { type: 'dial_visit', payload: { op: 'open' } }],+ ['w1', { type: 'dial_form', payload: { op: 'open' } }],+ ])+ form.wiring.log('form: opened')+ router.wiring.log('route: asked')+ expect(logs).toEqual(expect.arrayContaining(['[cable] form: opened', '[cable] route: asked']))+ expect(router.wiring.hasWindow()).toBe(true)+ router.wiring.send('v1', 'fix it', undefined)+ router.wiring.send('v2', 'fix it', 'review')+ expect(vi.mocked(core.clients.sendLocal).mock.calls.map(([frame]) => frame)).toEqual([+ { type: 'voice_route_request', payload: { voiceId: 'v1', text: 'fix it' } },+ { type: 'voice_route_request', payload: { voiceId: 'v2', text: 'fix it', cmd: 'review' } },+ ])+ expect(logs).toContain('[route] voice → the window · 6 bytes · /review')+ })++ it('hand each window\'s answer to its bridge, and tell them a window left', () => {+ const { port } = start()+ port.windowReply('selection', 'w1', 'm1', { a: 1 })+ port.windowReply('visit', 'w1', 'm1', { b: 2 })+ port.windowReply('form', 'w1', 'm1', { c: 3 })+ port.voiceReply('v1', { t: 'taken' })+ port.windowGone('w1')+ expect(seen.bridges.WindowSelection.calls).toEqual([['reply', ['w1', 'm1', { a: 1 }]], ['focusChanged', []]])+ expect(seen.bridges.WindowVisit.calls).toEqual([['reply', ['w1', 'm1', { b: 2 }]]])+ expect(seen.bridges.WindowForm.calls).toEqual([['reply', ['w1', 'm1', { c: 3 }]], ['disconnected', ['w1']]])+ expect(seen.bridges.WindowRouter.calls).toEqual([['reply', ['v1', { t: 'taken' }]]])+ })+})++describe('what the windows say, reaching the dial', () => {+ it('pushes a changed desk at once, and only a changed one, and says whether a tile is on screen', async () => {+ const { port } = start()+ port.desk(['a1', 'a2'], true)+ port.desk(['a1', 'a2'], true)+ port.desk(['a2', 'a1'], true)+ expect(calls('syncAgents')).toHaveLength(2)+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done', recap: 'fixed it' } })+ port.desk(['a2', 'a1'], false)+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'summary', text: 'done' } })+ port.card({ type: 'commander_event', agentId: 'a9', payload: { kind: 'summary', text: 'done', subagent: true } })+ expect(calls('summary')).toEqual([['a1', 'fixed it', 'done', true, false], ['a1', 'done', 'done', false, false], ['a9', 'done', 'done', false, true]])+ })++ it('passes the tabs, the unread rows, the window\'s focus and what it saw', () => {+ const { port } = start()+ port.swarms({ active: 't1', swarms: [], tiles: [] })+ port.unread([{ agentId: 'a1', machineId: 'm1', text: 'done', question: false }])+ port.appFocus('m1', 'a1')+ port.seen('a1', 'tok')+ expect(seen.cable.calls.map(([name]) => name)).toEqual(['start', 'syncSwarms', 'syncAgents', 'replaceNotifications', 'followApp', 'agentSeen'])+ expect(calls('followApp')).toEqual([['m1', 'a1']])+ expect(calls('agentSeen')).toEqual([['a1', 'tok']])+ })++ it('changes one device\'s settings, and logs a refusal', async () => {+ const { port } = start()+ port.settings('usb', { brightness: 3 })+ port.settings('', { brightness: 3 })+ port.settings('gone', { brightness: 3 })+ await vi.waitFor(() => expect(logs).toContain('[cable] settings for gone: That device is not plugged into this computer.'))+ expect(logs).toContain('[cable] settings for no device: That device is not plugged into this computer.')+ })++ it('translates every card for the devices into the dial\'s calls, and ignores the rest', () => {+ const { port } = start()+ const card = (kind: string) => port.card({ type: 'commander_event', agentId: 'a1', payload: { kind, text: kind } })+ card('processing'); card('done'); card('error'); card('tool')+ port.card({ type: 'commander_question', agentId: 'a1', payload: { requestId: 'r1', questions: [] } })+ port.card({ type: 'commander_question_close', agentId: 'a1', payload: { requestId: 'r1' } })+ port.card({ type: 'agent_deleted', payload: {} })+ expect(seen.cable.calls.map(([name]) => name)).toEqual(['start', 'turnStarted', 'turnDone', 'turnError', 'question', 'questionClose'])+ })++ it('says, with frame logging on, whether each card was teed to the dial', () => {+ const was = env.LOG_FRAMES+ ;(env as { LOG_FRAMES: boolean }).LOG_FRAMES = true+ try {+ const { port } = start()+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'done' } })+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'tool' } })+ port.card({ type: 'commander_event', agentId: 'a1' })+ expect(logs).toEqual(expect.arrayContaining(['[cable] tee done → sent', '[cable] tee tool → ignored', '[cable] tee ? → ignored']))+ } finally {+ ;(env as { LOG_FRAMES: boolean }).LOG_FRAMES = was+ }+ })++ it('logs a dial that throws on a card, and goes on', () => {+ const { port } = start({ faults: ['dial'] })+ port.card({ type: 'commander_event', agentId: 'a1', payload: { kind: 'done' } })+ port.desk(['a1'], true)+ expect(logs).toContain('[devices] dial failed · injected fault: dial')+ expect(calls('turnDone')).toEqual([])+ })+})++describe('the other machines\' cards', () => {+ it('reach the dial through the same calls as this computer\'s', () => {+ start()+ const tell = seen.fleet!.events!+ tell({ machineId: 'm2', kind: 'state', state: 'ready' })+ tell({ machineId: 'm2', kind: 'questionClosed', agentId: 'b1', requestId: 'r1' })+ tell({ machineId: 'm2', kind: 'question', agentId: 'b1', requestId: 'r2', questions: [] })+ tell({ machineId: 'm2', kind: 'processing', agentId: 'b1', text: 'go', recap: '' })+ tell({ machineId: 'm2', kind: 'summary', agentId: 'b1', text: 'done', recap: 'fixed', subagent: true })+ tell({ machineId: 'm2', kind: 'summary', agentId: 'b1', text: 'done', recap: '' })+ expect(seen.cable.calls.map(([name]) => name)).toEqual(['start', 'syncMachines', 'questionClose', 'question', 'turnStarted', 'summary', 'summary'])+ expect(calls('summary')).toEqual([['b1', 'fixed', 'done', false, true], ['b1', 'done', 'done', false, false]])+ })+})++describe('⌘K, the Wi-Fi device\'s borrowed walk, the voice router and stopping', () => {+ it('route a typed task and its send through the fleet, saying why a send was refused', async () => {+ const { port } = start()+ expect(await port.routeTask('fix the parser')).toMatchObject({ agentId: 'a1', reason: 'fix the parser' })+ expect(await port.routeSend('a1', 'go')).toEqual({ ok: true })+ expect(await port.routeSend('far', 'go')).toMatchObject({ ok: false, machine: 'mac-mini' })+ expect(await port.routeSend('nameless', 'go')).toMatchObject({ ok: false, machine: '' })+ expect(logs).toEqual(expect.arrayContaining([+ '[route] ⌘K → a1 · bytes=2',+ '[route] ⌘K → far · bytes=2 · REFUSED: the last request to it did not come back (mac-mini)',+ '[route] ⌘K → nameless · bytes=2 · REFUSED: no such agent',+ ]))+ })++ it('answer ⌘K with no agent list when the fleet did not start, and the dial routes this computer itself', async () => {+ const { port } = start({ faults: ['fleet'] })+ expect(await port.routeTask('anything')).toMatchObject({ agentId: '', reason: 'no agent list yet', candidates: [] })+ expect(await port.routeSend('a1', 'go')).toEqual({ ok: false, machine: '', reason: 'no agent list yet' })+ expect(logs).toContain('[devices] fleet did not start · injected fault: fleet · the devices run without it')+ expect(seen.host.fleet!()).toBeNull()+ await port.stop()+ expect(calls('stop')).toHaveLength(1)+ })++ it('answer the dial\'s routing as unavailable once the fleet fails, so the dial routes by itself', () => {+ start()+ seen.fleet!.fail = true+ expect(() => seen.host.fleet!()!.knows('a1')).toThrow(ServiceUnavailableError)+ })++ it('lend the Wi-Fi device the dial\'s walk and stroke', async () => {+ const { core, port } = start()+ port.desk(['a1', 'a2'], true)+ port.swarms({ active: 't1', swarms: [{ id: 't1', name: 'Tab', agentIds: ['a1', 'a2'], panes: 2 }], tiles: [] })+ vi.mocked(core.agents.advertised).mockReturnValue([{ agentId: 'a1', registeredAt: 1, engine: 'claude' }, { agentId: 'a2', registeredAt: 2, engine: 'claude' }] as RegisteredSession[])+ // The fleet's router is a stand-in here, so the walk is the host's own over the core's agents.+ seen.fleet!.fail = true+ expect(await port.stepFocus('next', 'a1')).toEqual(expect.objectContaining({ agentId: 'a2' }))+ port.scroll('down', 0, 0)+ expect(vi.mocked(core.clients.sendLocal).mock.calls.map(([frame]) => frame.type)).toEqual(['dial_focus', 'dial_scroll'])+ })++ it('tell the voice router the engines here and whether a device watches, and stop everything', async () => {+ const { port } = start()+ port.engines(['claude', 'codex'])+ port.commanders(true)+ expect(seen.voice.sessions).toHaveBeenCalledWith([{ engine: 'claude' }, { engine: 'codex' }])+ expect(seen.voice.connected).toHaveBeenCalledWith(true)+ await port.stop()+ expect(calls('stop')).toHaveLength(1)+ expect(seen.voice.shutdown).toHaveBeenCalled()+ })+})++describe('the devices\' own copy of the machine list', () => {+ it('is read through the core, and writes no file of its own', async () => {+ const machines = vi.fn(async (): Promise<{ status: number; body: Record<string, unknown> }> => ({ status: 200, body: { success: true, data: { machines: [{ machineId: 'm1', computerId: 'computer-1', name: 'Mine', status: 'running' }] } } }))+ start({ core: fakeCore({ dataDir, account: { machines } }) })+ const list = seen.fleet!.deps.machines+ await list.refresh()+ expect(list.list()).toEqual({ source: 'backend', machines: [expect.objectContaining({ machineId: 'm1', local: true })] })+ expect(existsSync(join(dataDir, 'machines.json'))).toBe(false)+ machines.mockResolvedValueOnce({ status: 500, body: {} })+ await list.refresh()+ expect(logs).toContain('[cable] machines: HTTP 500 — showing the last known list')+ expect(seen.fleet!.deps.desk()).toEqual([])+ })+})++describe('the Devices tab', () => {+ it('answers the owner alone: the devices here, and one device\'s settings', async () => {+ const { requests } = start()+ // The dial's own status, as its session reports it to the host, which tells the windows (revision 1).+ seen.dial.onDialStatus({ attached: true, devices: [{ id: 'usb', attached: true, settings: { brightness: 80 } }] })+ const owner = { local: true, owner: true }+ expect(await requests.harness_devices_list({}, { local: false, owner: false })).toEqual({ error: 'OWNER_REQUIRED' })+ expect(await requests.harness_devices_list({}, owner)).toMatchObject({ protocol: 1, revision: 1, status: { attached: true } })+ expect(await requests.harness_device_settings({ id: 'usb', patch: { brightness: 35 } }, owner)).toMatchObject({ ok: true, revision: 1 })+ expect(seen.cable.setSettings).toHaveBeenCalledWith('usb', { brightness: 35 })+ })+})diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.tsnew file mode 100644index 000000000..9d90f578a--- /dev/null+++ b/cli/src/services/devices.ts@@ -0,0 +1,319 @@+/**+ * The devices: the dials on this computer's USB ports, the window bridges they speak through, the fleet's+ * router every turn goes through (⌘K's too), the voice router, and the Devices tab+ * (docs/design/2026-10-06-core-boundary-next.md, "Devices — its own process", step 9).+ *+ * They reach the core only through `CoreApi` and the core reaches them only through `ports.devices`+ * (core/api.ts `DevicesPort`), so that they can run in a process of their own: the serial ports are+ * hardware, a dial speaks whatever its firmware says, and one device failing must cost the devices, never+ * a session. Inside, each part answers for itself (services/devicesGuard.ts): a dial throwing on every+ * frame costs ⌘K nothing, and a fleet that cannot start costs the dial nothing.+ *+ * Where the core used to wire all this inside `runForeground` (before step 9) it now hands over what the+ * windows on this computer say, as it hears it, and every card it sends the devices; the window's desk,+ * tabs, unread rows and focus it keeps, and says again whenever the devices start.+ *+ * The Wi-Fi device is not here yet: it rides the gateway's sessions and joins the devices next (step 10).+ */+import { existsSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { env } from '../config/env.js'+import { DEVICES_REQUESTS, type CoreApi, type CorePorts, type DevicesPort, type RouteAnswer, type SendResult, type ServiceRequests, type WindowFocus } from '../core/api.js'+import { CableFleet, testDialDiscovery, type CableFleetOptions } from '../cable/cableFleet.js'+import { cableEventFor, cableQuestionCloseFor, cableQuestionFor, DaemonCableHost } from '../cable/cableHost.js'+import { CableSession } from '../cable/cableSession.js'+import { DialLog } from '../cable/dialLog.js'+import { DialVerdicts } from '../cable/dialPortVerdicts.js'+import { WindowForm } from '../cable/windowForm.js'+import { createWindowRouter } from '../cable/windowRoute.js'+import { WindowSelection } from '../cable/windowSelection.js'+import { WindowVisit } from '../cable/windowVisit.js'+import { MachineListCache } from '../device/machineList.js'+import { harnessDevicesRequest } from '../lib/harnessDevices.js'+import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from '../lib/voiceRouter.js'+import { createPartGuard } from './devicesGuard.js'+import { FLEET_FALLBACKS, startFleet, type Fleet } from './fleet.js'++export { DEVICES_REQUESTS }++/** What the devices need that is not the core's to give. */+export interface DevicesDeps {+ /** Where each dial keeps its log, one file a day (cable/dialLog.ts). */+ logsDir: string+ /** The dials to look at, by serial number (`HARNESS_DIAL_SERIALS`); every one when empty. */+ dialSerials?: string[]+ /** The end-to-end suite's dial, a pseudo-terminal (`HARNESSD_TEST_DIAL_PORT`). */+ testDialPort?: string+ /** Leave the serial ports alone altogether (`CABLE_DISABLE`). */+ cableDisabled?: boolean+ /** `HARNESSD_TEST_FAULTS`: parts to fail, for the end-to-end suite. */+ faults?: ReadonlySet<string>+ log?: (line: string) => void+ /** How the voice router's worker is stopped when the process exits: an engine process of its own. */+ onExit?: (run: () => void) => void+ /** For this service's tests: the dial's session, and how dials are found and opened. */+ Session?: ConstructorParameters<typeof CableFleet>[0]+ cable?: Partial<CableFleetOptions>+}++/** ⌘K's answer while the fleet is not running: it never started, so there is no list to weigh. */+const NO_AGENT_LIST = 'no agent list yet'+const unrouted = (reason: string): RouteAnswer => ({ agentId: '', machineId: '', name: '', confidence: 0, reason, candidates: [], weighed: 0, machines: 0, via: '' })+const sid = (id: string): string => id.slice(0, 8)++export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps): ServiceRequests {+ const log = deps.log ?? ((line: string) => console.log(line))+ const part = createPartGuard({ log, faults: deps.faults })++ // What the windows on this computer last said: the desk the dial walks and whether it is in front, and+ // which window has the person's attention for a spoken selection, a visit or a form.+ let desk: string[] = []+ let foreground = true+ let onScreen = new Set<string>()+ let focus: WindowFocus = { voice: null, form: null }+ /**+ * Is this agent already in front of somebody at this desk?+ *+ * Both halves are needed and neither alone is enough: a tile on the tab says WHERE it is, the window+ * being in front says whether anyone can see it. The dial used to be told the first half only, so it+ * stayed quiet about a turn that finished while the window sat behind a browser — which is the one+ * case a notification exists for — and the window, which checks both (`_visibleOnTab`), spoke up.+ */+ const alreadyOnScreen = (agentId: string): boolean => foreground && onScreen.has(agentId)++ // ── the fleet: the owner's other machines, and the router every turn goes through ────────────────────+ //+ // The devices' own copy of the machine list, read through the core, which keeps the list the windows and+ // the trust group read; this copy writes no file of its own, so `machines.json` has one writer.+ const machines = new MachineListCache(() => core.account.machines(), () => core.machine.computerId(),+ (line) => log(`[cable] ${line}`), core.dataDir, () => null, false)+ const fleet: Fleet | null = part.start('fleet', () => startFleet(core, { machines, desk: () => desk }).fleet, FLEET_FALLBACKS)++ // ── the window bridges ─────────────────────────────────────────────────────────────────────────────+ //+ // Spoken tasks go to the WINDOW to be routed, not to the copy of the router in this process. See+ // cable/windowRoute.ts for the two-phase wait and why "no window" and "a person is still choosing" must+ // not be the same answer.+ const windowRouter = createWindowRouter({+ hasWindow: () => core.clients.hasWindow(),+ send: (voiceId, text, cmd) => {+ // To the windows on this computer, never the cloud: this asks the window in front of the dial to+ // open a palette, and fanning it out would pop one open on a computer nobody is sitting at.+ core.clients.sendLocal({ type: 'voice_route_request', payload: { voiceId, text, ...(cmd ? { cmd } : {}) } })+ log(`[route] voice → the window · ${Buffer.byteLength(text, 'utf8')} bytes${cmd ? ` · /${cmd}` : ''}`)+ },+ log: (line) => log(`[cable] ${line}`),+ })+ const windowSelection = new WindowSelection({+ focus: () => focus.voice ?? undefined,+ send: (connId, payload) => core.clients.sendToWindow(connId, { type: 'dial_selection', payload }),+ })+ const windowForm = new WindowForm({+ focus: () => focus.form ?? undefined,+ send: (connId, payload) => core.clients.sendToWindow(connId, { type: 'dial_form', payload }),+ log: (line) => log(`[cable] ${line}`),+ })+ const windowVisit = new WindowVisit({+ focus: () => focus.voice ?? undefined,+ send: (connId, payload) => core.clients.sendToWindow(connId, { type: 'dial_visit', payload }),+ })++ // ── the dial on the USB cable ──────────────────────────────────────────────────────────────────────+ //+ // A device surface served entirely over a wire the user physically owns: no backend, no pairing, no+ // E2EE, no credential on the device. Everything it can ask for is answered by the core through its API —+ // the same registry, the same delivery path — and by the fleet's router, because a second+ // implementation of any of those is a second set of bugs.+ let revision = 0+ const cableHost = new DaemonCableHost({+ sessions: () => core.agents.advertised(),+ displayName: (session) => core.agents.displayName(session),+ activityText: (agentId) => core.agents.activityText(agentId),+ machineName: () => core.machine.name(),+ machineId: () => core.machine.id(),+ computerId: () => core.machine.computerId(),+ signedIn: () => core.account.signedIn(),+ accessToken: (opts) => core.account.accessToken(opts),+ environment: () => core.account.environment(),+ watching: (on) => core.clients.dialWatching(on),+ // The core's own doors for a local agent. The fleet's router reaches them the same way; the dial uses+ // these only when it routes by itself, with the fleet off.+ 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),+ runtimeProfile: (session) => core.agents.runtimeProfile(session),+ updateAgent: (agentId, model, effort) => core.agents.setRuntime(agentId, model, effort),+ listModels: (agentId) => core.agents.runtimeModels(agentId),+ // Each of these is for the windows on this computer alone: 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.+ // A notification tap asks for a tile of its OWN (see CableHost.openAgent). `reason` rides along only+ // when the dial gave one ('question'): the window then brings the agent forward rather than opening a+ // tab, and an older window that does not know the field opens one as before.+ opened: (machineId, agentId, reason) =>+ core.clients.sendLocal({ type: 'dial_open', payload: { machineId, agentId, ...(reason ? { reason } : {}) } }),+ notificationRead: (machineId, agentId, readToken) =>+ core.clients.sendLocal({ type: 'dial_notification_read', payload: { machineId, agentId, readToken } }),+ forked: (machineId, agentId, sourceAgentId) => core.clients.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: (agentId) => core.agents.fork(agentId),+ focused: (machineId, agentId) => core.clients.sendLocal({ type: 'dial_focus', payload: { machineId, agentId } }),+ swarmSelected: (swarmId) => core.clients.sendLocal({ type: 'dial_swarm', payload: { swarmId } }),+ scrolled: (phase, dy, velocity) => core.clients.sendLocal({ type: 'dial_scroll', payload: { phase, dy, velocity } }),+ // Gestures stay at this desk. The device inventory and its settings also reach the owner's other+ // machines, through the encrypted device-management event.+ dialStatus: (status) => {+ revision+++ core.clients.sendLocal({ type: 'dial_status', payload: status as unknown as Record<string, unknown> })+ core.clients.devicesChanged({ status, revision })+ },+ // Words spoken on the overview belong to whichever agent the window's palette picks.+ routeInWindow: (text, cmd) => windowRouter.ask(text, cmd),+ selectPassage: (command) => windowSelection.command(command),+ clearSelection: () => windowSelection.cancel(),+ visit: (command) => windowVisit.command(command),+ clearVisit: () => windowVisit.cancel(),+ form: (command) => windowForm.command(command),+ clearForm: () => windowForm.clear(),+ log: (line) => log(`[cable] ${line}`),+ // Which machine an agent is on, and getting there: the fleet's router, guarded. Null when it never+ // started; a member that fails answers "unavailable", and the host routes this computer by itself.+ fleet: () => fleet,+ })+ // The dial's log lives with the app's, one file a day (dialLog.ts). The old unbounded `dial.log` in the+ // data folder is cut down to a pointer, for anyone with a bookmark.+ const legacyDialLog = join(core.dataDir, 'dial.log')+ if (existsSync(legacyDialLog)) {+ try { writeFileSync(legacyDialLog, `moved to ${join(deps.logsDir, 'dial-YYYYMMDD.log')}\n`) } catch { /* best effort */ }+ }+ const cable = new CableFleet(deps.Session ?? CableSession, cableHost, deps.logsDir, DialLog, {+ serials: deps.dialSerials,+ verdicts: new DialVerdicts(join(core.dataDir, 'dial-ports.json')),+ ...testDialDiscovery(deps.testDialPort),+ ...deps.cable,+ })++ /** One card for the dial, in its four calls. A remote machine's and this computer's are the same calls,+ * so a new kind of card lands on both the day it lands on either. */+ const toDial = (event: NonNullable<ReturnType<typeof cableEventFor>>): void => {+ if (event.kind === 'processing') void cable.turnStarted(event.agentId, event.text)+ else if (event.kind === 'done') void cable.turnDone(event.agentId)+ // Quiet when the window already has this agent on screen; silent when the turn was a sub-agent's. The+ // tile still updates — the recap is what it draws — only the beep and the drawer entry are withheld.+ else if (event.kind === 'summary') void cable.summary(event.agentId, event.recap || event.text, event.text, alreadyOnScreen(event.agentId), event.subagent)+ else void cable.turnError(event.agentId, event.text)+ }++ // A remote machine's cards reach the dial through the same calls. 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.+ fleet?.onEvent((event) => part.call('dial', () => {+ // A `state` event is about the WHEEL, not about a turn — live machine presence, which matters whichever+ // machine is selected. No selection guard on the rest: every machine's agents are on the carousel at+ // once, and dropping a card from one the wheel is not pointed at is what a tile that never leaves+ // "Working…" looks like from the outside.+ if (event.kind === 'state') { void cable.syncMachines(); return }+ if (event.kind === 'questionClosed') { void cable.questionClose(event.agentId, event.requestId); return }+ if (event.kind === 'question') { void cable.question(event.agentId, event.requestId, event.questions); return }+ toDial({ ...event, subagent: event.subagent === true })+ }))++ if (deps.cableDisabled) log('[cable] disabled (CABLE_DISABLE=true) — the serial port is left alone')+ else cable.start()+ ;(deps.onExit ?? ((run) => { process.once('exit', run) }))(() => shutdownVoiceRouter())++ const port: DevicesPort = {+ // Every card bound for the Wi-Fi devices goes down the cable too, translated once: a new kind of card+ // reaches the dial the day it reaches the backend's devices.+ card: (frame) => part.call('dial', () => {+ const close = cableQuestionCloseFor(frame as Parameters<typeof cableQuestionCloseFor>[0])+ if (close) { void cable.questionClose(close.agentId, close.requestId); return }+ const question = cableQuestionFor(frame as Parameters<typeof cableQuestionFor>[0])+ if (question) { void cable.question(question.agentId, question.requestId, question.questions); return }+ const event = cableEventFor(frame as Parameters<typeof cableEventFor>[0])+ // Logged at the fork, not at the send: this answers "did the daemon even decide to tell the dial",+ // a different question from "did the wire carry it", and the one nobody could answer when a tile+ // stayed idle through a whole turn.+ if (env.LOG_FRAMES && frame.type === 'commander_event') {+ log(`[cable] tee ${(frame as { payload?: { kind?: string } }).payload?.kind ?? '?'} → ${event ? 'sent' : 'ignored'}`)+ }+ if (event) toDial(event)+ }),+ desk: (agentIds, front) => {+ // ORDER matters, not just membership: the dial's carousel is the tiles, in tile order, so the thumb+ // walks the grid the eyes are on, and a change is a new ring, pushed at once. Left to the next tick,+ // a click on an agent with no tile yet (which changes the desk, then focuses) reached the dial before+ // its ring had a column for it, and the dial dropped the focus.+ const changed = agentIds.length !== desk.length || agentIds.some((id, at) => id !== desk[at])+ desk = [...agentIds]+ foreground = front+ onScreen = new Set(agentIds)+ part.call('dial', () => cableHost.setDesk(agentIds))+ if (changed) part.call('dial', () => cable.syncAgents())+ },+ // Null is the window gone: an empty desk with a window behind it is an empty tab, with none a shut app.+ swarms: (swarms) => part.call('dial', () => {+ cableHost.setSwarms(swarms)+ void cable.syncSwarms()+ void cable.syncAgents()+ }),+ // Held rather than acted on: the dial is handed it when it attaches, the one moment its drawer is known+ // to be empty.+ unread: (items) => part.call('dial', () => {+ cableHost.setUnread(items)+ void cable.replaceNotifications(items)+ }),+ appFocus: (machineId, agentId) => part.call('dial', () => cable.followApp(machineId, agentId)),+ // The window looked at a harness: the dial's drawer row for it is stale.+ seen: (agentId, readToken) => part.call('dial', () => cable.agentSeen(agentId, readToken)),+ // Addressed to one device by the fleet's id: a preference belongs to the glass it was set on. Nothing is+ // answered here; the device's own `settings.state` reaches the windows as an ordinary `dial_status`.+ settings: (id, patch) => part.call('dial', () => cable.setSettings(id, patch as Parameters<CableFleet['setSettings']>[1])+ .then((result) => { if (!result.ok) log(`[cable] settings for ${id || 'no device'}: ${result.error}`) })),+ windowFocus: (next) => {+ focus = next+ part.call('window', () => windowSelection.focusChanged())+ },+ windowReply: (kind, connId, machineId, payload) => part.call('window', () =>+ (kind === 'form' ? windowForm : kind === 'visit' ? windowVisit : windowSelection).reply(connId, machineId, payload)),+ voiceReply: (voiceId, reply) => part.call('window', () => windowRouter.reply(voiceId, reply)),+ windowGone: (connId) => part.call('window', () => {+ windowForm.disconnected(connId)+ windowSelection.focusChanged()+ }),+ // ⌘K in the window: a typed task, and which agent it belongs to, on any of the owner's machines.+ routeTask: async (text) => fleet ? fleet.routeTask(text) : unrouted(NO_AGENT_LIST),+ // Committed, through the fleet's router — the dial's own dispatch — so a remote agent is reached on its+ // own machine instead of being looked for in this computer's registry.+ routeSend: async (agentId, text): Promise<SendResult> => {+ const sent = fleet?.routeSend(agentId, text) ?? { ok: false as const, machine: '', reason: NO_AGENT_LIST }+ log(`[route] ⌘K → ${sid(agentId)} · bytes=${Buffer.byteLength(text, 'utf8')}`+ + (sent.ok ? '' : ` · REFUSED: ${sent.reason}${sent.machine ? ` (${sent.machine})` : ''}`))+ return sent+ },+ // The Wi-Fi device borrows the dial's walk along the desk and its stroke, until it is one of the devices.+ stepFocus: (direction, currentAgentId) => cableHost.stepFocus(direction, currentAgentId),+ scroll: (phase, dy, velocity) => cableHost.scrolled(phase, dy, velocity),+ // The voice router warms a worker on an engine the machine runs, while a device is watching.+ engines: (engines) => setVoiceRouterSessions(engines.map((engine) => ({ engine }))),+ commanders: (connected) => setVoiceRouterDeviceConnected(connected),+ // The serial ports first: a port left held makes esptool fail in a way that reads like dead hardware.+ stop: async () => {+ await cable.stop()+ fleet?.stop()+ shutdownVoiceRouter()+ },+ }+ ports.devices = port++ // The Devices tab: physical devices belong to this machine, and only its owner may manage them.+ const tab = {+ status: () => cableHost.currentDialStatus(),+ revision: () => revision,+ set: (id: string, patch: Parameters<CableFleet['setSettings']>[1]) => cable.setSettings(id, patch),+ }+ const answer = (type: string) => (payload: Record<string, unknown>, asker: { owner: boolean }) =>+ asker.owner ? harnessDevicesRequest(tab, type, payload) : { error: 'OWNER_REQUIRED' }+ return { harness_devices_list: answer('harness_devices_list'), harness_device_settings: answer('harness_device_settings') }+}diff --git a/cli/src/services/devicesGuard.spec.ts b/cli/src/services/devicesGuard.spec.tsnew file mode 100644index 000000000..234c46210--- /dev/null+++ b/cli/src/services/devicesGuard.spec.ts@@ -0,0 +1,150 @@+// The devices' own guards (services/devicesGuard.ts): one part failing costs that part, never the others.+import { afterEach, describe, expect, it, vi } from 'vitest'+import { FAIL, later, ServiceUnavailableError, type PortFallbacks } from '../core/api.js'+import { createPartGuard } from './devicesGuard.js'++afterEach(() => vi.restoreAllMocks())++describe('a notice into a part', () => {+ it('runs it, and logs a throw or a rejection once a minute with a count of the rest', async () => {+ let at = 0+ const log = vi.fn()+ const guard = createPartGuard({ log, now: () => at })+ const ran = vi.fn()+ guard.call('dial', ran)+ expect(ran).toHaveBeenCalledOnce()+ guard.call('dial', () => { throw new Error('unplugged') })+ guard.call('dial', () => { throw new Error('unplugged') })+ guard.call('dial', () => Promise.reject(new Error('later')))+ await Promise.resolve()+ expect(log.mock.calls).toEqual([['[devices] dial failed · unplugged']])+ // Each part is counted on its own, and a thrown non-error is said as it is.+ guard.call('window', () => { throw 'gone' })+ expect(log).toHaveBeenLastCalledWith('[devices] window failed · gone')+ at = 61_000+ guard.call('dial', () => { throw new Error('still') })+ expect(log).toHaveBeenLastCalledWith('[devices] dial failed · still · 2 more since')+ // A promise that settles well is nothing to say.+ guard.call('dial', () => Promise.resolve('fine'))+ await Promise.resolve()+ expect(log).toHaveBeenCalledTimes(3)+ })++ it('fails every call into a part the end-to-end suite names, and says so on the console by default', () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const guard = createPartGuard({ faults: new Set(['dial']) })+ const ran = vi.fn()+ guard.call('dial', ran)+ guard.call('window', ran)+ expect(ran).toHaveBeenCalledOnce()+ expect(error).toHaveBeenCalledWith('[devices] dial failed · injected fault: dial')+ })+})++interface Router {+ knows(agentId: string): boolean+ total(): number+ list(): Promise<string[]>+ named(): Promise<string>+ stop(): void+}++const FALLBACKS: PortFallbacks<Router> = { knows: FAIL, total: 0, list: later(FAIL), named: later('nobody'), stop: undefined }++describe('a part with members', () => {+ const router = (over: Partial<Router> = {}): Router => ({+ knows: () => true, total: () => 3, list: async () => ['a'], named: async () => 'Ada', stop: vi.fn(), ...over,+ })++ it('answers through its members while they answer', async () => {+ const guard = createPartGuard({ log: vi.fn() })+ const part = guard.start('fleet', () => router(), FALLBACKS)!+ expect(part.knows('a')).toBe(true)+ expect(part.total()).toBe(3)+ expect(await part.list()).toEqual(['a'])+ expect(await part.named()).toBe('Ada')+ expect(guard.isOff('fleet')).toBe(false)+ })++ it('is left off when its start throws, or the suite says so', () => {+ const log = vi.fn()+ const guard = createPartGuard({ log, faults: new Set(['lane']) })+ expect(guard.start('fleet', () => { throw new Error('no identity') }, FALLBACKS)).toBeNull()+ expect(guard.start('lane', () => router(), FALLBACKS)).toBeNull()+ expect(log.mock.calls).toEqual([+ ['[devices] fleet did not start · no identity · the devices run without it'],+ ['[devices] lane did not start · injected fault: lane · the devices run without it'],+ ])+ expect(guard.isOff('fleet')).toBe(true)+ })++ it('answers a failing member with its fallback: FAIL as unavailable, a value as itself, a promise as either', async () => {+ const log = vi.fn()+ const guard = createPartGuard({ log, faults: new Set(['fleet.total']) })+ const part = guard.start('fleet', () => router({+ knows: () => { throw new Error('lost') },+ list: async () => { throw new Error('rpc') },+ named: () => { throw new Error('sync throw') },+ }), FALLBACKS)!+ expect(() => part.knows('a')).toThrow(ServiceUnavailableError)+ expect(part.total()).toBe(0)+ await expect(part.list()).rejects.toBeInstanceOf(ServiceUnavailableError)+ expect(await part.named()).toBe('nobody')+ expect(log.mock.calls.map(([line]) => line)).toEqual([+ '[devices] fleet.knows failed · lost',+ '[devices] fleet.total failed · injected fault: fleet.total',+ '[devices] fleet.list failed · rpc',+ '[devices] fleet.named failed · sync throw',+ ])+ })++ it('is switched off, and stopped, after five failures in a minute: then only its fallbacks answer', async () => {+ let at = 0+ const log = vi.fn()+ const stop = vi.fn()+ const knows = vi.fn(() => { throw new Error('lost') })+ const guard = createPartGuard({ log, now: () => at })+ const part = guard.start('fleet', () => router({ knows, stop }), FALLBACKS)!+ for (let i = 0; i < 4; i++) { at += 20_000; expect(() => part.knows('a')).toThrow(ServiceUnavailableError) }+ // Spread over more than a minute: the oldest has aged out, so it is not off yet.+ expect(guard.isOff('fleet')).toBe(false)+ for (let i = 0; i < 2; i++) expect(() => part.knows('a')).toThrow(ServiceUnavailableError)+ expect(guard.isOff('fleet')).toBe(true)+ expect(stop).toHaveBeenCalledOnce()+ expect(log).toHaveBeenCalledWith('[devices] fleet switched off after 5 failures in 60s · it stays off until the devices restart')+ // Off: nothing reaches it any more.+ knows.mockClear()+ expect(() => part.knows('a')).toThrow(ServiceUnavailableError)+ expect(part.total()).toBe(0)+ expect(await part.named()).toBe('nobody')+ expect(knows).not.toHaveBeenCalled()+ })++ it('switches off a part with no stop, or one whose stop throws or rejects, all the same', () => {+ for (const stop of [undefined, () => { throw new Error('stuck') }, () => Promise.reject(new Error('stuck'))]) {+ const guard = createPartGuard({ log: vi.fn(), maxFailures: 1 })+ const base = router({ knows: () => { throw new Error('lost') } })+ const target = stop === undefined ? { ...base, stop: undefined } : { ...base, stop }+ const part = guard.start('fleet', () => target as Router, FALLBACKS)!+ expect(() => part.knows('a')).toThrow(ServiceUnavailableError)+ expect(guard.isOff('fleet')).toBe(true)+ // Failing again once off says it failed, and switches nothing a second time.+ expect(() => (part as unknown as { total: () => number }).total()).not.toThrow()+ }+ })++ it('counts a failure that lands after the part was switched off without switching it again', async () => {+ const log = vi.fn()+ let reject!: (error: Error) => void+ const guard = createPartGuard({ log, maxFailures: 1 })+ const part = guard.start('fleet', () => router({+ list: () => new Promise((_, no) => { reject = no }),+ knows: () => { throw new Error('lost') },+ }), FALLBACKS)!+ const pending = part.list()+ expect(() => part.knows('a')).toThrow(ServiceUnavailableError)+ reject(new Error('late'))+ await expect(pending).rejects.toBeInstanceOf(ServiceUnavailableError)+ expect(log.mock.calls.filter(([line]) => String(line).includes('switched off'))).toHaveLength(1)+ })+})diff --git a/cli/src/services/devicesGuard.ts b/cli/src/services/devicesGuard.tsnew file mode 100644index 000000000..2f4a217d3--- /dev/null+++ b/cli/src/services/devicesGuard.ts@@ -0,0 +1,129 @@+/**+ * How the devices keep one of their parts failing from costing the others (services/devices.ts): the+ * dial, the window bridges and the fleet's router share a service, and a dial that throws on every+ * frame must cost ⌘K nothing, as a fleet that cannot start must cost the dial nothing.+ *+ * The same two guards the core puts around a service (core/serviceHost.ts), one level down:+ * - `call` runs a notice into a part (a card for the dial, a window's answer for a bridge). One that+ * throws, or whose promise rejects, is logged, at most once a minute per part with a count of the rest,+ * and goes no further.+ * - `start` builds a part with members the others call in line (the fleet's routing), each with its+ * fallback. A part whose start throws is left off; a member that throws answers its fallback, and five+ * failures in a minute switch the part off for the life of the process. A `FAIL` fallback throws+ * `ServiceUnavailableError`, which the dial's host reads as "route this computer by yourself".+ *+ * `HARNESSD_TEST_FAULTS` names fail them for the end-to-end suite: `<part>` its start, or every call into+ * a notice part, and `<part>.<member>` one member.+ */+import { FAIL, readFallback, ServiceUnavailableError, type PortFallbacks } from '../core/api.js'++export interface PartGuardOptions {+ log?: (line: string) => void+ faults?: ReadonlySet<string>+ now?: () => number+ /** Failures within `windowMs` that switch a started part off. */+ maxFailures?: number+ windowMs?: number+}++type Member = (...args: unknown[]) => unknown++const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error))++export function createPartGuard(options: PartGuardOptions = {}) {+ const log = options.log ?? ((line: string) => console.error(line))+ const faults = options.faults ?? new Set<string>()+ const now = options.now ?? Date.now+ const maxFailures = options.maxFailures ?? 5+ const windowMs = options.windowMs ?? 60_000+ const said = new Map<string, { at: number; quiet: number }>()+ const failures = new Map<string, number[]>()+ const off = new Set<string>()++ const inject = (target: string): void => {+ if (faults.has(target)) throw new Error(`injected fault: ${target}`)+ }++ /** Logged once a minute per part: a dial unplugged mid-call throws on every frame until it is gone. */+ const quietly = (part: string, error: unknown): void => {+ const at = now()+ const last = said.get(part)+ if (last && at - last.at < 60_000) { last.quiet++; return }+ log(`[devices] ${part} failed · ${describe(error)}${last?.quiet ? ` · ${last.quiet} more since` : ''}`)+ said.set(part, { at, quiet: 0 })+ }++ const failed = (part: string, member: string, error: unknown, stop: (() => unknown) | undefined): void => {+ log(`[devices] ${part}.${member} failed · ${describe(error)}`)+ const at = now()+ const recent = [...(failures.get(part) ?? []).filter((t) => at - t < windowMs), at]+ failures.set(part, recent)+ if (recent.length < maxFailures || off.has(part)) return+ off.add(part)+ log(`[devices] ${part} switched off after ${recent.length} failures in ${Math.round(windowMs / 1000)}s · it stays off until the devices restart`)+ try { void Promise.resolve(stop?.()).catch(() => {}) } catch { /* a part failing to stop is already off */ }+ }++ return {+ /** Run a notice into `part`; a throw or a rejection is logged and goes no further. */+ call(part: string, run: () => unknown): void {+ try {+ inject(part)+ const result = run()+ if (result instanceof Promise) result.catch((error: unknown) => quietly(part, error))+ } catch (error) {+ quietly(part, error)+ }+ },++ /** Build `part` and guard every member `fallbacks` names; null when its start threw. */+ start<T extends object>(part: string, build: () => T, fallbacks: PortFallbacks<T>): T | null {+ let target: T+ try {+ inject(part)+ target = build()+ } catch (error) {+ off.add(part)+ log(`[devices] ${part} did not start · ${describe(error)} · the devices run without it`)+ return null+ }+ const stop = (target as { stop?: () => unknown }).stop?.bind(target)+ const guarded: Record<string, Member> = {}+ for (const [member, fallback] of Object.entries(fallbacks) as Array<[string, unknown]>) {+ const { deferred, value } = readFallback(fallback)+ const answer = (cause?: unknown): unknown => {+ if (value === FAIL) {+ const error = new ServiceUnavailableError(part, cause)+ if (deferred) return Promise.reject(error)+ throw error+ }+ return deferred ? Promise.resolve(value) : value+ }+ guarded[member] = (...args: unknown[]): unknown => {+ if (off.has(part)) return answer()+ let result: unknown+ try {+ inject(`${part}.${member}`)+ result = ((target as Record<string, Member>)[member]).apply(target, args)+ } catch (error) {+ failed(part, member, error, stop)+ return answer(error)+ }+ if (!deferred) return result+ return Promise.resolve(result).catch((error: unknown) => {+ failed(part, member, error, stop)+ return answer(error)+ })+ }+ }+ return guarded as T+ },++ /** Whether a started part is off: it did not start, or it failed too often. */+ isOff(part: string): boolean {+ return off.has(part)+ },+ }+}++export type PartGuard = ReturnType<typeof createPartGuard>diff --git a/cli/src/services/fleet.spec.ts b/cli/src/services/fleet.spec.tsindex 70230751a..e7137e0b6 100644--- a/cli/src/services/fleet.spec.ts+++ b/cli/src/services/fleet.spec.ts@@ -8,8 +8,8 @@ import type { MachineListCache } from '../device/machineList.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'+import { FAIL, type CoreApi } from '../core/api.js'+import { FLEET_FALLBACKS, startFleet, type Fleet, 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(() => ({@@ -61,21 +61,26 @@ function machinesOf(rows: Row[] = [THIS, OTHER]) {}}-function setup(over: Partial<FleetDeps> = {}, core = fakeCore()) {+/** This computer as the core names it: its ids, its name and its account's environment. */+function coreOf(over: { machineId?: () => string } = {}, core: CoreApi = fakeCore()): CoreApi {+ return {+ ...core,+ machine: { id: over.machineId ?? (() => 'mine'), computerId: () => 'computer-1', name: () => 'MacbookPro.local' },+ account: { ...core.account, environment: () => 'test-env' },+ }+}++function setup(over: Partial<FleetDeps> & { machineId?: () => string } = {}, base = fakeCore()) {const machines = machinesOf()+ const { machineId, ...rest } = over+ const core = coreOf({ machineId }, base)const deps: FleetDeps = {machines: machines as unknown as MachineListCache,- guestMachines: vi.fn(() => null),- computerId: () => 'computer-1',- machineId: () => 'mine',- machineName: () => 'MacbookPro.local',desk: () => [],- autonomousEnv: 'test-env',- ...over,+ ...rest,}- const ports: CorePorts = emptyPorts()- const router = startFleet(core, ports, deps)- return { router, ports, fleet: ports.fleet as FleetPort, deps, machines, core }+ const { fleet, router } = startFleet(core, deps)+ return { router, fleet: fleet as Fleet, deps, machines, core }}const decision = (over: Partial<RouteDecision> = {}): RouteDecision =>@@ -96,20 +101,16 @@ afterEach(() => {})describe('the machine list', () => {- it('is this computer alone signed out, the backend’s signed in, read again every minute until the fleet stops', () => {+ it('is read through the core at once, and 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)+ const { fleet, machines } = setup()expect(machines.refresh).toHaveBeenCalledTimes(1)+ vi.advanceTimersByTime(60_000)+ expect(machines.refresh).toHaveBeenCalledTimes(2)fleet.stop()expect(lane.stop).toHaveBeenCalled()vi.advanceTimersByTime(120_000)- expect(machines.refresh).toHaveBeenCalledTimes(1)+ expect(machines.refresh).toHaveBeenCalledTimes(2)})})@@ -301,3 +302,20 @@ describe('⌘K: which agent a typed task belongs to', () => {})})})++describe('the fleet failing', () => {+ it('answers ⌘K with no agent picked and nothing sent, saying why', () => {+ 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 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)+ }+ })+})diff --git a/cli/src/services/fleet.ts b/cli/src/services/fleet.tsindex 959ce6c3e..99ece81a4 100644--- a/cli/src/services/fleet.ts+++ b/cli/src/services/fleet.ts@@ -5,22 +5,96 @@* 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. ⌘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.+ * window's voice route reached another machine only through the dial. It is a part of the devices now+ * (services/devices.ts, step 9), beside its main caller: the dial reads a dozen routing facts while it+ * builds each frame (which machine an agent is on, whether it is known, who it is), and those reads+ * stay in line only on the same side of a process boundary as the dial. ⌘K reaches it through the+ * devices' port.*- * A service on the core boundary: it reads the core only through `CoreApi`, and the core reaches it- * only through `ports.fleet`.+ * It reads the core only through `CoreApi`.*/import { env } from '../config/env.js'-import type { CoreApi, CorePorts, RouteAnswer } from '../core/api.js'+import { FAIL, later, type CoreApi, type PortFallbacks, type RouteAnswer, type SendResult, type ForkResult } from '../core/api.js'import { DeviceFleet } from '../device/deviceFleet.js'import { DeviceLink } from '../device/deviceLink.js'import type { MachineListCache } from '../device/machineList.js'import { MachinePeerStore } from '../lib/e2ee/machinePeers.js'-import { routeVoiceTask, type RouterAgent } from '../lib/voiceRouter.js'+import { routeVoiceTask, type RouterAgent, type RouterContinuity } from '../lib/voiceRouter.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 { FleetRouter } from './fleetRouter.js'+/** 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 devices' guard,+ * a throw is a failure of the fleet, 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 fleet as the devices hold it: ⌘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 — the routing the dial asks of it,+ * the cards the other machines send, and stopping the lane to them. */+export interface Fleet extends FleetRouting {+ routeTask(text: string): Promise<RouteAnswer>+ routeSend(agentId: string, text: string): SendResult+ /** The other machines' cards, for the dial. Returns how to stop hearing them. */+ onEvent(listener: (event: FleetEvent) => void): () => void+ stop(): void+}++export const FLEET_UNAVAILABLE = 'the fleet service is unavailable'++/**+ * What the devices get 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<Fleet> = {+ routeTask: later({ agentId: '', machineId: '', name: '', confidence: 0, reason: FLEET_UNAVAILABLE, candidates: [], weighed: 0, machines: 0, via: '' }),+ 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,+}+/*** How many agents ⌘K weighs at once.*@@ -36,41 +110,23 @@ 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.- */+ /** The owner's machines: the devices' own copy of the list, read from the core (`account.machines`).+ * 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[]- /** The account's environment, which the lane names when it dials. Its tokens and its seal are the- * core's to give (`core.account`): this service holds no credential. */- autonomousEnv: string}-/** 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 {+/** Start the fleet: what ⌘K and the dial reach it through. The router itself is returned beside it, for+ * this service's own tests; nothing else holds it. */+export function startFleet(core: CoreApi, deps: FleetDeps): { fleet: Fleet; router: 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()- }+ // Signed out there is nothing to fetch and a fetch would only earn a 401 that empties the wheel, so the+ // core answers with the one row this daemon can speak for (`account.machines`).+ const refreshMachineList = (): void => { void deps.machines.refresh() }refreshMachineList()const machineListTimer = setInterval(refreshMachineList, MACHINE_LIST_REFRESH_MS)machineListTimer.unref?.()@@ -83,15 +139,15 @@ export function startFleet(core: CoreApi, ports: CorePorts, deps: FleetDeps): Fl// against, so one link ceremony covers the desktop app's relay and the dial's lane alike.auth: { accessToken: (options) => core.account.accessToken(options) },backendWsBase: env.BACKEND_WS_URL,- computerId: deps.computerId(),- autonomousEnv: deps.autonomousEnv,+ computerId: core.machine.computerId(),+ autonomousEnv: core.account.environment(),seal: core.account.lane,// 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(),+ localMachineId: () => core.machine.id(),log: (line) => console.log(`[device] ${line}`),})const devices = new DeviceFleet({@@ -104,9 +160,9 @@ export function startFleet(core: CoreApi, ports: CorePorts, deps: FleetDeps): Fl})// 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(),+ machineName: () => core.machine.name(),+ machineId: () => core.machine.id(),+ computerId: () => core.machine.computerId(),sessions: () => core.agents.advertised(),displayName: (session) => core.agents.displayName(session),runtimeProfile: (session) => core.agents.runtimeProfile(session),@@ -126,11 +182,11 @@ export function startFleet(core: CoreApi, ports: CorePorts, deps: FleetDeps): Fl// 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 = {+ const fleet: 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).+ // What the dial asks: the router's own answers.listMachines: () => router.listMachines(),listAgentsFlat: () => router.listAgentsFlat(),agentTotal: () => router.agentTotal(),@@ -161,7 +217,7 @@ export function startFleet(core: CoreApi, ports: CorePorts, deps: FleetDeps): Fllink.stop()},}- return router+ return { fleet, router }}/**diff --git a/cli/src/services/fleetRouter.ts b/cli/src/services/fleetRouter.tsindex 1bd36b5b3..bc3b84652 100644--- a/cli/src/services/fleetRouter.ts+++ b/cli/src/services/fleetRouter.ts@@ -12,7 +12,8 @@* 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 type { ForkResult, SendResult } from '../core/api.js'+import type { FleetRouting, ForkOutcome, SelectResult } from './fleet.js'import { extendShortRecap } from '../lib/deviceRecap.js'import type { RegisteredSession } from '../lib/registry.js'import type { RouterContinuity } from '../lib/voiceRouter.js'diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.tsindex deb71ba3a..dd3fe5848 100644--- a/cli/src/services/modelsProcess.ts+++ b/cli/src/services/modelsProcess.ts@@ -22,6 +22,7 @@ import { gridGlances, onGridModelsChanged } from '../lib/gridModels.js'import type { RuntimeModelOption } from '../lib/runtimeProfile.js'import { startModels } from './models.js'import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'+import { UNASKED } from './processCoreApi.js'type Payload = Record<string, unknown>@@ -56,6 +57,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: PadataDir,// Models opens no terminal.terminals: TERMINALS_OFF,+ machine: UNASKED.machine,agents: {all: () => [],live: () => [],@@ -74,6 +76,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: PasetRuntime: () => {},fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),...AGENT_ACTIONS_OFF,+ activityText: UNASKED.activityText,},turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },questions: { answer: () => {}, answerReviewed: async () => false },@@ -104,6 +107,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: Pa// Models never reaches another machine: the fleet's lane is not its to seal.lane: LANE_OFF,...ACCOUNT_BACKEND_OFF,+ ...UNASKED.account,},clients: {viewerChanged: () => {},@@ -111,6 +115,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: PagridModelsChanged: () => told('gridModelsChanged'),dshInstallStatus: () => {},windows: () => {}, observer: () => false,+ ...UNASKED.clients,},daemon: DAEMON_UNKNOWN,}diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.tsindex 1241fa591..ef310de41 100644--- a/cli/src/services/processCoreApi.spec.ts+++ b/cli/src/services/processCoreApi.spec.ts@@ -52,6 +52,17 @@ describe('the core API a light service runs on in its own process', () => {api.clients.gridNamed('grid')api.clients.gridModelsChanged()api.clients.dshInstallStatus({ phase: 'clone' })+ // What only the devices ask (services/devices.ts): nothing, from every other service.+ expect([api.machine.id(), api.machine.computerId(), api.machine.name()]).toEqual(['', '', ''])+ await expect(api.agents.activityText('a1')).resolves.toBeNull()+ expect(api.account.signedIn()).toBe(false)+ expect(api.account.environment()).toBe('')+ await expect(api.account.machines()).resolves.toEqual({ status: 503, body: {} })+ api.clients.sendLocal({ type: 'dial_focus', payload: {} })+ expect(api.clients.sendToWindow('w1', { type: 'dial_form', payload: {} })).toBe(false)+ expect(api.clients.hasWindow()).toBe(false)+ api.clients.devicesChanged({})+ api.clients.dialWatching(true)// With no way to ask the core, it acts on nothing: no agent made, no turn, no window told.await expect(api.agents.create({ engine: 'claude', cwd: '/w', dsh: null, prompt: 'p', name: 'n', bypassPermission: false })).resolves.toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex 6390b9fc7..b2eaa4378 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -62,6 +62,22 @@ function keyAnswer(answer: Payload): string {throw new Error(typeof answer.error === 'string' ? answer.error : 'the gateway did not answer for this machine\'s key')}+/**+ * What only the devices ask of the core (services/devices.ts), as every other service in its own process+ * answers it: nothing. Shared, so that a member added for the devices is added once for the others.+ */+export const UNASKED = {+ machine: { id: () => '', computerId: () => '', name: () => '' },+ activityText: async (): Promise<string | null> => null,+ account: { signedIn: () => false, environment: () => '', machines: async () => ({ status: 503, body: {} }) },+ clients: { sendLocal: () => {}, sendToWindow: () => false, hasWindow: () => false, devicesChanged: () => {}, dialWatching: () => {} },+} satisfies {+ machine: CoreApi['machine']+ activityText: CoreApi['agents']['activityText']+ account: Pick<CoreApi['account'], 'signedIn' | 'environment' | 'machines'>+ clients: Pick<CoreApi['clients'], 'sendLocal' | 'sendToWindow' | 'hasWindow' | 'devicesChanged' | 'dialWatching'>+}+export function processCoreApi(dataDir: string, service: string, view: AgentsView = {}): CoreApi {const live = (): ShownAgent[] => view.live?.() ?? []const ask = view.ask@@ -71,6 +87,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie// Terminals are launched by the core alone (the shell service, #893): a service in its own process// is refused, never handed a way to start a process outside the core.terminals: { open: TERMINALS_OFF.open, watch: view.watch ?? TERMINALS_OFF.watch },+ machine: UNASKED.machine,agents: {// The stopped agents are never sent to these services: none of them reads one.all: live,@@ -92,6 +109,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsViereturn { ok: false, error: typeof answer.error === 'string' ? answer.error : 'CREATE_FAILED', ...(typeof answer.detail === 'string' ? { detail: answer.detail } : {}) }},dsh: (session) => (session as ShownAgent).dshContext ?? null,+ activityText: UNASKED.activityText,},turns: {send: () => {},@@ -125,6 +143,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie: { status: 502, body: { error: typeof answer.error === 'string' ? answer.error : 'BACKEND_UNREACHABLE' } }},onNotice: (listener) => view.onNotice?.(listener) ?? (() => {}),+ ...UNASKED.account,},clients: {viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {},@@ -136,6 +155,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVievoid ask('observer_send', { connId, type, payload }).catch(() => {})return true},+ ...UNASKED.clients,},daemon: {get command() { return daemon().command },diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.tsindex bbcfd6044..c79755349 100644--- a/cli/src/services/searchProcess.ts+++ b/cli/src/services/searchProcess.ts@@ -14,6 +14,7 @@ import { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.jsimport { externalProviders } from '../lib/sessionSearch/externals/index.js'import type { RegisteredSession } from '../lib/registry.js'import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'+import { UNASKED } from './processCoreApi.js'import { SEARCH_REQUESTS, startSearch } from './search.js'export interface SearchServiceOptions {@@ -41,6 +42,7 @@ export function searchCoreApi(return {dataDir,terminals: TERMINALS_OFF,+ machine: UNASKED.machine,agents: {all: agents,live: () => agents().filter((agent) => agent.active),@@ -55,6 +57,7 @@ export function searchCoreApi(setRuntime: () => {},fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),...AGENT_ACTIONS_OFF,+ activityText: UNASKED.activityText,},// Search drives no agent: these are never asked of it.turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },@@ -72,8 +75,9 @@ export function searchCoreApi(privateGridName: async () => null,machineName: () => null,...ACCOUNT_BACKEND_OFF,+ ...UNASKED.account,},- clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false },+ clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false, ...UNASKED.clients },daemon: DAEMON_UNKNOWN,}}diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.tsindex 917e94500..4554b56a8 100644--- a/cli/src/services/viewersProcess.ts+++ b/cli/src/services/viewersProcess.ts@@ -21,6 +21,7 @@ import type { CoreApi } from '../core/api.js'import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'import type { RegisteredSession } from '../lib/registry.js'import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'+import { UNASKED } from './processCoreApi.js'import { startViewers } from './viewers.js'export interface ViewersServiceOptions {@@ -48,6 +49,7 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, Rereturn {dataDir,terminals: TERMINALS_OFF,+ machine: UNASKED.machine,agents: {all: attached,live: attached,@@ -62,6 +64,7 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, ResetRuntime: () => {},fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),...AGENT_ACTIONS_OFF,+ activityText: UNASKED.activityText,},// The viewers drive no agent: these are never asked of them.turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },@@ -78,8 +81,9 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, ReprivateGridName: async () => null,machineName: () => null,...ACCOUNT_BACKEND_OFF,+ ...UNASKED.account,},- clients: { viewerChanged: tell, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false },+ clients: { viewerChanged: tell, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false, ...UNASKED.clients },daemon: DAEMON_UNKNOWN,}}diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.tsindex 8da78d7d6..da094c21d 100644--- a/cli/src/services/workspacesProcess.ts+++ b/cli/src/services/workspacesProcess.ts@@ -16,6 +16,7 @@ import type { CoreApi } from '../core/api.js'import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, LANE_OFF, resolveAgent, TERMINALS_OFF } from '../core/api.js'import type { RegisteredSession } from '../lib/registry.js'import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'+import { UNASKED } from './processCoreApi.js'import { startWorkspaces } from './workspaces.js'export interface WorkspacesServiceOptions {@@ -46,6 +47,7 @@ export function workspacesCoreApi(return {dataDir,terminals: TERMINALS_OFF,+ machine: UNASKED.machine,agents: {all: () => {const agents = view.inUse()@@ -64,6 +66,7 @@ export function workspacesCoreApi(setRuntime: () => {},fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),...AGENT_ACTIONS_OFF,+ activityText: UNASKED.activityText,},// The workspaces drive no agent: these are never asked of them.turns: { send: () => {}, stop: () => {}, recent: () => [], asks: () => [], ...DELIVERIES_OFF },@@ -80,8 +83,9 @@ export function workspacesCoreApi(privateGridName: async () => null,machineName: () => null,...ACCOUNT_BACKEND_OFF,+ ...UNASKED.account,},- clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false },+ clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false, ...UNASKED.clients },daemon: DAEMON_UNKNOWN,}}diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.tsindex 1d86041e5..29a566c6f 100644--- a/cli/src/testing/fakeCore.ts+++ b/cli/src/testing/fakeCore.ts@@ -16,6 +16,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {watch: { frame: vi.fn(async () => {}), close: vi.fn(async () => {}), onOutput: vi.fn(() => () => {}) },...over.terminals,},+ machine: { id: vi.fn(() => 'machine-1'), computerId: vi.fn(() => 'computer-1'), name: vi.fn(() => 'This machine'), ...over.machine },agents: {all: vi.fn(() => []),live: vi.fn(() => []),@@ -31,6 +32,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {fork: vi.fn(async () => ({ ok: false as const, error: 'UNSUPPORTED' })),create: vi.fn(async () => ({ ok: false as const, error: 'UNSUPPORTED' })),dsh: vi.fn(() => null),+ activityText: vi.fn(async () => null),...over.agents,},turns: {@@ -61,9 +63,16 @@ export function fakeCore(over: Overrides = {}): CoreApi {backend: vi.fn(async () => ({ status: 200, body: {} })),observerKey: { publicKey: vi.fn(async () => 'cHVi'), signWelcome: vi.fn(async () => 'c2ln') },onNotice: vi.fn(() => () => {}),+ signedIn: vi.fn(() => true),+ environment: vi.fn(() => 'prod'),+ machines: vi.fn(async () => ({ status: 200, body: { success: true, data: { machines: [] } } })),...over.account,},- clients: { viewerChanged: vi.fn(), gridNamed: vi.fn(), gridModelsChanged: vi.fn(), dshInstallStatus: vi.fn(), windows: vi.fn(), observer: vi.fn(() => true), ...over.clients },+ clients: {+ viewerChanged: vi.fn(), gridNamed: vi.fn(), gridModelsChanged: vi.fn(), dshInstallStatus: vi.fn(), windows: vi.fn(), observer: vi.fn(() => true),+ sendLocal: vi.fn(), sendToWindow: vi.fn(() => true), hasWindow: vi.fn(() => true), devicesChanged: vi.fn(), dialWatching: vi.fn(),+ ...over.clients,+ },daemon: { command: 'harness', port: 18473, machineId: () => 'machine-1', autonomousEnv: 'prod', ...over.daemon },}}diff --git a/cli/src/testing/teamFixture.ts b/cli/src/testing/teamFixture.tsindex d79cd87eb..23b8b3498 100644--- a/cli/src/testing/teamFixture.ts+++ b/cli/src/testing/teamFixture.ts@@ -15,6 +15,7 @@ import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, DELIVERIES_OFF, LANE_OFF, TERMIimport { projectDisplayName, registry } from '../lib/registry.js'import type { SessionInputDelivery } from '../lib/sessionInput.js'import { startCollaboration, type Teams } from '../services/collaboration.js'+import { UNASKED } from '../services/processCoreApi.js'import { SwarmPromptScopes } from '../teams/promptScope.js'export interface TeamFixture {@@ -39,12 +40,14 @@ export function attachTeams<T extends BackendSocket>(socket: T): T & TeamFixtureconst core = (): CoreApi => ({dataDir: env.ADAPTER_DATA_DIR,terminals: TERMINALS_OFF,+ machine: UNASKED.machine,agents: {all: () => registry.list(), live: () => registry.list(), displayName: projectDisplayName,byAgent: (agentId) => registry.byAgent(agentId), resolve: (id) => registry.resolve(id), advertised: () => registry.advertised(),terminalAvailable: (agentId) => registry.terminalAvailable(agentId), sync: () => {},runtimeModels: async () => [], runtimeProfile: () => null, setRuntime: () => {}, fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),...AGENT_ACTIONS_OFF,+ activityText: UNASKED.activityText,},turns: {send: () => {}, stop: () => {}, recent: () => [], asks: () => [],@@ -60,6 +63,7 @@ export function attachTeams<T extends BackendSocket>(socket: T): T & TeamFixturemintGridName: async () => null, accessToken: () => Promise.reject(new Error('no credential')), lane: LANE_OFF,privateGridName: async () => null, machineName: () => null,...ACCOUNT_BACKEND_OFF,+ ...UNASKED.account,// The tab channels as the spec says the account has them; a backend without them answers 404.backend: async (method, path) => {if (method !== 'GET' || path !== '/api/tab-channels' || !fixture.readChannelDesk) return { status: 404, body: {} }@@ -70,6 +74,7 @@ export function attachTeams<T extends BackendSocket>(socket: T): T & TeamFixtureviewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {},windows: (frame) => socket.sendLocal(frame),observer: () => false,+ ...UNASKED.clients,},daemon: { command: 'harness', port: env.PORT, machineId: () => socket.machineId, autonomousEnv: 'prod' },})diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex b0df4bdbf..bb73cdfe3 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -255,12 +255,21 @@ The steps, each a pull request with its end-to-end proof: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 theydo 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.+ port too. **D1's remainder (done, 6 October):** `services/devices.ts` owns the serial ports, the+ dial's host, its log, the window bridges, the fleet (router and lane, now one of its parts), the voice+ router and the `harness_devices_*` requests. The core reaches it through `DevicesPort`, each member+ with its fallback: the desk, the swarms, what is unread, focus, what was seen, the cards teed to it,+ settings, the window bridges' answers, ⌘K, and stop. The devices reach the core through `CoreApi`:+ this computer's ids and name, the sign-in (the transcriber and the lane ask the core for a token; the+ dial's host no longer holds a session manager of its own), a pane's activity line, recent turns,+ sending and stopping a turn, answering, the runtime profile and models, fork, and the windows: the+ `dial_*` frames (`clients.sendLocal`, only the devices' own types), a bridge's ask+ (`clients.sendToWindow`), whether a window is there, and whether a dial is watching+ (`clients.dialWatching`, which the core keeps for the cards it makes). The pane writer lock and the+ card text moved into the core (`core/deviceInput.ts`, `core/cardText.ts`). Inside, each part answers+ for itself (`services/devicesGuard.ts`): a dial throwing costs ⌘K nothing, a fleet that cannot start+ costs the dial nothing. ⌘K's answers are sent off the window's ordered chain, so they can come from+ another process without holding the window's typing.- **D2, the dial in its own process.** Sized on 2026-10-05 against the viewers' process (#775): itis several times larger. Viewers cross the link in about five calls; the dial needs about fifteenfrom the core (the desk, swarms, unread, focus, seen, settings, status, the six kinds of turn and