The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
harnessd: devices D3, the Wi-Fi device with the dials, in their process (#929)
Deece61cdbcb99f
diff --git a/cli/e2e/deviceCompat.e2e.ts b/cli/e2e/deviceCompat.e2e.tsindex f454dc0f8..ff99d761f 100644--- a/cli/e2e/deviceCompat.e2e.ts+++ b/cli/e2e/deviceCompat.e2e.ts@@ -12,6 +12,12 @@* 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.*+ * The Wi-Fi device too (harness/fakeWifiDevice.ts): paired with a signed-in machine and reaching it through+ * the fake relay, it says hello, lists its agents, follows the window's focus, sends a prompt and reads its+ * receipt, subscribes to an agent's live text, answers a question, scrolls the window's terminal, steps+ * along the desk and lists the Store. Every answer and event it heard, and the window's frames it caused,+ * are compared the same way.+ ** Skipped unless COMPAT_FROM names a bundle, as e2e/compat.e2e.ts is. `COMPAT_REPORT=<file>` writes both* sides, for reading.*/@@ -21,6 +27,8 @@ 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'+import { FakeWifiDevice } from './harness/fakeWifiDevice.js'+import { startPhoneMachine } from './harness/fleet.js'const FROM = process.env.COMPAT_FROM@@ -155,6 +163,117 @@ async function scenario(scriptPath: string | undefined, label: string): Promise<}}+/** Types the Wi-Fi device may hear in one run and not the other, by timing alone, each with why. */+const WIFI_TIMING: Record<string, string> = {+ // A summary's recap or a tool's card reaches the device as the core's mirror writes it; how many of a+ // fast fake turn's land before the scenario moves on is timing.+ 'event turn.tool': 'a tool card of a fast fake turn, which lands or not before the scenario moves on',+ // The answer's text is flushed every few hundred milliseconds or at a size; a short fake answer may go in+ // one flush or in none before the final.+ 'event stream.text': 'flushed on a timer or at a size: a short fake answer may land only in the final',+ 'event stream.tool': 'the fake turn the subscription watched may call no tool',+}++/** One build's signed-in machine, a window and a Wi-Fi device through the scenario; what both heard. */+async function wifiScenario(scriptPath: string | undefined, label: string): Promise<Heard> {+ const world = await startPhoneMachine({ wifiDevice: true, ...(scriptPath ? { scriptPath } : {}) })+ const { backend, machine } = world+ const device = new FakeWifiDevice({ backend, machineId: machine.machineId, identity: world.wifi.identity, machinePub: machine.identity.pub, token: world.wifi.token })+ onTestFailed(() => { console.log(`---- ${label} daemon log\n${machine.daemon.log().split('\n').slice(-120).join('\n')}\n---- the device heard\n${JSON.stringify(device.events().slice(-30))}`) })+ const heard: Heard = { shapes: new Map(), values: {}, order: [] }+ try {+ const window = await LocalClient.connect(machine.daemon, { machineId: machine.machineId })+ const cwd = join(machine.daemon.projectsDir, 'wifi-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)+ window.send('app_swarms', { active: 't1', swarms: [{ id: 't1', name: 'Tab', agentIds: [agentId], panes: 1 }], tiles: [] })+ window.send('app_panes', { agentIds: [agentId], foreground: true })+ await until('the machine to be on the relay', () => backend.nodeUp(machine.machineId) || null, 30_000)+ await until('the device to open a session', async () => { await device.open(10_000); return true }, 60_000, 500)+ const answers: Array<Record<string, any>> = []+ const ask = async (type: string, fields: Record<string, unknown> = {}) => {+ const answer = await device.ask(type, fields)+ answers.push(answer)+ return answer+ }+ const hello = await until('the hello to be answered', async () => (await device.ask('hello', { proto: 1 }).catch(() => null)) ?? null, 60_000, 500)+ answers.push(hello)+ const target = { machineId: machine.machineId, agentId }+ await ask('agents.list')+ await ask('status', target)+ await ask('recap', { ...target, n: 1 })+ // The window moves to the agent: the device's focus follows.+ let since = device.mark()+ window.send('app_focus', { agentId })+ await device.nextEvent((e) => e.kind === 'focus.changed' && e.payload?.focus?.agentId === agentId, 'focus.changed', since)+ const focus = await ask('focus.get')+ // A prompt from the device, its turn, and its receipt.+ since = device.mark()+ await ask('turn.send', { ...target, idempotencyKey: 'prompt-1', text: 'from the wifi device' })+ await device.nextEvent((e) => e.kind === 'turn.done' && e.agentId === agentId, 'the prompt\'s turn ending', since)+ await new Promise((resolve) => setTimeout(resolve, 1_000))+ await ask('receipt.get', { idempotencyKey: 'prompt-1' })+ // Its live text, while subscribed.+ const subscribed = await ask('agent.subscribe', { ...target, ttlSec: 60 })+ since = device.mark()+ window.send('message', { agentId, content: 'streamed to the device' })+ await device.nextEvent((e) => e.kind === 'stream.final' && e.agentId === agentId, 'stream.final', since)+ await ask('agent.unsubscribe', { subscriptionId: subscribed.subscriptionId })+ // A question, answered from the device.+ since = device.mark()+ window.send('message', { agentId, content: '!ask' })+ const open = await device.nextEvent((e) => e.kind === 'question.open' && e.agentId === agentId, 'question.open', since)+ const first = (open.payload.questions as Array<Record<string, any>>)[0]+ await ask('question.answer', { ...target, idempotencyKey: 'answer-1', questionRequestId: open.payload.questionRequestId,+ answers: { [first.question ?? first.q ?? first.header]: 'Coffee' } })+ await device.nextEvent((e) => e.kind === 'question.close' && e.agentId === agentId, 'question.close', since)+ // A stroke for the window's terminal, and a step along the desk.+ await ask('scroll', { phase: 'down', dy: 0, velocity: 0 })+ await ask('scroll', { phase: 'up', dy: 0, velocity: 0 })+ await window.waitFor((f) => f.type === 'dial_scroll' && f.payload?.phase === 'up', 15_000, 'dial_scroll')+ await ask('focus.step', { direction: 'next', idempotencyKey: 'step-1', focusRevision: focus.focusRevision })+ await ask('store.list')+ await new Promise((resolve) => setTimeout(resolve, 1_500))+ for (const answer of answers) hear(heard, `result ${answer.type}`, answer)+ for (const event of device.events()) {+ const key = `event ${event.kind ?? event.type}`+ hear(heard, key, event)+ heard.order.push(`${key} ${JSON.stringify(event).slice(0, 160)}`)+ }+ for (const frame of window.frames as Frame[]) {+ if (!frame.type.startsWith('dial_') && !frame.type.startsWith('device_')) continue+ hear(heard, `window ${frame.type}`, frame)+ }+ heard.values.hello = { proto: hello.proto, capabilities: [...(hello.capabilities as string[])].sort() }+ heard.values.agents = (answers[1].agents as Array<Record<string, unknown>>).map((agent) => ({ engine: agent.engine, state: agent.state, runtime: agent.runtime }))+ heard.values.focus = { agent: focus.focus?.agentId === agentId }+ window.close()+ return heard+ } finally {+ device.close()+ await world.close()+ }+}++/** What two runs heard that differs, but for what is listed as changed or timing. */+function differ(before: Heard, after: Heard, timing: Record<string, string>): string[] {+ 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 })}`)+ }+ return differences+}+describe.skipIf(!FROM)('the devices\' frames, against another build\'s', () => {afterEach(() => {})@@ -165,18 +284,18 @@ describe.skipIf(!FROM)('the devices\' frames, against another build\'s', () => {const side = (heard: Heard) => ({ shapes: Object.fromEntries([...heard.shapes].map(([key, set]) => [key, [...set].map((s) => JSON.parse(s))])), values: heard.values, order: heard.order })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(differ(before, after, TIMING)).toEqual([])+ expect(after.values).toEqual(before.values)+ })++ it('the Wi-Fi device and the windows hear the same answers and events, in the same shapes', async () => {+ const before = await wifiScenario(FROM, 'released')+ const after = await wifiScenario(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, order: heard.order })+ writeFileSync(`${process.env.COMPAT_REPORT}.wifi.json`, JSON.stringify({ before: side(before), after: side(after) }, null, 2))}- expect(differences).toEqual([])+ expect(differ(before, after, WIFI_TIMING)).toEqual([])expect(after.values).toEqual(before.values)})})diff --git a/cli/e2e/devicesProcess.e2e.ts b/cli/e2e/devicesProcess.e2e.tsindex 05d68befc..2eec82b59 100644--- a/cli/e2e/devicesProcess.e2e.ts+++ b/cli/e2e/devicesProcess.e2e.ts@@ -9,15 +9,14 @@* - a dial unplugged and plugged in again and again, a dial whose session throws on every call, and a dial* flooding its port with what no dial sends are each dropped alone, and come back.*/-import { execFileSync } from 'node:child_process'import { appendFileSync, 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'+import { Desk, devicesPids } from './harness/desk.js'+import type { DialMessage, FakeDial } from './harness/fakeDial.js'-const SETTINGS = { brightness: 60, character: 0, face: 466, muted: false, quiet: false, straightTitle: false, focusFace: false, scrollReversed: false, round: true, voiceLang: 'en' }const row = async (client: LocalClient, agentId: string) =>((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents)@@ -39,14 +38,6 @@ async function turn(client: LocalClient, agentId: string, content: string): Promclient.send('message', { agentId, content })await ended}-/** This daemon's devices processes, by the pids its master logged: `harnessd-devices` alone would match every- * daemon's on the machine, another file's in a parallel run. */-function devicesPids(d: IsolatedDaemon): number[] {- const ours = new Set([...d.log().matchAll(/\[harnessd\] service devices started \(pid (\d+)\)/g)].map((match) => Number(match[1])))- const table = execFileSync('ps', ['-A', '-o', 'pid=,command=']).toString().trim().split('\n')- return table.map((line) => line.trim().match(/^(\d+)\s+(.*)$/)).filter((match): match is RegExpMatchArray => !!match)- .filter(([, pid, command]) => command.trim() === 'harnessd-devices' && ours.has(Number(pid))).map(([, pid]) => Number(pid))-}const restarts = (d: IsolatedDaemon) => d.log().split('\n').filter((line) => /\[harnessd\] service devices started .* restart \d+/.test(line)).lengthconst connections = (d: IsolatedDaemon) => d.log().split('\n').filter((line) => line.includes('[services] devices connected')).length/** ⌘K's pick for a typed task: `route_task` answers as `route_result`, under the asker's request id. */@@ -57,30 +48,6 @@ async function routeTask(client: LocalClient, text: string): Promise<Record<strireturn (await answered).payload as Record<string, any>}-/** The dials this daemon finds, written where its discovery reads them at every scan. */-class Desk {- constructor(readonly file: string, private readonly plugged = new Map<string, FakeDial>()) {}- async plug(serial: string, mac: string): Promise<FakeDial> {- const dial = await FakeDial.open({ mac, settings: SETTINGS })- this.plugged.set(serial, dial)- this.write()- dial.keepGreeting()- return dial- }- async unplug(serial: string): Promise<void> {- const dial = this.plugged.get(serial)- this.plugged.delete(serial)- this.write()- await dial?.close()- }- async close(): Promise<void> {- for (const serial of [...this.plugged.keys()]) await this.unplug(serial)- }- private write(): void {- writeFileSync(this.file, JSON.stringify([...this.plugged].map(([serial, dial]) => ({ serial, path: dial.path }))))- }-}-describe('the devices in their own process', () => {let daemon: IsolatedDaemon | undefinedlet desk: Desk | undefineddiff --git a/cli/e2e/harness/desk.ts b/cli/e2e/harness/desk.tsnew file mode 100644index 000000000..42c087bbb--- /dev/null+++ b/cli/e2e/harness/desk.ts@@ -0,0 +1,45 @@+/**+ * The dials on a desk, for the end-to-end suite: fake dials on pseudo-terminals (fakeDial.ts) that a daemon+ * finds where `HARNESSD_TEST_DIAL_PORT` points, a file it reads at every scan (cable/cableFleet.ts), so a+ * test can plug several in and unplug them. And the devices' processes a daemon's master started.+ */+import { execFileSync } from 'node:child_process'+import { writeFileSync } from 'node:fs'+import type { IsolatedDaemon } from './daemon.js'+import { FakeDial } from './fakeDial.js'++/** What a dial says its settings are when it greets. */+export const SETTINGS = { brightness: 60, character: 0, face: 466, muted: false, quiet: false, straightTitle: false, focusFace: false, scrollReversed: false, round: true, voiceLang: 'en' }++/** This daemon's devices processes, by the pids its master logged: `harnessd-devices` alone would match every+ * daemon's on the machine, another file's in a parallel run. */+export function devicesPids(d: IsolatedDaemon): number[] {+ const ours = new Set([...d.log().matchAll(/\[harnessd\] service devices started \(pid (\d+)\)/g)].map((match) => Number(match[1])))+ const table = execFileSync('ps', ['-A', '-o', 'pid=,command=']).toString().trim().split('\n')+ return table.map((line) => line.trim().match(/^(\d+)\s+(.*)$/)).filter((match): match is RegExpMatchArray => !!match)+ .filter(([, pid, command]) => command.trim() === 'harnessd-devices' && ours.has(Number(pid))).map(([, pid]) => Number(pid))+}+/** The dials this daemon finds, written where its discovery reads them at every scan. */+export class Desk {+ constructor(readonly file: string, private readonly plugged = new Map<string, FakeDial>()) {}+ async plug(serial: string, mac: string): Promise<FakeDial> {+ const dial = await FakeDial.open({ mac, settings: SETTINGS })+ this.plugged.set(serial, dial)+ this.write()+ dial.keepGreeting()+ return dial+ }+ async unplug(serial: string): Promise<void> {+ const dial = this.plugged.get(serial)+ this.plugged.delete(serial)+ this.write()+ await dial?.close()+ }+ async close(): Promise<void> {+ for (const serial of [...this.plugged.keys()]) await this.unplug(serial)+ }+ private write(): void {+ writeFileSync(this.file, JSON.stringify([...this.plugged].map(([serial, dial]) => ({ serial, path: dial.path }))))+ }+}+diff --git a/cli/e2e/harness/fakeWifiDevice.ts b/cli/e2e/harness/fakeWifiDevice.tsnew file mode 100644index 000000000..154d43494--- /dev/null+++ b/cli/e2e/harness/fakeWifiDevice.ts@@ -0,0 +1,60 @@+/**+ * A Wi-Fi device, as the daemon sees one: an identity paired with the machine under the device role,+ * reaching it through the (fake) relay over an end-to-end encrypted session (harness/relayPhone.ts, with+ * the CLI's own client crypto), and speaking the device protocol (docs/autonomous-device-integration.md):+ * a request sealed as `autonomous_device_request`, its answer `autonomous_device_result`, the machine's+ * events `autonomous_device_event`.+ *+ * What the device's own OS does with them it does here the documented way, and no more: an application+ * hello first, and after a `resync` it asks again what it needs (its agents, its receipts by idempotency+ * key). Everything it heard is kept, in order, so a test can say what it was told and when.+ */+import type { FakeBackend } from './fakeBackend.js'+import { RelayPhone, type PhoneFrame } from './relayPhone.js'+import type { Identity } from '../../src/lib/e2ee/core.js'++export type DeviceEvent = Record<string, any> & { type: string }++export class FakeWifiDevice {+ readonly link: RelayPhone++ constructor(options: { backend: FakeBackend; machineId: string; identity: Identity; machinePub: Uint8Array; token: string }) {+ this.link = new RelayPhone(options)+ }++ /** Open its session with the machine through the relay. */+ open(ms = 30_000): Promise<void> {+ return this.link.open(ms)+ }++ /** A request and its answer (`<type>_result`), as the device's OS asks it. */+ async ask(type: string, fields: Record<string, unknown> = {}, ms = 30_000): Promise<Record<string, any>> {+ // Sealed, as its firmware seals every request: the machine refuses one in the clear.+ return this.link.request('autonomous_device_request', { type, ...fields }, ms, true)+ }++ /** The application hello every session starts with. */+ hello(resume?: { serverInstanceId: string; cursor: number }): Promise<Record<string, any>> {+ return this.ask('hello', { proto: 1, ...(resume ? { resume } : {}) })+ }++ /** Every event the machine sent it, in order. */+ events(since = 0): DeviceEvent[] {+ return this.link.frames.slice(since).filter((frame) => frame.type === 'autonomous_device_event').map((frame) => frame.payload as DeviceEvent)+ }++ /** How far it has heard: pass to `nextEvent` or `events` to look only after this point. */+ mark(): number {+ return this.link.frames.length+ }++ /** The first event, from `since` on, that passes `test`. */+ async nextEvent(test: (event: DeviceEvent) => boolean, what: string, since = this.mark(), ms = 45_000): Promise<DeviceEvent> {+ const frame = await this.link.waitFor((f: PhoneFrame) => f.type === 'autonomous_device_event' && test(f.payload as DeviceEvent), ms, what, since)+ return frame.payload as DeviceEvent+ }++ close(): void {+ this.link.close()+ }+}diff --git a/cli/e2e/harness/fleet.ts b/cli/e2e/harness/fleet.tsindex 569e34dfc..01736c79f 100644--- a/cli/e2e/harness/fleet.ts+++ b/cli/e2e/harness/fleet.ts@@ -86,8 +86,8 @@ async function writeE2ee(daemon: IsolatedDaemon, files: Record<string, unknown>)}/** A daemon for one machine of the account, signed in to the fake backend and nothing else. */-async function signedInDaemon(backend: FakeBackend, spec: FakeMachine, env: Record<string, string> = {}): Promise<IsolatedDaemon> {- const daemon = await IsolatedDaemon.create({ env: { ...remoteSettings(backend), ADAPTER_COMPUTER_ID: spec.computerId, ...env } })+async function signedInDaemon(backend: FakeBackend, spec: FakeMachine, env: Record<string, string> = {}, scriptPath?: string): Promise<IsolatedDaemon> {+ const daemon = await IsolatedDaemon.create({ ...(scriptPath ? { scriptPath } : {}), env: { ...remoteSettings(backend), ADAPTER_COMPUTER_ID: spec.computerId, ...env } })// The daemon inherits the runner's environment, where a registry or a proxy may be named. None of// them is anywhere a fleet daemon may go.for (const [key, value] of Object.entries(daemon.env)) {@@ -104,28 +104,36 @@ export interface PhoneMachine {machine: FleetMachine/** A phone of the account, paired with the machine: its key is trusted there as a web client. */phone: { identity: Identity; token: string }+ /** A Wi-Fi device paired with the machine (`wifiDevice`): its key is trusted there as a device, and it+ * reaches the machine through the relay as a phone does (harness/fakeWifiDevice.ts). */+ wifi: { identity: Identity; token: string }close(): Promise<void>}/** One signed-in machine and a phone paired with it, on the fake backend: what a phone reaches the* machine through, end to end encrypted and relayed. */-export async function startPhoneMachine(options: { env?: Record<string, string> } = {}): Promise<PhoneMachine> {+export async function startPhoneMachine(options: { env?: Record<string, string>; wifiDevice?: boolean; scriptPath?: string } = {}): Promise<PhoneMachine> {const backend = await FakeBackend.start()const spec = { machineId: 'a1'.repeat(16), computerId: 'e2e-computer-0000-0000-00000000000a', name: 'machine-a', token: 'e2e-token-machine-a', identity: newIdentity() }backend.addMachine(spec)const phone = { identity: newIdentity(), token: 'e2e-token-phone' }backend.addUser(phone.token)+ const wifi = { identity: newIdentity(), token: 'e2e-token-wifi-device' }+ backend.addUser(wifi.token)let daemon: IsolatedDaemon | null = nulltry {- daemon = await signedInDaemon(backend, spec, options.env)+ daemon = await signedInDaemon(backend, spec, options.env, options.scriptPath)await writeE2ee(daemon, {'identity.json': { priv: b64e(spec.identity.priv), pub: b64e(spec.identity.pub) },- 'paired.json': [{ identityPub: b64e(phone.identity.pub), label: 'phone', pairedAt: Date.now(), role: 'web' }],+ 'paired.json': [+ { identityPub: b64e(phone.identity.pub), label: 'phone', pairedAt: Date.now(), role: 'web' },+ ...(options.wifiDevice ? [{ identityPub: b64e(wifi.identity.pub), label: 'Wi-Fi device', pairedAt: Date.now(), role: 'device' }] : []),+ ],})await daemon.start()const started = daemonreturn {- backend, machine: { ...spec, daemon: started }, phone,+ backend, machine: { ...spec, daemon: started }, phone, wifi,async close() {await started.close().catch(() => {})await backend.close()diff --git a/cli/e2e/harness/relayPhone.ts b/cli/e2e/harness/relayPhone.tsindex dfbc14dc0..5c653cdac 100644--- a/cli/e2e/harness/relayPhone.ts+++ b/cli/e2e/harness/relayPhone.ts@@ -13,7 +13,7 @@*/import { randomUUID } from 'node:crypto'import { WebSocket } from 'ws'-import type { Identity } from '../../src/lib/e2ee/core.js'+import { wrapPayload, type Identity } from '../../src/lib/e2ee/core.js'import { RelaySessionCrypto } from '../../src/lib/e2ee/relayClient.js'import type { FakeBackend } from './fakeBackend.js'@@ -141,17 +141,25 @@ export class RelayPhone {if (ws && ws.readyState === WebSocket.OPEN) ws.close()}- /** A sealed frame with no answer expected (a message). False when there is no session to send it on. */- send(type: string, payload: Record<string, unknown>): boolean {+ /** A sealed frame with no answer expected (a message). False when there is no session to send it on.+ * `always`: sealed whatever its type, as a client with a protocol of its own seals every request (the+ * Wi-Fi device's firmware; the CLI's client crypto seals only the types its apps send). */+ send(type: string, payload: Record<string, unknown>, always = false): boolean {if (!this.ready) return false- const sealed = this.crypto!.wrapOutgoing({ type, payload }) as PhoneFrame+ const sealed = (always ? this.sealAlways({ type, payload }) : this.crypto!.wrapOutgoing({ type, payload })) as PhoneFramethis.sealed.push(sealed)this.ws!.send(JSON.stringify(sealed))return true}+ /** The client crypto's own sealing, for any type: its session key and counter (test code reaches them). */+ private sealAlways(frame: { type: string; payload: Record<string, unknown> }): PhoneFrame {+ const crypto = this.crypto as unknown as { c2s: Uint8Array; c2sCounter: number }+ return { type: frame.type, payload: wrapPayload(crypto.c2s, 'p', crypto.c2sCounter++, frame.type, undefined, frame.payload) as unknown as Record<string, any> }+ }+/** A sealed request and its sealed answer. Fails at once with no session, or when the session ends. */- request(type: string, payload: Record<string, unknown> = {}, ms = 30_000): Promise<Record<string, any>> {+ request(type: string, payload: Record<string, unknown> = {}, ms = 30_000, always = false): Promise<Record<string, any>> {if (!this.ready) return Promise.reject(new Error(`no session to ask ${type} on`))const requestId = randomUUID()return new Promise((resolve, reject) => {@@ -163,7 +171,7 @@ export class RelayPhone {resolve: (answer) => { clearTimeout(timer); resolve(answer) },reject: (error) => { clearTimeout(timer); reject(error) },})- this.send(type, { ...payload, requestId })+ this.send(type, { ...payload, requestId }, always)})}diff --git a/cli/e2e/robustness.e2e.ts b/cli/e2e/robustness.e2e.tsindex b2a563ce0..cad616d3e 100644--- a/cli/e2e/robustness.e2e.ts+++ b/cli/e2e/robustness.e2e.ts@@ -187,7 +187,9 @@ describe('what the daemon survives', () => {})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' } })+ // The Wi-Fi device's service is the devices' process's too, on a link of its own: every call the desktop's+ // frames make into it fails there (services/process.ts).+ const d = await fresh({ env: { HARNESSD_TEST_FAULTS: 'dial,window,wifi.appFocus,wifi.card' } })await d.start()// The handshake itself asks the dial for its status.const desktop = await LocalClient.connect(d)@@ -207,7 +209,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] wifi failed · injected fault: wifi')+ await until('the Wi-Fi device\'s service to fail the desktop\'s focus', () => d.log().includes('[service wifi] appFocus failed · injected fault: wifi.appFocus') || null, 15_000, 100)expect(d.log()).not.toContain('local dispatch failed')expect(d.coresStarted()).toBe(1)desktop.close()diff --git a/cli/e2e/wifiDevice.e2e.ts b/cli/e2e/wifiDevice.e2e.tsnew file mode 100644index 000000000..8d82c25f3--- /dev/null+++ b/cli/e2e/wifiDevice.e2e.ts@@ -0,0 +1,211 @@+/**+ * The Wi-Fi device with the dials, in the devices' process (services/wifi.ts, docs/design/2026-10-06-core-+ * boundary-next.md, step 9), on the real daemon: a device paired with the machine reaches it through the+ * fake relay (harness/fakeWifiDevice.ts), its session the gateway's (in a process of its own), its service+ * the devices', every answer passing through the core:+ * - it is answered as it was in the core's process: its hello, its agents, a prompt with its receipt and the+ * turn's events, and the focus a window gives;+ * - the devices' process killed: its session stays, it is told to resync and served on, the receipt of a+ * prompt it sent before is kept, a new prompt works, and the core never restarts;+ * - two dials and a Wi-Fi device are three devices: each hears its own, the desk's turn reaches all three,+ * and a dial unplugged costs the other two nothing;+ * - its service failing to start costs it alone: the dials and the agents go on, and+ * `harness device receipt` says it is not running.+ */+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient, type Frame } from './harness/client.js'+import { until } from './harness/daemon.js'+import { Desk, devicesPids } from './harness/desk.js'+import type { DialMessage, FakeDial } from './harness/fakeDial.js'+import { FakeWifiDevice } from './harness/fakeWifiDevice.js'+import { startPhoneMachine, type PhoneMachine } from './harness/fleet.js'++const row = async (client: LocalClient, agentId: string) =>+ ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents).find((agent) => agent.id === agentId)+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId+const restarts = (w: PhoneMachine) => w.machine.daemon.log().split('\n').filter((line) => /\[harnessd\] service devices started .* restart \d+/.test(line)).length+const wifiConnections = (w: PhoneMachine) => w.machine.daemon.log().split('\n').filter((line) => line.includes('[services] wifi connected')).length++describe('the Wi-Fi device with the dials', () => {+ let world: PhoneMachine | undefined+ let device: FakeWifiDevice | undefined+ let window: LocalClient | undefined+ let desk: Desk | undefined+ afterEach(async () => {+ device?.close()+ window?.close()+ await desk?.close()+ await world?.close()+ world = undefined; device = undefined; window = undefined; desk = undefined+ })++ const fresh = async (env: Record<string, string> = {}) => {+ const dials = join(mkdtempSync(join(tmpdir(), 'wifi-dials-')), 'dials.json')+ writeFileSync(dials, '[]')+ const w = await startPhoneMachine({ wifiDevice: true, env: {+ CABLE_DISABLE: 'false',+ HARNESSD_TEST_DIAL_PORT: dials,+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',+ HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',+ ...env,+ } })+ world = w+ desk = new Desk(dials)+ const { backend, machine } = w+ onTestFailed(() => {+ console.log(`---- daemon log\n${machine.daemon.log().split('\n').slice(-200).join('\n')}`)+ console.log(`---- the device heard\n${JSON.stringify(device?.events().slice(-20))}`)+ })+ window = await LocalClient.connect(machine.daemon, { machineId: machine.machineId })+ const cwd = join(machine.daemon.projectsDir, 'wifi')+ mkdirSync(cwd, { recursive: true })+ const created = await window.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 60_000)+ expect(created.error, JSON.stringify(created)).toBeUndefined()+ const agentId: string = created.agent.id+ await until('the agent to bind its conversation', async () => (await row(window!, agentId))?.sessionId || null, 45_000, 500)+ device = new FakeWifiDevice({ backend, machineId: machine.machineId, identity: w.wifi.identity, machinePub: machine.identity.pub, token: w.wifi.token })+ await until('the machine to be on the relay', () => backend.nodeUp(machine.machineId) || null, 30_000)+ return { w, machine, window, agentId, device, desk: desk! }+ }+ /** The device's session and its application hello, retried until the service answers it. */+ const connect = async (d: FakeWifiDevice) => {+ await until('the device to open a session', async () => { await d.open(10_000); return true }, 60_000, 500)+ return until('the device\'s hello to be answered', async () => {+ const answer = await d.hello().catch(() => null)+ return answer?.proto === 1 ? answer : null+ }, 60_000, 500)+ }+ const windowTurn = async (client: LocalClient, agentId: string, content: string) => {+ const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)+ client.send('message', { agentId, content })+ await ended+ }+ const heard = (dial: FakeDial, t: string, since = 0, agentId?: string, ms = 45_000): Promise<DialMessage> =>+ dial.next((m) => m.t === t && (agentId === undefined || m.agentId === agentId), ms, t, since)+ const onTab = (client: LocalClient, agentIds: string[]): void => {+ client.send('app_swarms', { active: 't1', swarms: [{ id: 't1', name: 'Tab', agentIds, panes: agentIds.length }], tiles: [] })+ client.send('app_panes', { agentIds, foreground: true })+ }+ /** A prompt from the device, to its turn's end as the device hears it. */+ const deviceTurn = async (d: FakeWifiDevice, machineId: string, agentId: string, key: string, text: string) => {+ const since = d.mark()+ const sent = await d.ask('turn.send', { machineId, agentId, idempotencyKey: key, text })+ expect(sent, JSON.stringify(sent)).toMatchObject({ status: 'accepted', receipt: { idempotencyKey: key } })+ await d.nextEvent((e) => e.kind === 'turn.started' && e.agentId === agentId, `turn.started (${text})`, since)+ await d.nextEvent((e) => (e.kind === 'turn.done' || e.kind === 'turn.summary') && e.agentId === agentId, `the turn's end (${text})`, since)+ return sent+ }++ // In the core's process too, with every service (`HARNESSD_SERVICES=none`): the same doors, called.+ it.each([['from the devices\' process', {}], ['from the core\'s own, with every service there', { HARNESSD_SERVICES: 'none' }]] as const)(+ 'is answered %s as it was: its hello, its agents, a prompt and its receipt, a question, a window\'s focus', async (_where, env) => {+ const { w, machine, window, agentId, device } = await fresh(env)+ const hello = await connect(device)+ expect(hello).toMatchObject({ type: 'hello_result', proto: 1, machineId: machine.machineId })+ expect(hello.capabilities).toEqual(expect.arrayContaining(['agents.list', 'turn.send', 'receipt.get', 'focus.step', 'agent.subscribe']))+ const listed = await device.ask('agents.list')+ expect(listed.agents).toEqual([expect.objectContaining({ agentId, machineId: machine.machineId, engine: 'claude', state: 'idle' })])+ // A prompt from the device: typed into the pane, its turn's events, and its receipt.+ await deviceTurn(device, machine.machineId, agentId, 'first', 'hello from the device')+ const receipt = await until('the prompt\'s receipt to settle', async () => {+ const answer = await device.ask('receipt.get', { idempotencyKey: 'first' })+ return answer.receipt && !['queued', 'delivered'].includes(answer.receipt.state) ? answer.receipt : null+ }, 30_000, 500)+ expect(receipt).toMatchObject({ idempotencyKey: 'first', agentId, machineId: machine.machineId })+ // The window, too, saw the turn the device sent.+ expect(window.frames.some((f) => f.type === 'turn_started' && f.agentId === agentId)).toBe(true)+ // A window moving to the agent moves the device's focus.+ const since = device.mark()+ window.send('app_focus', { agentId })+ const focus = await device.nextEvent((e) => e.kind === 'focus.changed' && e.payload?.focus?.agentId === agentId, 'focus.changed', since)+ expect(focus.payload.focus).toMatchObject({ machineId: machine.machineId, agentId })+ expect((await device.ask('focus.get')).focus).toMatchObject({ agentId })+ // A question the agent asks, answered from the device: through the core, into the pane.+ const asked = device.mark()+ window.send('message', { agentId, content: '!ask' })+ const open = await device.nextEvent((e) => e.kind === 'question.open' && e.agentId === agentId, 'question.open', asked)+ const question = (open.payload.questions as Array<Record<string, any>>)[0]+ const answered = await device.ask('question.answer', { machineId: machine.machineId, agentId, idempotencyKey: 'answer-1',+ questionRequestId: open.payload.questionRequestId, answers: { [question.key ?? question.q]: 'Coffee' } })+ expect(answered).toMatchObject({ status: 'accepted', receipt: { state: 'completed' } })+ await device.nextEvent((e) => e.kind === 'question.close' && e.agentId === agentId, 'question.close', asked)+ // `harness device receipt`, through the core's hook server, asks the service in its process.+ const credential = readFileSync(join(machine.daemon.dataDir, 'hook-credential'), 'utf8').trim()+ const deviceId = (await device.ask('receipt.get', { idempotencyKey: 'first' })).receipt+ expect(deviceId).toBeTruthy()+ const status = await fetch(`http://127.0.0.1:${machine.daemon.port}/api/autonomous-device/status`, { headers: { authorization: `Bearer ${credential}` } })+ expect(status.status).toBe(200)+ expect(w.machine.daemon.coresStarted()).toBe(1)+ })++ it('the devices\' process killed: its session stays, it is told to resync and served on, its receipts kept, and the core never restarts', async () => {+ const { w, machine, window, agentId, device } = await fresh()+ const hello = await connect(device)+ await deviceTurn(device, machine.machineId, agentId, 'before', 'before the kill')+ const sessions = device.link.sessions+ const since = device.mark()+ for (const pid of devicesPids(machine.daemon)) process.kill(pid, 'SIGKILL')+ // Every agent and window goes on meanwhile.+ await windowTurn(window, agentId, 'while the devices are down')+ await until('the master to restart the devices', () => restarts(w) >= 1 || null, 30_000, 200)+ await until('the Wi-Fi device to connect again', () => wifiConnections(w) >= 2 || null, 30_000, 200)+ // Told to resync on the session it had: the documented way back after the daemon's own restart.+ const resync = await device.nextEvent((e) => e.type === 'resync', 'resync', since)+ expect(resync).toMatchObject({ reason: 'instance_changed' })+ expect(resync.serverInstanceId).not.toBe(hello.serverInstanceId)+ expect(device.link.sessions).toBe(sessions)+ // Served on without a new hello: its agents, the receipt of the prompt it sent before, a new prompt.+ expect((await device.ask('agents.list')).agents).toEqual([expect.objectContaining({ agentId })])+ expect((await device.ask('receipt.get', { idempotencyKey: 'before' })).receipt).toMatchObject({ idempotencyKey: 'before', agentId })+ await deviceTurn(device, machine.machineId, agentId, 'after', 'after the kill')+ expect(machine.daemon.coresStarted()).toBe(1)+ })++ it('two dials and a Wi-Fi device are three devices: each its own, the desk\'s turn on all three, and a dial unplugged costs the others nothing', async () => {+ const { machine, window, agentId, device, desk } = await fresh()+ onTab(window, [agentId])+ const a = await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')+ const b = await desk.plug('E2E-B', 'e2:e0:00:00:00:0b')+ await heard(a, 'agents.end')+ await heard(b, 'agents.end')+ await connect(device)+ // A turn from the device reaches both dials' tiles.+ const sinceA = a.messages.length, sinceB = b.messages.length+ await deviceTurn(device, machine.machineId, agentId, 'three', 'one turn, three devices')+ await heard(a, 'summary', sinceA, agentId)+ await heard(b, 'summary', sinceB, agentId)+ // Each dial its own settings, through the Devices tab; the Wi-Fi device hears none of theirs.+ const settingsA = a.messages.length, settingsB = b.messages.length+ expect(await window.request('harness_device_settings', { id: 'E2E-A', patch: { brightness: 10 } })).toMatchObject({ ok: true })+ await heard(a, 'settings.set', settingsA)+ expect(b.messages.slice(settingsB).some((m) => m.t === 'settings.set')).toBe(false)+ expect(device.events().some((e) => JSON.stringify(e).includes('brightness'))).toBe(false)+ // Dial A unplugged: dial B and the Wi-Fi device carry on.+ await desk.unplug('E2E-A')+ const sinceB2 = b.messages.length+ await deviceTurn(device, machine.machineId, agentId, 'two', 'after a dial left')+ await heard(b, 'summary', sinceB2, agentId)+ expect(machine.daemon.coresStarted()).toBe(1)+ })++ it('its service failing to start costs it alone: the dials and the agents go on, and its receipts say it is not running', async () => {+ const { machine, window, agentId, device, desk } = await fresh({ HARNESSD_TEST_FAULTS: 'wifi' })+ onTab(window, [agentId])+ const dial = await desk.plug('E2E-A', 'e2:e0:00:00:00:0a')+ await heard(dial, 'agents.end')+ await until('the Wi-Fi device\'s service to be left off', () => machine.daemon.log().includes('[service wifi] did not start · injected fault: wifi') || null, 30_000, 200)+ await device.open(30_000)+ // Its requests go unanswered, as frames lost on the way: it asks again later, by the same keys.+ await expect(device.ask('hello', { proto: 1 }, 5_000)).rejects.toThrow()+ const since = dial.messages.length+ await windowTurn(window, agentId, 'the dial and the agent go on')+ await heard(dial, 'summary', since, agentId)+ const credential = readFileSync(join(machine.daemon.dataDir, 'hook-credential'), 'utf8').trim()+ const receipt = await fetch(`http://127.0.0.1:${machine.daemon.port}/api/autonomous-device/receipt?deviceId=${encodeURIComponent('A'.repeat(43) + '=')}&idempotencyKey=k`, { headers: { authorization: `Bearer ${credential}` } })+ expect(receipt.status).toBe(503)+ expect(machine.daemon.coresStarted()).toBe(1)+ })+})diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 4a2faf9a8..8392d1e48 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -150,14 +150,17 @@ const WALK_TIMEOUT_MS = 60_000* 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. Then 2,240 (step 9,* D2): the devices' link to their own process and its routes, as every service there has, 2,213 to 2,232.+ * Then 2,230 (step 9, D3): the Wi-Fi device's wiring went with them (core/wifi.ts, core/wifiAgents.ts),+ * 2,232 lines to 2,227, though its link to the devices' process came in.*/-const RUN_FOREGROUND_BUDGET = 2_240+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. 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+ * became the devices' own (step 9, D1), 1,207 → 1,194. Then 1,195 when the Wi-Fi device's relay left+ * it for the devices' process (step 9, D3): the socket hands its sessions' events on (core/wifi.ts). */+const BACKEND_SOCKET_BUDGET = 1_195/** Exceptions, each with its reason. Keep this short. */const SERVICE_MAY_IMPORT: Record<string, string> = {@@ -262,7 +265,12 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {// to run them in its process instead (services/inline.ts). With them went the dial (cable/), the window// bridges, the fleet's router and its lane to the owner's other machines, and the voice router with its// engine worker pool, and the E2EE code the fleet read the linked machines with (lib/e2ee/machinePeers.ts).-const CORE_CLOSURE_BUDGET = 77_800+//+// Then at 75,746 in 345 (step 9, D3), from 77,669 in 358: the Wi-Fi device's service, its relay, its+// receipts and streams and its Store preparations run with the dials (services/wifi.ts, in the devices'+// process; the core's side is core/wifi.ts and core/wifiLink.ts), and with them went the Store's installs+// and catalog, which only the device's preparations reached from the core.+const CORE_CLOSURE_BUDGET = 75_850/** 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[] = [@@ -282,34 +290,13 @@ const EDGE: RegExp[] = [* The edge files the core's process still loads, each with the step of the plan that takes it out. The* list only shrinks: an entry no longer reached fails the test, so remove it with the move that ends it.*/-/** The Wi-Fi device lists, installs and checks harnesses with the Store's code, in the core's process- * (lib/autonomous-device/storeRuntime.ts). It reaches the Store through the Store's process once a port- * 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'-const CORE_MAY_REACH: Record<string, string> = {'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,- 'dsh/lock.ts': STORE_BYPASS,- 'dsh/registry.ts': STORE_BYPASS,- 'dsh/service.ts': STORE_BYPASS,- '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/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',- 'lib/autonomous-device/relay.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',- 'lib/autonomous-device/resultContract.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',- 'lib/autonomous-device/resultEvidence.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',- 'lib/autonomous-device/resultJournal.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',- 'lib/autonomous-device/service.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',- 'lib/autonomous-device/store.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',- 'lib/autonomous-device/storeContract.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',- 'lib/autonomous-device/storeRuntime.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',- 'lib/autonomous-device/stream.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',+ 'dsh/lock.ts': 'with dsh/builtins.ts',+ 'dsh/registry.ts': 'with dsh/builtins.ts, which checks the bundled harnesses against the catalog\'s entries',+ 'dsh/updates.ts': 'with dsh/builtins.ts',+ 'lib/autonomous-device/localApi.ts': 'the hook server\'s routes for `harness device`, which the core serves: the pairings they answer are the gateway\'s, the receipts the Wi-Fi device\'s service\'s','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',diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 427d21088..74b698760 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -3,8 +3,7 @@ import { SHARE_REQUESTS, TEAMS_REQUESTS, type Asker, type BackendNotice, type Gaimport { ServiceUnavailableError } from './core/serviceHost.js'import type { ActivityFrame } from './lib/turnActivity.js'import { MonitorCompletions } from './lib/harnessMonitor.js'-import { deviceRelayOverGateway, type DeviceRelayOverGateway } from './lib/autonomous-device/overGateway.js'-import type { AutonomousDeviceService, AutonomousDeviceFrame } from './lib/autonomous-device/service.js'+import type { WifiCore } from './core/wifi.js'/*** BackendSocket — the clients' hub and the request dispatch: the windows and tools on this computer* (localWsServer.ts), and the remote clients the gateway hands on (gateway/gateway.ts), each in its own@@ -339,12 +338,13 @@ export class BackendSocket {frame: (connId, frame, transport, role) => this.enqueueDown(frame, connId, transport, role),binary: (connId, clear) => this.enqueueTerminalBinary(connId, clear),client: (connId, client) => {+ this.wifi?.session(connId, client)if (client) { this.remoteClients.set(connId, client); return }if (!this.remoteClients.delete(connId)) returnthis.viewerForwarder.closeConnection(connId); this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)},disconnected: async (connId) => {- this.autonomousDeviceRelay?.drop(connId)+ this.wifi?.dropped(connId)this.remoteClients.delete(connId)this.viewerForwarder.closeConnection(connId)this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)@@ -394,26 +394,21 @@ export class BackendSocket {},revoked: () => this.onRevoked?.(),busy: () => this.onBusy?.(),- device: async (connId, frame, opened) => { await this.autonomousDeviceRelay?.handle(connId, frame, opened) },- deviceRevoked: (identity) => this.autonomousDeviceRelay?.revoke(identity),+ device: (connId, frame, opened) => this.wifi?.request(connId, frame, opened),+ deviceRevoked: (identity) => this.wifi?.revoked(identity),toWindows: (frame) => this.sendLocal(frame),}- /** The Wi-Fi device's application protocol, beside the device service it answers for, over the- * gateway's sessions (lib/autonomous-device/overGateway.ts). */- private autonomousDeviceRelay?: DeviceRelayOverGateway- setAutonomousDeviceService(service: AutonomousDeviceService, onRemoteRevoke: (identity: string) => void): void {- this.autonomousDeviceRelay = deviceRelayOverGateway({- client: (connId) => this.remoteClients.get(connId),- send: (connId, type, payload) => { this.throughGateway('device', (gateway) => gateway.device(connId, type, payload), false) },- service, machineId: this.machineId, onReady: () => this.onCommanderJoin?.(), onRemoteRevoke,- onClient: (connId, identity) => this.gatewayPort?.deviceClient(connId, identity),- })+ /** The Wi-Fi device's sessions and requests, as the gateway hands them on, for its service with the+ * devices (core/wifi.ts, services/wifi.ts). */+ private wifi?: WifiCore['fromGateway']+ useWifi(wifi: WifiCore['fromGateway']): void { this.wifi = wifi }+ /** The Wi-Fi device's answers and events, sealed to one session; and which identity's app said hello on+ * one. Through the gateway, guarded as every frame of the core's is. */+ deviceFrame(connId: string, type: string, payload: Record<string, unknown>): void {+ this.throughGateway('device', (gateway) => gateway.device(connId, type, payload), false)}- /** Wi-Fi device sessions on a direct link that said hello to the device service. */- directAutonomousDeviceSessions(): number { return this.autonomousDeviceRelay?.directSessions() ?? 0 }- autonomousDeviceConnected(): boolean { return this.autonomousDeviceRelay?.connected() ?? false }- emitAutonomousDeviceEvent(frame: AutonomousDeviceFrame, deviceId?: string): void { this.autonomousDeviceRelay?.emit(frame, deviceId) }+ deviceClient(connId: string, identity: string | null): void { this.toGateway('device', (gateway) => gateway.deviceClient(connId, identity)) }setTerminalStreamManager(manager: TerminalStreamManager): void {this.terminalStreams = managerdiff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.mdindex 194385230..c163aeeb0 100644--- a/cli/src/core/AGENTS.md+++ b/cli/src/core/AGENTS.md@@ -56,4 +56,7 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGEwindow's sessions to another machine or a shared harness, and the fleet's lane's sealing(`core.account.lane`). `devicesLink.ts`: the devices in their own process (the dials, the windowbridges, the fleet): what the core tells them, what it asks with a deadline and a fallback, and what it- answers them.+ answers them. `wifi.ts`: the Wi-Fi device, as the core keeps it wherever its service runs (who said+ hello, which transcripts and streams it follows, the focus revision, and the check on every answer it+ sends a device); `wifiAgents.ts`: its doors into the core (the agents as it lists them, a prompt, an+ agent made for a Store harness); `wifiLink.ts`: its service in the devices' process.diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex b456b454c..f324d62b4 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'-import { 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 { 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, WIFI_FALLBACKS, WIFI_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@@ -77,6 +77,7 @@ describe('the core API services stand on', () => {hasWindow: vi.fn(() => true),devicesChanged: vi.fn(),dialWatching: vi.fn(),+ wifi: WIFI_OFF,log: vi.fn(),})@@ -171,6 +172,32 @@ describe('the core API services stand on', () => {expect(FAIL).toBeTypeOf('symbol')})+ it('answers, when the Wi-Fi device\'s service is off, nothing to its devices and "not running" to a receipt', () => {+ expect(readFallback(WIFI_FALLBACKS.receipt)).toEqual({ deferred: true, value: { unavailable: true } })+ for (const member of ['request', 'resume', 'appFocus', 'stop'] as const) {+ expect(readFallback(WIFI_FALLBACKS[member]), member).toEqual({ deferred: true, value: undefined })+ }+ for (const member of ['session', 'dropped', 'revoked', 'card', 'turnStarted', 'turnEnded', 'stream', 'transcript', 'delivery',+ 'dispatched', 'inputStatus', 'agentGone', 'revealed'] as const) {+ expect(WIFI_FALLBACKS[member], member).toBeUndefined()+ }+ })++ it('gives a service that is not the Wi-Fi device\'s doors that list, send, make and move nothing', async () => {+ expect(await WIFI_OFF.view()).toEqual({ agents: [], store: [], hasWindow: false })+ expect(await WIFI_OFF.stop('a')).toBe(false)+ expect(await WIFI_OFF.answer('a', 'r', {})).toBe(false)+ expect(await WIFI_OFF.create('p', 'claude', '/w')).toEqual({ ok: false, error: 'UNSUPPORTED' })+ expect(await WIFI_OFF.stepFocus('next')).toBe('no_app')+ expect(WIFI_OFF.scroll('down', 0, 0)).toBe(false)+ expect(WIFI_OFF.focusApp('a', 0, 'r')).toBe(false)+ await expect(WIFI_OFF.submit('a', 't', 'd')).resolves.toBeUndefined()+ for (const call of [() => WIFI_OFF.cancel('d'), () => WIFI_OFF.started('a', 't'),+ () => WIFI_OFF.reveal('o', 'a'), () => WIFI_OFF.send('c', 'i', 't', {}), () => WIFI_OFF.hello('c', null), () => WIFI_OFF.joined(), () => WIFI_OFF.ready(),+ () => WIFI_OFF.unpaired('i'), () => WIFI_OFF.focus('r'), () => WIFI_OFF.transcripts('a', 0), () => WIFI_OFF.watching([]),+ () => WIFI_OFF.streams([])]) expect(call()).toBeUndefined()+ })+it('falls back, when the teams fail, to an undo that has nothing to undo, and holds no pane for a team', () => {const undo = TEAMS_FALLBACKS.prepare as () => voidexpect(undo()).toBeUndefined()@@ -178,7 +205,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, devices: null, monitor: null, orchestrator: null, sharing: null })+ expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: 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 ccc527e60..5fbdcfadf 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -15,6 +15,8 @@ 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 '../lib/notificationRead.js'+import type { AutonomousDeviceAgent, AutonomousDeviceDelivery, AutonomousDeviceReceipt } from '../lib/autonomous-device/service.js'+import type { StoreAgent } from '../lib/autonomous-device/store.js'import type { AgentDshContext } from '../lib/agentFrame.js'import type { GridAccess } from '../lib/gridAttach.js'import type { createHarnessResourcesReader } from '../lib/harnessResources.js'@@ -33,6 +35,7 @@ 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 type { DeviceInputStatus } from './deviceInput.js'import { FAIL, later, readFallback, ServiceUnavailableError, type PortFallbacks } from './serviceHost.js'export type { RouteAnswer }@@ -227,6 +230,53 @@ export interface CoreApi {* serves and the machine it serves as. An experiment writes them into the prompts of the agents it runs* (`… orchestrator --port 18473 --machine …`). */daemon: DaemonAddress+ /** The Wi-Fi device's doors into the core (services/wifi.ts): each one call it made when it ran here. */+ wifi: {+ /** What it lists and reads in line (`WifiView`), asked again before each request it answers. */+ view(): Promise<WifiView>+ /** A device's prompt into a live agent, through the pane's write lock, as delivery `deliveryId`. Settles+ * once the lock has taken it: what it said of the prompt meanwhile is the reply's to carry. */+ submit(agentId: string, text: string, deliveryId: string): Promise<void>+ /** A queued delivery the device no longer stands behind (it was unpaired). */+ cancel(deliveryId: string): void+ /** The agent's transcript shows the device's prompt began its turn: the pane's lock moves on. */+ started(agentId: string, text: string): void+ /** Stop a live agent's turn; resolves whether it stopped. */+ stop(agentId: string): Promise<boolean>+ /** Answer a live agent's question, never a permission dialog; resolves whether the terminal took it. */+ answer(agentId: string, requestId: string, answers: Record<string, string>): Promise<boolean>+ /** Start an agent for an installed Store harness in `cwd`, with the device's fixed, safe launch+ * arguments; refused when another agent works there. */+ create(packageId: string, engine: string, cwd: string): Promise<ForkResult>+ /** Move the window's focus one agent along the desk, the dial's way; 'no_app' without a window. */+ stepFocus(direction: 'next' | 'previous', currentAgentId?: string): Promise<{ machineId: string; agentId: string } | 'no_agents' | 'no_app'>+ /** A stroke on the device's glass for the window's terminal; false without a window. */+ scroll(phase: 'down' | 'move' | 'up', dy: number, velocity: number): boolean+ /** Ask the window to select an agent (`device_focus`); false without a window. */+ focusApp(agentId: string, expiresAt: number, focusRevision: string): boolean+ /** Ask the window to open the agent a Store preparation made (`device_prepare_open`). */+ reveal(operationId: string, agentId: string): void+ /** An answer or event for one device session, sealed to it by the gateway, if the session is still+ * that identity's device. */+ send(connId: string, identity: string, type: string, payload: Record<string, unknown>): void+ /** Which identity's app said hello on a session (null: it left): the core counts it as watching. */+ hello(connId: string, identity: string | null): void+ /** A device said hello: what the agents are doing is sent again for it. */+ joined(): void+ /** It is built and serving: the gateway may connect the devices' direct links, which a service that+ * could not be built would leave unanswered. */+ ready(): void+ /** A device asked to be unpaired, over its session: its pairing goes. */+ unpaired(identity: string): void+ /** The focus revision, as it changes: a window's stale selection is refused against it. */+ focus(revision: string): void+ /** It no longer reads this agent's transcript, as of the `seen`th prompt the core told it of. */+ transcripts(agentId: string, seen: number): void+ /** The agents whose transcripts it reads, said as it starts. */+ watching(agentIds: string[]): void+ /** The agents a device subscribed to: their tools' events are sent too, not only the answer's text. */+ streams(agentIds: string[]): void+ }}/** An agent to create, as an experiment asks for one (the orchestrator's Director and specialists). */@@ -667,7 +717,7 @@ export interface DevicesPort {routeTask(text: string): Promise<RouteAnswer>/** ⌘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). */+ /** The Wi-Fi device borrowing the dial's walk along the desk, through the core (`CoreApi.wifi.stepFocus`). */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@@ -693,6 +743,96 @@ export const DEVICES_FALLBACKS: PortFallbacks<DevicesPort> = {stepFocus: later('no_agents'), scroll: undefined, engines: undefined, commanders: undefined, stop: later(undefined),}+/*+ * The Wi-Fi device (services/wifi.ts, lib/autonomous-device/): a paired device that speaks its own+ * protocol (docs/autonomous-device-integration.md) over an E2EE session the gateway holds, on its direct+ * link or the relay. It runs beside the dials, in the devices' process (step 9, D3): the core tells it+ * what the agents do and the requests its sessions bring, and it answers them through the core, which+ * checks that each answer goes to the session it came from.+ */++/** What the core holds for the Wi-Fi device's service, said again each time it starts: every device+ * session the gateway holds, which of them said their app's hello (served on, told to resync, as after a+ * daemon restart), and the window that has the person's attention. */+export interface WifiResume {+ sessions: Array<{ connId: string; client: RemoteClient }>+ helloed: Array<{ connId: string; identity: string }>+ focus: { machineId: string; agentId: string; connId: string } | null+}++/** A receipt the device asked for by `harness device receipt`, or the service is not there to say. */+export type WifiReceipt = { receipt: AutonomousDeviceReceipt | null } | { unavailable: true }++/** What the core lists for the Wi-Fi device, read in line while it answers a request: the agents as it+ * shows them, the Store's evidence on each, and whether a window is attached to show one. */+export interface WifiView {+ agents: AutonomousDeviceAgent[]+ store: StoreAgent[]+ hasWindow: boolean+}++/**+ * The core's calls into the Wi-Fi device: its sessions and their requests, as the gateway hands them on,+ * and what the agents do that it follows (cards, turns, live text, its own deliveries into the panes and+ * the transcript lines that prove them). All notices but `receipt`, which a person asked for.+ */+export interface WifiPort {+ /** A device session the gateway holds, as it changes (null: it lost its session). */+ session(connId: string, client: RemoteClient | null): void+ /** A device's request, as it arrived sealed and as its session opened it (null: it would not open).+ * Settles once the service has taken it: what the core says after it is heard after it. */+ request(connId: string, frame: Record<string, unknown>, opened: Record<string, unknown> | null): Promise<void>+ /** A device's connection closed. */+ dropped(connId: string): void+ /** The owner unpaired a device here; its sessions are gone. */+ revoked(identity: string): void+ /** What the core holds for it (`WifiResume`), as it starts. Settles once the sessions are served again. */+ resume(state: WifiResume): Promise<void>+ /** A frame bound for the devices, as it is sent, with the turn's whole answer for a summary. */+ card(frame: Record<string, unknown>, fullText?: string): void+ turnStarted(agentId: string): void+ turnEnded(agentId: string, aborted: boolean): void+ /** An agent's live events, for the devices that subscribed to it. */+ stream(agentId: string, events: readonly LiveEvent[]): void+ /** A transcript line of an agent the device sent a prompt to, which proves what its turn did. */+ transcript(agentId: string, sessionId: string, engine: string, line: string): void+ /** Its own deliveries into the panes, as the pane's write lock moves them on (core/deviceInput.ts). */+ delivery(event: AutonomousDeviceDelivery): void+ dispatched(agentId: string, deliveryId: string, text: string, sessionId?: string): void+ inputStatus(event: DeviceInputStatus): void+ agentGone(agentId: string): void+ /** A window moved to an agent (null: it left one), by its connection. Settles once it is applied. */+ appFocus(machineId: string, agentId: string | null, connId: string): Promise<void>+ /** A window opened the agent a device's Store preparation made. */+ revealed(operationId: string, agentId: string): void+ /** `harness device receipt`: what became of one of a device's requests. */+ receipt(deviceId: string, idempotencyKey: string): Promise<WifiReceipt>+ stop(): Promise<void>+}++/** The Wi-Fi device's doors, for a service that is not it: nothing is listed, sent, made or moved. */+export const WIFI_OFF: CoreApi['wifi'] = {+ view: async () => ({ agents: [], store: [], hasWindow: false }),+ submit: async () => {}, cancel: () => {}, started: () => {},+ stop: async () => false, answer: async () => false,+ create: async () => ({ ok: false, error: 'UNSUPPORTED' }),+ stepFocus: async () => 'no_app', scroll: () => false, focusApp: () => false, reveal: () => {},+ send: () => {}, hello: () => {}, joined: () => {}, ready: () => {}, unpaired: () => {}, focus: () => {},+ transcripts: () => {}, watching: () => {}, streams: () => {},+}++/**+ * What the core gets when the Wi-Fi device's service is off: its devices hear nothing (a request they sent+ * is unanswered, which they retry with the same key, as after a lost frame) and `harness device receipt`+ * says it is not running.+ */+export const WIFI_FALLBACKS: PortFallbacks<WifiPort> = {+ session: undefined, request: later(undefined), dropped: undefined, revoked: undefined, resume: later(undefined), card: undefined,+ turnStarted: undefined, turnEnded: undefined, stream: undefined, transcript: undefined, delivery: undefined,+ dispatched: undefined, inputStatus: undefined, agentGone: undefined, appFocus: later(undefined), revealed: undefined,+ receipt: later({ unavailable: true }), stop: later(undefined),+}+/** The gateway: the relay and its end-to-end encryption (docs/design/2026-10-06-core-boundary-next.md,* "Relay and E2EE", step 10). It holds the backend link, the E2EE sessions and the keys; every remote@@ -963,13 +1103,14 @@ export interface CorePorts {workspaces: WorkspacesPort | nullteams: TeamsPort | nulldevices: DevicesPort | null+ wifi: WifiPort | nullmonitor: MonitorPort | nullorchestrator: OrchestratorPort | nullsharing: SharingPort | null}export function emptyPorts(): CorePorts {- return { search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, monitor: null, orchestrator: null, sharing: null }+ return { search: null, viewers: null, models: null, workspaces: null, teams: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null }}export interface CoreApiDeps {@@ -1016,6 +1157,8 @@ export interface CoreApiDeps {hasWindow: CoreApi['clients']['hasWindow']devicesChanged: CoreApi['clients']['devicesChanged']dialWatching: CoreApi['clients']['dialWatching']+ /** The Wi-Fi device's doors (core/wifi.ts). */+ wifi: CoreApi['wifi']log?: (line: string) => void}@@ -1023,7 +1166,7 @@ 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, machine, activityText,- signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, log = (line) => console.warn(line),+ signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, 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.@@ -1069,5 +1212,6 @@ export function createCoreApi({},},daemon,+ wifi,}}diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 15a607268..cdd8b1b79 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -10,7 +10,7 @@* the other controller lazily: each one calls into the other.*/import { AutonomousDeviceInput, type DeviceInputDeps } from './deviceInput.js'-import type { AutonomousDeviceService } from '../lib/autonomous-device/service.js'+import type { WifiFeed } from './wifi.js'import type { CommandCodeNormalizer } from '../engines/commandcode/normalizer.js'import { deviceErrorText } from './cardText.js'import { adaptSlashCommand } from '../lib/goalCommand.js'@@ -38,8 +38,8 @@ export interface InputDeps {/** Whether a team delivery still holds control of its pane. */canWrite: (deliveryId: string) => boolean}- /** The Harness device service, once it exists. */- device: () => Pick<AutonomousDeviceService, 'delivery' | 'inputDispatched' | 'inputStatus' | 'agentGone'> | undefined+ /** The Wi-Fi device's service, wherever it runs (core/wifi.ts). */+ device: () => Pick<WifiFeed, 'delivery' | 'inputDispatched' | 'inputStatus' | 'agentGone'> | undefined/** The app (`send`) and the dial (`sendCommander`). */clients: { send(frame: Frame): void; sendCommander(frame: Frame): void }agentIdFor: (sessionId: string) => stringdiff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex e1debef91..73f066201 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -10,8 +10,6 @@* the core with `__run`.*/import { ensureBundledCoreHarnesses } from '../dsh/builtins.js'-import { createDeviceStore, deviceStoreAgents } from '../lib/autonomous-device/storeRuntime.js'-import { runningDevicePart, startDevicePart } from '../lib/autonomous-device/parts.js'import { readFileSync, writeFileSync, openSync, existsSync, rmSync, statSync } from 'fs'import { join } from 'path'import { execFile, spawn, spawnSync } from 'child_process'@@ -93,7 +91,7 @@ import { createLastTurnReader } from './transcripts/lastTurn.js'import { createRecaps } from './turns/recaps.js'import { createUpdateHandoff, probeStagedMaster, probeVerdict } from './updateHandoff.js'import { createHeartbeats } from './turns/heartbeats.js'-import { createEventFunnel, outsideConsumers } from './turns/funnel.js'+import { createEventFunnel } from './turns/funnel.js'import { createAgyBackstop } from './turns/agyBackstop.js'import { createIngest } from './transcripts/ingest.js'import { createTurnHooks } from './turns/turnHooks.js'@@ -121,7 +119,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, 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 { 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, WIFI_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'@@ -148,7 +146,9 @@ import { publishHookRoute } from '../lib/hookRoutes.js'import { commandBarService } from '../lib/commandBar.js'import { BackendSocket, isLocalClientId } from '../backendSocket.js'import { createGatewayLink, laneOf } from './gatewayLink.js'-import { AutonomousDeviceService } from '../lib/autonomous-device/service.js'+import { createWifiCore } from './wifi.js'+import { createWifiLink } from './wifiLink.js'+import { wifiDoors } from './wifiAgents.js'import { autonomousDeviceLocalRequest } from '../lib/autonomous-device/localApi.js'import { attachLocalWsServer, LOCAL_WS_PATH, LOCAL_WS_PROTOCOL_VERSION } from '../localWsServer.js'import { TERMINAL_BINARY_VERSION } from '../lib/terminalBinary.js'@@ -167,8 +167,6 @@ import { AgentCreationReceipts } from '../lib/agentCreationReceipt.js'import { agentFrame, lastActivityAt, type AgentFrame } from '../lib/agentFrame.js'import { forgetAgentProject } from '../lib/agentProject.js'import { agentTokenUsage } from '../lib/agentTokenUsage.js'-import { DeviceResultJournal } from '../lib/autonomous-device/resultJournal.js'-import { adaptSlashCommand } from '../lib/goalCommand.js'import { RuntimeProfileManager, type RuntimeModelOption } from '../lib/runtimeProfile.js'import { RuntimeProfileController } from '../lib/runtimeProfileController.js'import { installTimestampedConsole, sid, prepareLogFile, trimLogFile, LOG_CHECK_INTERVAL_MS } from '../lib/log.js'@@ -629,6 +627,30 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The experiments: the orchestrator's turns, and those of the experiments after it.deliverers: new Set(Object.keys(EXPERIMENTS)),})+ const ports = emptyPorts()+ // The Wi-Fi device's service runs with the dials (services/wifi.ts); what the core reads in line of it+ // (who is watching, which transcripts and streams it follows, the focus revision) and the check on every+ // answer it sends a device are here (core/wifi.ts). Its doors are the calls it made when it ran here.+ const machineIdNow = (): string => backendRef?.machineId ?? ''+ const wifiCore = createWifiCore({+ port: () => ports.wifi,+ gateway: {+ device: (connId, type, payload) => backendRef?.deviceFrame(connId, type, payload),+ deviceClient: (connId, identity) => backendRef?.deviceClient(connId, identity),+ revokeIdentity: (identity) => gatewayOps.revokeIdentity(identity),+ },+ remoteClient: (connId) => backendRef?.remoteClient(connId) ?? null,+ fullText: (agentId) => mirror.lastFullText(registry.byAgent(agentId)?.sessionId ?? agentId),+ joined: () => backendRef?.onCommanderJoin?.(),+ // Its direct links are the gateway's, started only once it serves: a device they connected to a service+ // that could not be built would be answered by nothing.+ ready: () => gatewayOps.wifiService(true),+ doors: wifiDoors({+ registry, machineId: machineIdNow, displayName: projectDisplayName, running: (sessionId) => turnStartedAt.has(sessionId),+ socket: () => backendRef ?? null, deviceInput: () => deviceInput, answer: (request) => questions.answer(request),+ stop: (agentId) => cancelAgent(agentId, true), devices: () => ports.devices,+ }),+ })const coreApi = createCoreApi({// Agents' terminals: a literal-argv launch, and a read-only view for Share's observers (core/terminalWatch.ts).terminals: { ...createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder: (cwd) => !!backendRef?.purgeAgentService?.blocksFolder(cwd) }), watch: terminalWatch.watch },@@ -688,6 +710,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {sendToWindow: (connId, frame) => localWsServerRef?.sendToWindow(connId, frame) ?? false,hasWindow: () => backendRef?.hasLocalClient() ?? false,devicesChanged: (payload) => backendRef?.send({ type: 'harness_devices_changed', payload }),+ wifi: wifiCore.api,dialWatching: (watching) => {const attached = watching && !dialWatchingdialWatching = watching@@ -733,7 +756,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {answers: answer.answers, expectedQuestions: answer.questions, selectedLabels: answer.selections, freeTextKeys: answer.freeTextKeys })).ok,},})- const ports = emptyPorts()// Each service starts and is called through the host, so one that fails is logged and left off and// the core carries on without it (core/serviceHost.ts).const serviceHost = createServiceHost(ports, { faults: testFaults(process.env.HARNESSD_TEST_FAULTS) })@@ -768,8 +790,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {}}}- let deviceStoreRef: ReturnType<typeof createDeviceStore> | undefined- let autonomousDeviceService: AutonomousDeviceService | undefinedlet devicePartsBuilt = falselet appFormWindow: { machineId: string; connId: string } | undefinedlet appVoiceFocus: { machineId: string; agentId: string; connId: string } | undefined@@ -821,6 +841,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {signedIn: !!session?.machineId, tokens: auth, backend: (method, path) => proxyBackend(method, path), account: account(),})backend.useGateway(gateway.port)+ backend.useWifi(wifiCore.fromGateway)const gatewayOps = gateway.opsdaemonBoot.openRequests = () => backend.openRequests()const teams: TeamsPort = {@@ -866,7 +887,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {* the cards are made for it in line, without asking the devices, which may be in another process. */const cableWatchingLocal = (): boolean => dialWatching- const deviceIsWatching = (): boolean => backend.hasCommander() || cableWatchingLocal() || backend.autonomousDeviceConnected()+ const deviceIsWatching = (): boolean => backend.hasCommander() || cableWatchingLocal() || wifiCore.connected()/** Anyone who can DRAW a question: a device, a cabled dial, or a desktop window on this computer. */const someoneCanAnswer = (): boolean => deviceIsWatching() || backend.hasLocalClient()const terminalStreams = new TerminalStreamManager({@@ -981,7 +1002,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {normalizers,watcher,cursorDiscovery,- device: () => autonomousDeviceService,+ device: () => wifiCore.feed,runtimeProfiles,captureTerminal,emit: (sessionId, events, opts) => emitSessionEvents(sessionId, events, opts),@@ -1017,7 +1038,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {},canWrite: (deliveryId) => teams.canWrite(deliveryId),},- device: () => autonomousDeviceService,+ device: () => wifiCore.feed,clients: backend,// Declared further down: read when an error is reported, never now.agentIdFor: (sessionId) => agentIdFor(sessionId),@@ -1152,6 +1173,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {state: () => ({ desk: appPaneAgents, foreground: appWindowForeground, swarms: appSwarmsLatest, unread: appUnreadLatest,focus: windowFocus(), engines: registry.active().map((agent) => agent.engine), commanders: backend.hasCommander() }),})+ // The Wi-Fi device in the devices' process (core/wifiLink.ts): its sessions' requests and what the agents do,+ // in order; on each connection, what the core holds for it (core/wifi.ts).+ const wifiLink = createWifiLink({+ core: coreApi,+ notify: (frame) => serviceLinks.notify('wifi', frame),+ call: (type, payload, waitMs) => serviceLinks.call('wifi', type, payload, waitMs),+ })+ // Its port from the start: its process connects as soon as the socket answers, before the rest of the+ // core is wired, and is resumed through this port then (core/wifi.ts `started`).+ if (outOfProcess.has('wifi')) ports.wifi = wifiLink.portconst serviceLinks = createServiceLinks({token: serviceToken,owned: Object.fromEntries([...outOfProcess].map((name) => [name, requestsOf[name] ?? []])),@@ -1169,19 +1200,22 @@ async function runForeground(session: AuthSession | null): Promise<void> {: service === 'models' ? modelsLink.answer(query, payload): service === 'teams' || service === 'collaboration' ? teamsLink.answer(query, payload): service === 'devices' ? devicesLink.answer(query, payload)+ : service === 'wifi' ? wifiLink.answer(query, payload): service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : answerAgentQuery(coreApi, query)),// The gateway's own traffic: its remote clients and what they sent, and its comings and goings; and what// the devices tell the core (a turn, a frame for the windows, a dial on the wire).- notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload); else if (service === 'devices') devicesLink.notice(payload) },+ notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload); else if (service === 'devices') devicesLink.notice(payload); else if (service === 'wifi') wifiLink.notice(payload) },binary: (service, bytes) => { if (service === 'gateway') gatewayLink?.binary(bytes) },connected: (service) => {if (service === 'gateway') gatewayLink?.connected()if (service === 'teams') teamsLink.on()if (service === 'devices') devicesLink.connected()+ if (service === 'wifi') wifiCore.started(appVoiceFocus ?? null)},disconnected: (service) => {if (service === 'gateway') gatewayLink?.disconnected()if (service === 'devices') devicesLink.disconnected()+ if (service === 'wifi') wifiCore.stopped()void terminalWatch.gone(service)},})@@ -1308,7 +1342,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {input,teams,deviceInput,- device: () => autonomousDeviceService,+ device: () => wifiCore.feed,startHeartbeat,questionWatcher,mirror,@@ -1676,8 +1710,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Until the pieces below are built; after, a piece that could not be is refused by the requests// that need it, and the rest (list, status, revoke) answer from the pairings.if (!devicePartsBuilt) return { status: 503, body: { error: { code: 'UNAVAILABLE', message: 'Autonomous device service is starting' } } }- // The Wi-Fi device's pairings and direct links are the gateway's (gateway/start.ts); its receipts the- // device service's, here.+ // The Wi-Fi device's pairings and direct links are the gateway's (gateway/start.ts); its receipts its+ // service's, with the dials (services/wifi.ts).const viaGateway = async (request: Parameters<GatewayOps['wifi']>[0]): Promise<Record<string, unknown>> => {const answer = await gatewayOps.wifi(request)if ('refused' in answer) throw Object.assign(new Error(answer.refused.message), { code: answer.refused.code })@@ -1688,10 +1722,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {pairStart: ({ code, device }) => viaGateway({ op: 'pair', code, device }),pairStatus: () => viaGateway({ op: 'pairStatus' }),list: () => viaGateway({ op: 'list' }),- status: async () => ({ transport: 'direct', connected: backend.directAutonomousDeviceSessions() > 0,- paired: ((await viaGateway({ op: 'list' })).devices as unknown[]).length, sessions: backend.directAutonomousDeviceSessions(), proto: 1 }),+ status: async () => ({ transport: 'direct', connected: wifiCore.directSessions() > 0,+ paired: ((await viaGateway({ op: 'list' })).devices as unknown[]).length, sessions: wifiCore.directSessions(), proto: 1 }),revoke: ({ id }) => viaGateway({ op: 'revoke', id }),- receipt: target => ({ receipt: runningDevicePart(autonomousDeviceService, 'Wi-Fi device service').receipt(target.deviceId, target.idempotencyKey) }),+ receipt: async (target) => {+ const answer = await (ports.wifi?.receipt(target.deviceId, target.idempotencyKey) ?? { unavailable: true as const })+ if ('unavailable' in answer) throw Object.assign(new Error('The Wi-Fi device service is not running on this computer. See the daemon\'s log.'), { code: 'UNAVAILABLE' })+ return { receipt: answer.receipt }+ },}, method, target, body)},resolveHookAgent: engineHooks.resolveHookAgent,@@ -1774,11 +1812,9 @@ 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 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) })+ // The dial, the window bridges and the Wi-Fi device are the devices' (services/devices.ts, services/wifi.ts),+ // behind their ports, guarded there: the local socket closes a connection whose frame handler throws, so a+ // device fault reaching here would disconnect the desktop, again on every pane change./** 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. */@@ -1797,23 +1833,21 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (appVoiceFocus?.connId === connId) appVoiceFocus = undefinedports.devices?.windowFocus(windowFocus())ports.devices?.windowGone(connId)- wifi('wifi', () => autonomousDeviceService?.appFocus(machineId, null, connId))+ void ports.wifi?.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) => wifi('wifi', () => deviceStoreRef?.acknowledgeReveal(operationId, agentId)),+ onDevicePrepareOpened: (operationId, agentId) => ports.wifi?.revealed(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- wifi('wifi', () => { focusRevision = autonomousDeviceService?.focusSnapshot().focusRevision })- if (expectedRevision && focusRevision !== expectedRevision) return false+ if (expectedRevision && wifiCore.focusRevision() !== expectedRevision) return falseappFormWindow = { machineId, connId }if (agentId === null) {if (appVoiceFocus?.connId === connId) appVoiceFocus = undefined} else appVoiceFocus = { machineId, agentId, connId }ports.devices?.windowFocus(windowFocus())- wifi('wifi', () => autonomousDeviceService?.appFocus(machineId, agentId, connId))+ void ports.wifi?.appFocus(machineId, agentId, connId)},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@@ -1895,7 +1929,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {has: (sessionId) => registry.has(sessionId),bySession: (sessionId) => registry.bySession(sessionId),tokenUsage: agentTokenUsage,- device: () => autonomousDeviceService,+ device: () => wifiCore.feed,runtimeProfiles,normalizers,announceTurnAborted,@@ -2186,7 +2220,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {normalizers,cursorSubagents,input,- device: () => autonomousDeviceService,+ device: () => wifiCore.feed,stopHeartbeat,questionWatcher,mirror,@@ -2526,52 +2560,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (ports.devices) devicesLink.started(ports.devices)}- const deviceStore = createDeviceStore({ dataDir: env.ADAPTER_DATA_DIR, machineId: backend.machineId,- create: input => backend.onCreateAgent!(input),- reveal: (operationId, agentId) => { backend.sendFirstLocal({ type: 'device_prepare_open', payload: { operationId, machineId: backend.machineId, agentId } }) },- })- deviceStoreRef = deviceStore- deviceStore.startUiDelivery()- autonomousDeviceService = startDevicePart('Wi-Fi device service', () => new AutonomousDeviceService({- store: deviceStore,- resultJournal: new DeviceResultJournal(join(env.ADAPTER_DATA_DIR, 'device-results.json')),- inputConsumed: (id, text) => deviceInput.onTurnStarted(id, text),- machineId: backend.machineId,- requestAppFocus: (agentId, expiresAt, focusRevision) => backend.sendFirstLocal({- type: 'device_focus', payload: { machineId: backend.machineId, agentId, expiresAt, focusRevision },- }),- // 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; 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,- packageId: evidence.get(s.agentId)?.packageId ?? null, workspace: evidence.get(s.agentId)?.workspace ?? s.cwd,- runtime: evidence.get(s.agentId)?.runtime ?? 'unavailable',- state: turnStartedAt.has(s.sessionId) ? 'running' : 'idle' }))- },- submit: (id, text, deliveryId) => {- const session = registry.resolve(id)- deviceInput.submit(session?.agentId ?? id, adaptSlashCommand(text, session?.engine ?? 'claude'), deliveryId)- },- cancelDelivery: id => deviceInput.cancelDelivery(id),- stop: id => cancelAgent(id, true),- answer: async (agentId, requestId, answers) => (await questions.answer({ agentId, requestId, answers, allowPermissions: false })).ok,- recent: (id, n) => mirror.recent(registry.byAgent(id)?.sessionId ?? id, n),- fullText: id => mirror.lastFullText(registry.byAgent(id)?.sessionId ?? id),- emit: (frame, deviceId) => backend.emitAutonomousDeviceEvent(frame, deviceId),- }))- if (appVoiceFocus) autonomousDeviceService?.appFocus(appVoiceFocus.machineId, appVoiceFocus.agentId, appVoiceFocus.connId)- // The device's requests reach the service through its relay in the socket; its sessions and its direct- // links are the gateway's, which starts the links only with the service up: a device it connected would- // be answered by nothing.- if (autonomousDeviceService) {- backend.setAutonomousDeviceService(autonomousDeviceService, (identity) => gatewayOps.revokeIdentity(identity))- gatewayOps.wifiService(true)+ // The Wi-Fi device (services/wifi.ts), with the dials: in their process by default (core/wifiLink.ts,+ // resumed there as its link connects), or here.+ if (!outOfProcess.has('wifi')) {+ serviceHost.start('wifi', inline!.startWifi, coreApi, WIFI_FALLBACKS)+ if (ports.wifi) wifiCore.started(appVoiceFocus ?? null)}devicePartsBuilt = true@@ -2588,7 +2581,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// 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>))+ wifiCore.card(frame as Record<string, unknown>)ports.devices?.card(frame as Record<string, unknown>)}diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.tsindex 324a7576a..faa61021d 100644--- a/cli/src/core/transcripts/attach.ts+++ b/cli/src/core/transcripts/attach.ts@@ -27,7 +27,7 @@ import type { AgentEngine } from '../../engines/types.js'import { pollsQuestions, type QuestionWatcher } from '../../lib/askQuestion.js'import { attachTranscript, claudeAttachRules, codexAttachRules, type AttachRead } from '../../lib/attachTranscript.js'import { AttachTracker } from '../../lib/attachTracker.js'-import type { AutonomousDeviceService } from '../../lib/autonomous-device/service.js'+import type { WifiFeed } from '../wifi.js'import { sid } from '../../lib/log.js'import { foldTranscript, lineToEvents, newTurnState, TranscriptFold, type LiveEvent } from '../../lib/normalize.js'import type { RegisteredSession } from '../../lib/registry.js'@@ -44,8 +44,8 @@ export interface AttachDeps {normalizers: SessionNormalizerswatcher: Pick<Watcher, 'addSession' | 'hold' | 'tails'>cursorDiscovery: Pick<CursorTranscriptDiscovery, 'add'>- /** The Harness device service, once it exists: some subscriptions read the raw transcript. */- device: () => Pick<AutonomousDeviceService, 'needsTranscript' | 'observeTranscript'> | undefined+ /** The Wi-Fi device's service, wherever it runs (core/wifi.ts): it proves its turns by the raw transcript. */+ device: () => Pick<WifiFeed, 'needsTranscript' | 'observeTranscript'> | undefinedruntimeProfiles: Pick<RuntimeProfileManager, 'transcriptFields' | 'beginHydrate' | 'hydrate' | 'ingestConfig' | 'ingestPane'>captureTerminal: (target: string, historyLines?: number) => Promise<string | null>emit: (sessionId: string, events: LiveEvent[], opts?: { resumed?: boolean }) => voiddiff --git a/cli/src/core/transcripts/ingest.ts b/cli/src/core/transcripts/ingest.tsindex d7c931b9d..5cf415f0e 100644--- a/cli/src/core/transcripts/ingest.ts+++ b/cli/src/core/transcripts/ingest.ts@@ -18,7 +18,7 @@ import { CursorNormalizer } from '../../engines/cursor/normalizer.js'import { GrokNormalizer } from '../../engines/grok/normalizer.js'import { MuseNormalizer } from '../../engines/muse/normalizer.js'import { PiNormalizer } from '../../engines/pi/normalizer.js'-import type { AutonomousDeviceService } from '../../lib/autonomous-device/service.js'+import type { WifiFeed } from '../wifi.js'import { sid } from '../../lib/log.js'import { lineToEvents, newTurnState, type LiveEvent } from '../../lib/normalize.js'import type { RegisteredSession } from '../../lib/registry.js'@@ -31,8 +31,8 @@ export interface IngestDeps {has: (sessionId: string) => booleanbySession: (sessionId: string) => RegisteredSession | undefinedtokenUsage: { changed(session: RegisteredSession): void }- /** The Harness device service, once it exists: some subscriptions read the raw transcript. */- device: () => Pick<AutonomousDeviceService, 'needsTranscript' | 'observeTranscript'> | undefined+ /** The Wi-Fi device's service, wherever it runs (core/wifi.ts): it proves its turns by the raw transcript. */+ device: () => Pick<WifiFeed, 'needsTranscript' | 'observeTranscript'> | undefinedruntimeProfiles: Pick<RuntimeProfileManager, 'ingest'>normalizers: SessionNormalizersannounceTurnAborted: (sessionId: string, engine: string, message: string, deviceMessage?: string) => voiddiff --git a/cli/src/core/turns/cancel.ts b/cli/src/core/turns/cancel.tsindex f147ef500..f56ea22db 100644--- a/cli/src/core/turns/cancel.ts+++ b/cli/src/core/turns/cancel.ts@@ -8,7 +8,7 @@import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'import { correlateAgentEvent } from '../../lib/agentEvent.js'import type { QuestionWatcher } from '../../lib/askQuestion.js'-import type { AutonomousDeviceService } from '../../lib/autonomous-device/service.js'+import type { WifiFeed } from '../wifi.js'import type { CommanderMirror } from '../../lib/commander.js'import type { RegisteredSession } from '../../lib/registry.js'import type { SessionInputController } from '../../lib/sessionInput.js'@@ -20,8 +20,8 @@ export interface CancelDeps {normalizers: Pick<SessionNormalizers, 'closeTurns'>cursorSubagents: Pick<CursorSubagentManager, 'forget'>input: Pick<SessionInputController, 'cancel' | 'cancelConfirmed'>- /** The Harness device service, once it exists. */- device: () => Pick<AutonomousDeviceService, 'turnEnded'> | undefined+ /** The Wi-Fi device's service, wherever it runs (core/wifi.ts). */+ device: () => Pick<WifiFeed, 'turnEnded'> | undefinedstopHeartbeat: (sessionId: string) => voidquestionWatcher: Pick<QuestionWatcher, 'stop'>mirror: Pick<CommanderMirror, 'cancel'>diff --git a/cli/src/core/turns/funnel.ts b/cli/src/core/turns/funnel.tsindex 0d2e5e280..aea593df6 100644--- a/cli/src/core/turns/funnel.ts+++ b/cli/src/core/turns/funnel.ts@@ -13,7 +13,7 @@import { correlateAgentEvent } from '../../lib/agentEvent.js'import type { AutonomousDeviceInput } from '../deviceInput.js'import { isDeviceInputBoundary } from '../deviceInput.js'-import type { AutonomousDeviceService } from '../../lib/autonomous-device/service.js'+import type { WifiFeed } from '../wifi.js'import type { CommanderMirror } from '../../lib/commander.js'import { deviceErrorText } from '../cardText.js'import { preview, sid } from '../../lib/log.js'@@ -48,7 +48,7 @@ export interface FunnelDeps {input: Pick<SessionInputController, 'onTurnStarted' | 'onTurnEnded'>teams: Pick<SwarmPromptScopes, 'started'>deviceInput: Pick<AutonomousDeviceInput, 'onTurnStarted' | 'onTurnEnded'>- device: () => Pick<AutonomousDeviceService, 'turnStarted' | 'turnEnded' | 'stream'> | undefined+ device: () => Pick<WifiFeed, 'turnStarted' | 'turnEnded' | 'stream'> | undefinedstartHeartbeat: (sessionId: string) => voidquestionWatcher: Pick<QuestionWatcher, 'start' | 'noteTurnStart' | 'stop'>mirror: Pick<CommanderMirror, 'ingest'>diff --git a/cli/src/core/wifi.spec.ts b/cli/src/core/wifi.spec.tsnew file mode 100644index 000000000..58cc332bf--- /dev/null+++ b/cli/src/core/wifi.spec.ts@@ -0,0 +1,227 @@+import { describe, expect, it, vi } from 'vitest'+import type { LiveEvent } from '../lib/normalize.js'+import { WIFI_OFF, type RemoteClient, type WifiPort } from './api.js'+import { createWifiCore } from './wifi.js'++const device = (identity: string, direct = false): RemoteClient => ({ role: 'device', label: 'Desk', identity, direct })++function harness() {+ const port = {+ session: vi.fn(), request: vi.fn(async () => {}), dropped: vi.fn(), revoked: vi.fn(), resume: vi.fn(async () => {}), card: vi.fn(),+ turnStarted: vi.fn(), turnEnded: vi.fn(), stream: vi.fn(), transcript: vi.fn(), delivery: vi.fn(), dispatched: vi.fn(),+ inputStatus: vi.fn(), agentGone: vi.fn(), appFocus: vi.fn(async () => {}), revealed: vi.fn(), receipt: vi.fn(), stop: vi.fn(),+ } satisfies WifiPort+ let on: WifiPort | null = port+ const clients = new Map<string, RemoteClient>()+ const gateway = { device: vi.fn(), deviceClient: vi.fn(), revokeIdentity: vi.fn() }+ const joined = vi.fn()+ const ready = vi.fn()+ const fullText = vi.fn((agentId: string) => (agentId === 'a' ? 'the whole answer' : undefined))+ const wifi = createWifiCore({ port: () => on, gateway, remoteClient: (connId) => clients.get(connId) ?? null, fullText, joined, ready, doors: WIFI_OFF })+ return { wifi, port, clients, gateway, joined, ready, fullText, off: () => { on = null } }+}++describe('the Wi-Fi device, as the core keeps it', () => {+ it('counts a device as watching only while its app said hello on a session still its own, with the service there', () => {+ const { wifi, clients, gateway } = harness()+ clients.set('c1', device('id-1', true))+ clients.set('c2', device('id-2'))+ wifi.api.hello('c1', 'id-1')+ wifi.api.hello('c2', 'id-2')+ expect(gateway.deviceClient).toHaveBeenCalledWith('c1', 'id-1')+ // No service yet: nobody is served, so nobody watches.+ expect(wifi.connected()).toBe(false)+ wifi.started(null)+ expect(wifi.connected()).toBe(true)+ expect(wifi.directSessions()).toBe(1)+ // A session that became another identity's, or a phone's, is not the device that said hello.+ clients.set('c2', { ...device('id-3') })+ clients.set('c1', { ...device('id-1', true), role: 'web' })+ expect(wifi.connected()).toBe(false)+ clients.set('c1', device('id-1', true))+ wifi.api.hello('c1', null)+ expect(gateway.deviceClient).toHaveBeenLastCalledWith('c1', null)+ expect(wifi.connected()).toBe(false)+ wifi.stopped()+ expect(wifi.directSessions()).toBe(0)+ })++ it('seals an answer to a session only while it is still the identity\'s device', () => {+ const { wifi, clients, gateway } = harness()+ clients.set('c1', device('id-1'))+ wifi.api.send('c1', 'id-1', 'autonomous_device_result', { ok: true })+ wifi.api.send('c1', 'id-2', 'autonomous_device_result', { stolen: true })+ wifi.api.send('gone', 'id-1', 'autonomous_device_result', {})+ expect(gateway.device).toHaveBeenCalledTimes(1)+ expect(gateway.device).toHaveBeenCalledWith('c1', 'autonomous_device_result', { ok: true })+ })++ it('passes on the doors, a hello\'s join, its readiness and an unpairing the device asked for', () => {+ const { wifi, gateway, joined, ready } = harness()+ expect(wifi.api.view).toBe(WIFI_OFF.view)+ wifi.api.joined()+ expect(joined).toHaveBeenCalled()+ wifi.api.ready()+ expect(ready).toHaveBeenCalled()+ wifi.api.unpaired('id-1')+ expect(gateway.revokeIdentity).toHaveBeenCalledWith('id-1')+ })++ it('sends an agent\'s transcript lines from its prompt\'s dispatch until the service is done with it as of its last prompt', () => {+ const { wifi, port } = harness()+ expect(wifi.feed.needsTranscript('a', 's', 'claude')).toBe(false)+ wifi.started(null)+ wifi.feed.inputDispatched('a', 'd1', 'hi', 's')+ expect(port.dispatched).toHaveBeenCalledWith('a', 'd1', 'hi', 's')+ // Before the service could ask for it: the prompt's first lines may come at once.+ expect(wifi.feed.needsTranscript('a', 's', 'claude')).toBe(true)+ expect(wifi.feed.needsTranscript('a', 's', 'codex')).toBe(true)+ // Only the engines whose transcripts prove a turn.+ expect(wifi.feed.needsTranscript('a', 's', 'cursor')).toBe(false)+ wifi.feed.observeTranscript('a', 's', 'claude', '{"line":1}')+ expect(port.transcript).toHaveBeenCalledWith('a', 's', 'claude', '{"line":1}')+ // A second prompt the service has not heard of yet: its "done as of the first" leaves it watched.+ wifi.feed.inputDispatched('a', 'd2', 'again', 's')+ wifi.api.transcripts('a', 1)+ expect(wifi.feed.needsTranscript('a', 's', 'claude')).toBe(true)+ wifi.api.transcripts('a', 2)+ expect(wifi.feed.needsTranscript('a', 's', 'claude')).toBe(false)+ // An agent it was never told of.+ wifi.api.transcripts('b', 0)+ expect(wifi.feed.needsTranscript('b', 's', 'claude')).toBe(false)+ })++ it('takes the service\'s own list as it starts, and forgets the counts the last one heard', () => {+ const { wifi } = harness()+ wifi.started(null)+ wifi.feed.inputDispatched('a', 'd1', 'hi')+ wifi.api.watching(['b'])+ expect(wifi.feed.needsTranscript('a', 's', 'claude')).toBe(false)+ expect(wifi.feed.needsTranscript('b', 's', 'claude')).toBe(true)+ wifi.api.transcripts('b', 0)+ expect(wifi.feed.needsTranscript('b', 's', 'claude')).toBe(false)+ })++ it('streams the answer\'s text always and a tool\'s events only for a subscribed agent, and nothing with the service away', () => {+ const { wifi, port } = harness()+ const events = [+ { type: 'turn_started', payload: {} }, { type: 'text_delta', payload: { content: 'hi' } },+ { type: 'tool_start', payload: { id: 't', tool: 'Read', input: {} } }, { type: 'tool_end', payload: { id: 't', tool: 'Read', isError: false } },+ { type: 'thinking_delta', payload: {} }, { type: 'turn_ended', payload: {} },+ ] as unknown as LiveEvent[]+ wifi.feed.stream('a', events)+ expect(port.stream).not.toHaveBeenCalled()+ wifi.started(null)+ wifi.feed.stream('a', events)+ expect(port.stream).toHaveBeenLastCalledWith('a', [events[0], events[1], events[5]])+ wifi.api.streams(['a'])+ wifi.feed.stream('a', events)+ expect(port.stream).toHaveBeenLastCalledWith('a', [events[0], events[1], events[2], events[3], events[5]])+ port.stream.mockClear()+ wifi.feed.stream('a', [events[4]])+ expect(port.stream).not.toHaveBeenCalled()+ })++ it('passes what the agents do and the panes say on to the service, and nothing when it is off', () => {+ const { wifi, port, off } = harness()+ wifi.feed.delivery({ deliveryId: 'd', sessionId: 'a', state: 'delivered' })+ wifi.feed.inputStatus({ deliveryId: 'd', sessionId: 'a', mode: 'queued', phase: 'waiting' } as never)+ wifi.feed.agentGone('a')+ wifi.feed.turnStarted('a')+ wifi.feed.turnEnded('a')+ wifi.feed.turnEnded('b', true)+ expect(port.delivery).toHaveBeenCalledWith({ deliveryId: 'd', sessionId: 'a', state: 'delivered' })+ expect(port.inputStatus).toHaveBeenCalled()+ expect(port.agentGone).toHaveBeenCalledWith('a')+ expect(port.turnStarted).toHaveBeenCalledWith('a')+ expect(port.turnEnded).toHaveBeenCalledWith('a', false)+ expect(port.turnEnded).toHaveBeenCalledWith('b', true)+ off()+ for (const call of [() => wifi.feed.delivery({ deliveryId: 'd', sessionId: 'a', state: 'delivered' }), () => wifi.feed.agentGone('a'),+ () => wifi.feed.observeTranscript('a', 's', 'claude', 'x'), () => wifi.feed.inputDispatched('a', 'd', 't'),+ () => wifi.feed.inputStatus({} as never), () => wifi.feed.turnStarted('a'), () => wifi.feed.turnEnded('a'),+ () => wifi.card({ type: 'commander_event' }), () => wifi.fromGateway.request('c', {}, null), () => wifi.fromGateway.revoked('i'),+ () => wifi.fromGateway.dropped('c'), () => wifi.fromGateway.session('c', device('i')), () => wifi.started(null)]) expect(call()).toBeUndefined()+ wifi.api.streams(['a'])+ expect(wifi.feed.stream('a', [{ type: 'text_delta', payload: { content: 'x' } } as unknown as LiveEvent])).toBeUndefined()+ })++ it('hands a summary card its turn\'s whole answer, and any other card as it is', () => {+ const { wifi, port, fullText } = harness()+ const summary = { type: 'commander_event', agentId: 'a', payload: { kind: 'summary', text: 'short' } }+ wifi.card(summary)+ expect(port.card).toHaveBeenLastCalledWith(summary, 'the whole answer')+ const tool = { type: 'commander_event', agentId: 'a', payload: { kind: 'tool' } }+ wifi.card(tool)+ expect(port.card).toHaveBeenLastCalledWith(tool, undefined)+ wifi.card({ type: 'commander_question', agentId: 'a' })+ wifi.card({ type: 'commander_event', payload: { kind: 'summary' } })+ expect(fullText).toHaveBeenCalledTimes(1)+ })++ it('passes the gateway\'s device sessions on, and forgets a phone\'s', () => {+ const { wifi, port, gateway } = harness()+ wifi.fromGateway.session('phone', { role: 'web', label: null, identity: 'p', direct: false })+ wifi.fromGateway.session('phone', null)+ expect(port.session).not.toHaveBeenCalled()+ wifi.fromGateway.session('c1', device('id-1'))+ expect(port.session).toHaveBeenCalledWith('c1', device('id-1'))+ // A device session that became something else is gone, as far as the service knows.+ wifi.fromGateway.session('c1', { role: 'web', label: null, identity: 'p', direct: false })+ expect(port.session).toHaveBeenLastCalledWith('c1', null)+ wifi.fromGateway.session('c1', device('id-1'))+ wifi.fromGateway.session('c1', null)+ expect(port.session).toHaveBeenLastCalledWith('c1', null)+ wifi.fromGateway.request('c1', { type: 'autonomous_device_request' }, { payload: {} })+ expect(port.request).toHaveBeenCalledWith('c1', { type: 'autonomous_device_request' }, { payload: {} })+ // A connection that closed: forgotten here and told to the gateway, said or not by the service.+ wifi.api.hello('c1', 'id-1')+ gateway.deviceClient.mockClear()+ wifi.fromGateway.dropped('c1')+ expect(gateway.deviceClient).toHaveBeenCalledWith('c1', null)+ expect(port.dropped).toHaveBeenCalledWith('c1')+ gateway.deviceClient.mockClear()+ wifi.fromGateway.dropped('c1')+ expect(gateway.deviceClient).not.toHaveBeenCalled()+ })++ it('forgets an unpaired identity\'s sessions and tells the service', () => {+ const { wifi, port, clients } = harness()+ clients.set('c1', device('id-1'))+ clients.set('c2', device('id-2'))+ wifi.api.hello('c1', 'id-1')+ wifi.api.hello('c2', 'id-2')+ wifi.started(null)+ wifi.fromGateway.revoked('id-1')+ expect(port.revoked).toHaveBeenCalledWith('id-1')+ expect(wifi.connected()).toBe(true)+ wifi.fromGateway.revoked('id-2')+ expect(wifi.connected()).toBe(false)+ })++ it('hands a starting service what it holds: the sessions, those still the device that said hello, and the window\'s focus', () => {+ const { wifi, port, clients, gateway } = harness()+ clients.set('c1', device('id-1'))+ clients.set('c2', device('id-2'))+ wifi.fromGateway.session('c1', device('id-1'))+ wifi.fromGateway.session('c2', device('id-2'))+ wifi.api.hello('c1', 'id-1')+ wifi.api.hello('c2', 'id-2')+ // c2's session went to another identity while the service was away: not handed back as id-2's.+ clients.set('c2', device('id-9'))+ wifi.api.focus('old')+ wifi.started({ machineId: 'm', agentId: 'a', connId: 'w' })+ expect(gateway.deviceClient).toHaveBeenCalledWith('c2', null)+ expect(port.resume).toHaveBeenCalledWith({+ sessions: [{ connId: 'c1', client: device('id-1') }, { connId: 'c2', client: device('id-2') }],+ helloed: [{ connId: 'c1', identity: 'id-1' }],+ focus: { machineId: 'm', agentId: 'a', connId: 'w' },+ })+ // The revision is the new service's to say.+ expect(wifi.focusRevision()).toBeUndefined()+ wifi.api.focus('r1')+ expect(wifi.focusRevision()).toBe('r1')+ wifi.stopped()+ expect(wifi.focusRevision()).toBeUndefined()+ })+})diff --git a/cli/src/core/wifi.ts b/cli/src/core/wifi.tsnew file mode 100644index 000000000..a2d0b6a41--- /dev/null+++ b/cli/src/core/wifi.ts@@ -0,0 +1,211 @@+/**+ * The Wi-Fi device, as the core keeps it. The device's service runs with the dials, in the devices'+ * process (services/wifi.ts, step 9, D3); what stays here is what the core reads in line, kept from what+ * the service tells it, and the checks on what the service sends a device:+ *+ * - **Presence.** Which device sessions said their app's hello, by connection: a device watching means the+ * core makes the turn cards and recaps for it, as it reads in line on every card. The core keeps them, so+ * a service that starts again is handed the devices it was serving and serves them on (`WifiResume`).+ * - **The transcripts it proves its turns by.** Every transcript line of every agent is too much to send+ * to another process; the service reads only those of an agent it sent a prompt to, until that prompt's+ * turn is proven. The core starts sending an agent's lines as it dispatches the prompt, before the service+ * could ask, and stops when the service says it is done with the agent as of the last prompt it was told+ * of: never in the gap between a prompt and the service hearing of it.+ * - **The live text it streams.** The answer's text goes always (a device subscribing mid-turn is sent the+ * whole final, as before), a tool's events only for an agent a device subscribed to; the service says+ * which before the subscription's answer leaves it, so no event in between is lost.+ * - **The focus revision** a window's delayed selection is checked against, as the service last said it;+ * none while it is off, so a selection is refused then, as it was with no service.+ * - **Each answer goes to the session it came from:** the core seals it to a session only while that+ * session is still the same identity's device.+ */+import type { LiveEvent } from '../lib/normalize.js'+import type { DeviceInputStatus } from './deviceInput.js'+import type { CoreApi, RemoteClient, WifiPort, WifiResume } from './api.js'+import type { AutonomousDeviceDelivery } from '../lib/autonomous-device/service.js'++/** What the core's own modules tell the Wi-Fi device: its deliveries into the panes (core/input.ts), the+ * transcript lines (core/transcripts/), the turns and their live events (core/turns/). */+export interface WifiFeed {+ needsTranscript(agentId: string, sessionId: string, engine: string): boolean+ observeTranscript(agentId: string, sessionId: string, engine: string, line: string): void+ delivery(event: AutonomousDeviceDelivery): void+ inputDispatched(agentId: string, deliveryId: string, text: string, sessionId?: string): void+ inputStatus(event: DeviceInputStatus): void+ agentGone(agentId: string): void+ turnStarted(agentId: string): void+ turnEnded(agentId: string, aborted?: boolean): void+ stream(agentId: string, events: readonly LiveEvent[]): void+}++/** The gateway's calls a device's relay makes. */+export interface WifiGateway {+ /** An answer or event, sealed to one session. */+ device(connId: string, type: string, payload: Record<string, unknown>): void+ /** Which identity's app said hello on a session, so the gateway can tell it it was unpaired. */+ deviceClient(connId: string, identity: string | null): void+ /** A pairing the device gave up over its own session. */+ revokeIdentity(identity: string): void+}++export interface WifiCoreDeps {+ /** The service's port; null while it is off. */+ port(): WifiPort | null+ gateway: WifiGateway+ /** A remote client the gateway holds a session with, as the socket last heard. */+ remoteClient(connId: string): RemoteClient | null+ /** A turn's whole answer, for its summary card: the device shows more than the card carries. */+ fullText(agentId: string): string | undefined+ /** A device said hello: the live cards and the open questions again (BackendSocket.onCommanderJoin). */+ joined(): void+ /** The service is built and serving: the gateway's direct links may connect devices to it. */+ ready(): void+ /** The doors that are one call each into the core's own modules. */+ doors: Pick<CoreApi['wifi'], 'view' | 'submit' | 'cancel' | 'started' | 'stop' | 'answer' | 'create' | 'stepFocus' | 'scroll' | 'focusApp' | 'reveal'>+}++/** The engines whose transcripts prove a device's turn (lib/autonomous-device/resultEvidence.ts). */+const PROVEN_BY_TRANSCRIPT = new Set(['claude', 'codex'])+/** The live events a device's stream is made of (lib/autonomous-device/stream.ts): the answer's text,+ * always, and a tool's start and end, for an agent a device subscribed to. */+const ALWAYS_STREAMED = new Set(['turn_started', 'text_delta', 'turn_ended'])+const TOOL_EVENTS = new Set(['tool_start', 'tool_end'])++export function createWifiCore(deps: WifiCoreDeps) {+ const { port, gateway, remoteClient } = deps+ /** The device sessions the gateway holds, as the socket heard them. */+ const sessions = new Map<string, RemoteClient>()+ /** Which identity's app said hello on each session. */+ const helloed = new Map<string, string>()+ /** The agents whose transcript lines the service reads, and how many prompts the core told it of. */+ const watched = new Set<string>()+ const dispatched = new Map<string, number>()+ /** The agents a device subscribed to. */+ let streamed = new Set<string>()+ let revision: string | undefined+ let up = false++ /** A session that is still the identity's device it said hello as. */+ const serving = (connId: string, identity: string): boolean => {+ const client = remoteClient(connId)+ return client?.role === 'device' && client.identity === identity+ }+ const servingCount = (only: (client: RemoteClient) => boolean = () => true): number => {+ if (!up) return 0+ let count = 0+ for (const [connId, identity] of helloed) {+ const client = remoteClient(connId)+ if (client && serving(connId, identity) && only(client)) count+++ }+ return count+ }+ const forget = (connId: string): void => {+ if (!helloed.delete(connId)) return+ gateway.deviceClient(connId, null)+ }++ const api: CoreApi['wifi'] = {+ ...deps.doors,+ send: (connId, identity, type, payload) => { if (serving(connId, identity)) gateway.device(connId, type, payload) },+ hello: (connId, identity) => {+ if (identity) helloed.set(connId, identity)+ else helloed.delete(connId)+ gateway.deviceClient(connId, identity)+ },+ joined: () => deps.joined(),+ ready: () => deps.ready(),+ unpaired: (identity) => gateway.revokeIdentity(identity),+ focus: (next) => { revision = next },+ transcripts: (agentId, seen) => { if ((dispatched.get(agentId) ?? 0) <= seen) watched.delete(agentId) },+ watching: (agentIds) => {+ watched.clear()+ dispatched.clear()+ for (const agentId of agentIds) watched.add(agentId)+ },+ streams: (agentIds) => { streamed = new Set(agentIds) },+ }++ const feed: WifiFeed = {+ needsTranscript: (agentId, _sessionId, engine) => up && watched.has(agentId) && PROVEN_BY_TRANSCRIPT.has(engine),+ observeTranscript: (agentId, sessionId, engine, line) => port()?.transcript(agentId, sessionId, engine, line),+ delivery: (event) => port()?.delivery(event),+ inputDispatched: (agentId, deliveryId, text, sessionId) => {+ // Before the service hears of it: the prompt's first lines may be written before it could ask.+ watched.add(agentId)+ dispatched.set(agentId, (dispatched.get(agentId) ?? 0) + 1)+ port()?.dispatched(agentId, deliveryId, text, sessionId)+ },+ inputStatus: (event) => port()?.inputStatus(event),+ agentGone: (agentId) => port()?.agentGone(agentId),+ turnStarted: (agentId) => port()?.turnStarted(agentId),+ turnEnded: (agentId, aborted = false) => port()?.turnEnded(agentId, aborted),+ stream: (agentId, events) => {+ if (!up) return+ const tools = streamed.has(agentId)+ const sent = events.filter((event) => ALWAYS_STREAMED.has(event.type) || (tools && TOOL_EVENTS.has(event.type)))+ if (sent.length) port()?.stream(agentId, sent)+ },+ }++ return {+ api,+ feed,+ /** What the gateway says of the device sessions (GatewayEvents), on to the service. */+ fromGateway: {+ session: (connId: string, client: RemoteClient | null): void => {+ if (client?.role === 'device') sessions.set(connId, client)+ else if (!sessions.delete(connId)) return+ port()?.session(connId, client?.role === 'device' ? client : null)+ },+ request: (connId: string, frame: Record<string, unknown>, opened: Record<string, unknown> | null): void => {+ port()?.request(connId, frame, opened)+ },+ dropped: (connId: string): void => {+ sessions.delete(connId)+ // The service forgets it too, and says so; said here as well, for a service that is not there.+ forget(connId)+ port()?.dropped(connId)+ },+ revoked: (identity: string): void => {+ for (const [connId, said] of [...helloed]) if (said === identity) helloed.delete(connId)+ port()?.revoked(identity)+ },+ },+ /** A frame bound for the devices, as it is sent; a summary with the turn's whole answer. */+ card: (frame: Record<string, unknown>): void => {+ const service = port()+ if (!service) return+ const payload = frame.payload as Record<string, unknown> | undefined+ const summary = frame.type === 'commander_event' && payload?.kind === 'summary' && typeof frame.agentId === 'string'+ service.card(frame, summary ? deps.fullText(frame.agentId as string) : undefined)+ },+ /** Whether a device's app said hello on a session that is still its own: the core then makes the+ * cards and recaps it shows. */+ connected: (): boolean => servingCount() > 0,+ /** How many of those are on a direct link, for `harness device status`. */+ directSessions: (): number => servingCount((client) => client.direct),+ /** The focus revision, as the service last said; none while it is off. */+ focusRevision: (): string | undefined => (up ? revision : undefined),+ /** The service is there (it started here, or its process connected): it is handed what the core holds. */+ started: (focus: WifiResume['focus']): void => {+ up = true+ watched.clear()+ dispatched.clear()+ streamed = new Set()+ revision = undefined+ for (const [connId, identity] of [...helloed]) if (!serving(connId, identity)) forget(connId)+ port()?.resume({+ sessions: [...sessions].map(([connId, client]) => ({ connId, client })),+ helloed: [...helloed].map(([connId, identity]) => ({ connId, identity })),+ focus,+ })+ },+ /** The service went away: nothing it watched is sent, and no device is served until it is back. */+ stopped: (): void => {+ up = false+ revision = undefined+ },+ }+}++export type WifiCore = ReturnType<typeof createWifiCore>diff --git a/cli/src/core/wifiAgents.spec.ts b/cli/src/core/wifiAgents.spec.tsnew file mode 100644index 000000000..62a4a311e--- /dev/null+++ b/cli/src/core/wifiAgents.spec.ts@@ -0,0 +1,156 @@+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../lib/registry.js'++const installed = vi.hoisted(() => new Map<string, { id: string }>())+vi.mock('../dsh/installed.js', () => ({ installedDsh: (id: string) => installed.get(id) }))+const { storeAgents, wifiCreate, wifiDoors, wifiView } = await import('./wifiAgents.js')++let root: string+beforeEach(() => { root = realpathSync(mkdtempSync(join(tmpdir(), 'wifi-agents-'))); installed.clear() })+afterEach(() => { rmSync(root, { recursive: true, force: true }) })++const agent = (over: Partial<RegisteredSession>): RegisteredSession =>+ ({ agentId: 'a', sessionId: 's-a', engine: 'claude', cwd: '/nowhere', active: true, dsh: null, ...over }) as RegisteredSession++function registryOf(agents: RegisteredSession[], terminal = (_agentId: string) => true) {+ return {+ list: () => agents,+ advertised: () => agents.filter((a) => a.active),+ terminalAvailable: terminal,+ resolve: (id: string) => agents.find((a) => a.agentId === id || a.sessionId === id),+ }+}++describe('the agents as the Wi-Fi device lists them', () => {+ it('gives the Store its evidence on each agent: the harness it runs, its folder as it really is, and whether its engine is up', () => {+ installed.set('autonomous/robot', { id: 'autonomous/robot' })+ const work = join(root, 'work'); mkdirSync(work)+ const link = join(root, 'link'); symlinkSync(work, link)+ const agents = [+ agent({ agentId: 'ready', cwd: link, dsh: 'autonomous/robot', launch: { state: 'ready' } }),+ agent({ agentId: 'unknown-dsh', dsh: 'someone/else', sessionId: 's' }),+ agent({ agentId: 'starting', launch: { state: 'starting' } }),+ agent({ agentId: 'failed', launch: { state: 'failed', error: 'ENGINE_FAILED' } }),+ agent({ agentId: 'failed-detail', launch: { state: 'failed', error: 'ENGINE_FAILED', detail: 'npm said no' } }),+ agent({ agentId: 'no-terminal' }),+ agent({ agentId: 'stopped', active: false }),+ agent({ agentId: 'terminal', engine: 'terminal', sessionId: '' }),+ agent({ agentId: 'unbound', sessionId: '', cwd: null as unknown as string }),+ ]+ const rows = storeAgents({ registry: registryOf(agents, (id) => id !== 'no-terminal'), machineId: () => 'mac' })+ const by = (id: string) => rows.find((row) => row.agentId === id)!+ expect(by('ready')).toEqual({ agentId: 'ready', machineId: 'mac', packageId: 'autonomous/robot', engine: 'claude', workspace: work, state: 'active', runtime: 'ready' })+ expect(by('unknown-dsh')).toMatchObject({ packageId: 'someone/else', workspace: '/nowhere', runtime: 'ready' })+ expect(by('starting').runtime).toBe('starting')+ expect(by('failed')).toMatchObject({ runtime: 'unavailable', error: 'ENGINE_FAILED' })+ expect(by('failed-detail')).toMatchObject({ runtime: 'unavailable', error: 'npm said no' })+ expect(by('no-terminal').runtime).toBe('unavailable')+ expect(by('stopped')).toMatchObject({ state: 'inactive', runtime: 'unavailable' })+ expect(by('terminal').runtime).toBe('ready')+ expect(by('unbound')).toMatchObject({ workspace: null, runtime: 'starting' })+ })++ it('lists the agents the apps are shown, with their names, the Store\'s evidence, and whether each is running', () => {+ const agents = [agent({ agentId: 'a', sessionId: 's-a', launch: { state: 'ready' } }), agent({ agentId: 'b', sessionId: 's-b', cwd: '/b' })]+ const view = wifiView({ registry: registryOf(agents, (id) => id === 'a'), machineId: () => 'mac', displayName: (s) => `name ${s.agentId}`,+ running: (sessionId) => sessionId === 's-a', hasWindow: () => true })+ expect(view.hasWindow).toBe(true)+ expect(view.store).toHaveLength(2)+ expect(view.agents).toEqual([+ { agentId: 'a', name: 'name a', engine: 'claude', packageId: null, workspace: '/nowhere', runtime: 'ready', state: 'running' },+ { agentId: 'b', name: 'name b', engine: 'claude', packageId: null, workspace: '/b', runtime: 'unavailable', state: 'idle' },+ ])+ // An agent the apps are shown but the registry's list does not have (a moment apart): no evidence.+ const odd = { ...registryOf(agents), list: () => [] }+ expect(wifiView({ registry: odd, machineId: () => 'mac', displayName: () => '', running: () => false, hasWindow: () => false }).agents[0])+ .toMatchObject({ packageId: null, workspace: '/nowhere', runtime: 'unavailable' })+ })++ it('makes an agent for a Store harness with the device\'s fixed launch arguments, never over another agent\'s folder', async () => {+ const agents = [agent({ agentId: 'busy', cwd: '/busy' })]+ const created = vi.fn(async () => ({ ok: true as const, session: agent({ agentId: 'made' }) }))+ const create = wifiCreate({ registry: registryOf(agents), machineId: () => 'mac', createAgent: () => created })+ expect(await create('autonomous/robot', 'claude', '/busy')).toEqual({ ok: false, error: 'WORKSPACE_IN_USE' })+ expect(created).not.toHaveBeenCalled()+ expect(await create('autonomous/robot', 'codex', '/free')).toEqual({ ok: true, agentId: 'made' })+ expect(created).toHaveBeenCalledWith({ engine: 'codex', cwd: '/free', dsh: 'autonomous/robot', bypassPermission: false,+ permissionMode: null, grid: null, codexHome: null, prompt: null, name: null, agent: null })+ created.mockResolvedValueOnce({ ok: false, error: 'SPAWN_FAILED', detail: 'tmux said no' } as never)+ expect(await create('autonomous/robot', 'claude', '/free')).toEqual({ ok: false, error: 'SPAWN_FAILED', detail: 'tmux said no' })+ created.mockResolvedValueOnce({ ok: false, error: 'INVALID_DSH' } as never)+ expect(await create('autonomous/robot', 'claude', '/free')).toEqual({ ok: false, error: 'INVALID_DSH' })+ // Before the socket exists, nothing can be made.+ expect(await wifiCreate({ registry: registryOf([]), machineId: () => 'mac', createAgent: () => null })('p', 'claude', '/free'))+ .toEqual({ ok: false, error: 'UNSUPPORTED' })+ })+})++describe('the Wi-Fi device\'s doors into the core', () => {+ function doorsWith(over: { window?: boolean; socket?: boolean; devices?: boolean } = {}) {+ const agents = [agent({ agentId: 'a', sessionId: 's-a', engine: 'codex' })]+ const socket = { hasLocalClient: vi.fn(() => over.window !== false), sendFirstLocal: vi.fn(() => true), onCreateAgent: null }+ const deviceInput = { submit: vi.fn(), cancelDelivery: vi.fn(() => true), onTurnStarted: vi.fn() }+ const devices = { stepFocus: vi.fn(async () => ({ machineId: 'mac', agentId: 'a' })), scroll: vi.fn() }+ const answer = vi.fn(async () => ({ ok: true }))+ const stop = vi.fn(async () => true)+ const doors = wifiDoors({+ registry: registryOf(agents), machineId: () => 'mac', displayName: () => 'A', running: () => false,+ socket: () => (over.socket === false ? null : socket), deviceInput: () => deviceInput, answer, stop,+ devices: () => (over.devices === false ? null : devices),+ })+ return { doors, socket, deviceInput, devices, answer, stop }+ }++ it('lists the agents and says whether a window is there', async () => {+ const { doors } = doorsWith()+ expect(await doors.view()).toMatchObject({ agents: [{ agentId: 'a', name: 'A', state: 'idle' }], hasWindow: true })+ expect((await doorsWith({ socket: false }).doors.view()).hasWindow).toBe(false)+ })++ it('types a device\'s prompt through the pane\'s lock, adapted to the agent\'s engine, and lets go of it as its turn starts', () => {+ const { doors, deviceInput } = doorsWith()+ doors.submit('s-a', '/goal ship it', 'd1')+ expect(deviceInput.submit).toHaveBeenCalledWith('a', expect.any(String), 'd1')+ doors.submit('gone', 'hello', 'd2')+ expect(deviceInput.submit).toHaveBeenLastCalledWith('gone', 'hello', 'd2')+ doors.cancel('d1')+ expect(deviceInput.cancelDelivery).toHaveBeenCalledWith('d1')+ doors.started('a', 'hello')+ expect(deviceInput.onTurnStarted).toHaveBeenCalledWith('a', 'hello')+ })++ it('stops a turn and answers a question, never a permission dialog', async () => {+ const { doors, answer, stop } = doorsWith()+ expect(await doors.stop('a')).toBe(true)+ expect(stop).toHaveBeenCalledWith('a')+ expect(await doors.answer('a', 'r', { q: 'yes' })).toBe(true)+ expect(answer).toHaveBeenCalledWith({ agentId: 'a', requestId: 'r', answers: { q: 'yes' }, allowPermissions: false })+ expect(await doors.create('p', 'claude', '/x')).toEqual({ ok: false, error: 'UNSUPPORTED' })+ })++ it('walks the desk and scrolls through the dials\' own, with a window to show it', async () => {+ const { doors, devices } = doorsWith()+ expect(await doors.stepFocus('next', 'a')).toEqual({ machineId: 'mac', agentId: 'a' })+ expect(devices.stepFocus).toHaveBeenCalledWith('next', 'a')+ expect(doors.scroll('move', 4, 10)).toBe(true)+ expect(devices.scroll).toHaveBeenCalledWith('move', 4, 10)+ expect(await doorsWith({ window: false }).doors.stepFocus('next')).toBe('no_app')+ expect(doorsWith({ window: false }).doors.scroll('down', 0, 0)).toBe(false)+ expect(await doorsWith({ devices: false }).doors.stepFocus('previous')).toBe('no_agents')+ expect(doorsWith({ devices: false }).doors.scroll('up', 0, 0)).toBe(true)+ })++ it('asks the first window to show an agent, or a Store preparation\'s, with this machine named', () => {+ const { doors, socket } = doorsWith()+ expect(doors.focusApp('a', 123, 'rev')).toBe(true)+ expect(socket.sendFirstLocal).toHaveBeenCalledWith({ type: 'device_focus', payload: { machineId: 'mac', agentId: 'a', expiresAt: 123, focusRevision: 'rev' } })+ doors.reveal('op', 'a')+ expect(socket.sendFirstLocal).toHaveBeenLastCalledWith({ type: 'device_prepare_open', payload: { operationId: 'op', machineId: 'mac', agentId: 'a' } })+ const none = doorsWith({ socket: false }).doors+ expect(none.focusApp('a', 1, 'r')).toBe(false)+ expect(none.reveal('op', 'a')).toBeUndefined()+ })+})diff --git a/cli/src/core/wifiAgents.ts b/cli/src/core/wifiAgents.tsnew file mode 100644index 000000000..1c77e570c--- /dev/null+++ b/cli/src/core/wifiAgents.ts@@ -0,0 +1,120 @@+/**+ * The Wi-Fi device's doors into the core (`CoreApi.wifi`), where the registry, the panes and the windows+ * are: its service runs with the dials, in the devices' process (services/wifi.ts). The agents as it+ * lists them, asked before each request it answers; an agent made for a Store harness; its prompts into+ * the panes; the window it moves. Moved as they were from the core's wiring and+ * lib/autonomous-device/storeRuntime.ts.+ */+import { realpathSync } from 'node:fs'+import { installedDsh } from '../dsh/installed.js'+import type { AutonomousDeviceAgent } from '../lib/autonomous-device/service.js'+import type { StoreAgent } from '../lib/autonomous-device/store.js'+import type { RegisteredSession, registry } from '../lib/registry.js'+import type { BackendSocket } from '../backendSocket.js'+import { adaptSlashCommand } from '../lib/goalCommand.js'+import type { CoreApi, DevicesPort, WifiView } from './api.js'+import type { AutonomousDeviceInput } from './deviceInput.js'+import type { WifiCoreDeps } from './wifi.js'++const canonicalPath = (path: string | null): string | null => {+ if (!path) return null+ try { return realpathSync(path) } catch { return path }+}++export interface WifiAgentsDeps {+ registry: Pick<typeof registry, 'list' | 'advertised' | 'terminalAvailable'>+ /** The account's id for this machine. */+ machineId(): string+ displayName(session: RegisteredSession): string+ /** Whether an engine session has a turn open: its agent is running. */+ running(sessionId: string): boolean+ hasWindow(): boolean+}++/** Every agent with the Store's evidence on it: which harness it runs, where, and whether its engine is up+ * yet. A device's Store preparation reads it to find an agent already working in a folder. */+export function storeAgents(deps: Pick<WifiAgentsDeps, 'registry' | 'machineId'>): StoreAgent[] {+ const machineId = deps.machineId()+ return deps.registry.list().map(s => ({ agentId: s.agentId, machineId, packageId: s.dsh ? installedDsh(s.dsh)?.id ?? s.dsh : null,+ engine: s.engine, workspace: canonicalPath(s.cwd), state: s.active ? 'active' : 'inactive',+ runtime: !deps.registry.terminalAvailable(s.agentId) || s.launch?.state === 'failed' ? 'unavailable'+ : s.launch?.state === 'starting' ? 'starting' : s.active ? (s.launch?.state === 'ready' || s.sessionId || s.engine === 'terminal' ? 'ready' : 'starting') : 'unavailable',+ ...(s.launch?.state === 'failed' ? { error: s.launch.detail ?? s.launch.error } : {}) }))+}++export function wifiView(deps: WifiAgentsDeps): WifiView {+ const store = storeAgents(deps)+ const evidence = new Map(store.map(a => [a.agentId, a]))+ const agents: AutonomousDeviceAgent[] = deps.registry.advertised().map(s => ({ agentId: s.agentId, name: deps.displayName(s), engine: s.engine,+ packageId: evidence.get(s.agentId)?.packageId ?? null, workspace: evidence.get(s.agentId)?.workspace ?? s.cwd,+ runtime: evidence.get(s.agentId)?.runtime ?? 'unavailable',+ state: deps.running(s.sessionId) ? 'running' : 'idle' }))+ return { agents, store, hasWindow: deps.hasWindow() }+}++/** What a device's Store preparation launches with: the harness's own engine in the folder it prepared,+ * never a bypass, a grid, another engine home, a first prompt, a name or a named agent. Fixed here, in the+ * core, so no process but the core's decides how an agent starts. */+export type WifiCreateInput = Parameters<NonNullable<BackendSocket['onCreateAgent']>>[0]+export function wifiCreate(deps: Pick<WifiAgentsDeps, 'registry' | 'machineId'> & {+ createAgent(): BackendSocket['onCreateAgent']+}): CoreApi['wifi']['create'] {+ return async (packageId, engine, cwd) => {+ // Checked again here, immediately before the agent is made: another agent working there is never retargeted.+ if (storeAgents(deps).some(a => a.workspace === cwd)) return { ok: false, error: 'WORKSPACE_IN_USE' }+ const create = deps.createAgent()+ if (!create) return { ok: false, error: 'UNSUPPORTED' }+ const input: WifiCreateInput = { engine: engine as WifiCreateInput['engine'], cwd, dsh: packageId,+ bypassPermission: false, permissionMode: null, grid: null, codexHome: null, prompt: null, name: null, agent: null }+ const result = await create(input)+ return result.ok ? { ok: true, agentId: result.session.agentId } : { ok: false, error: result.error, ...(result.detail ? { detail: result.detail } : {}) }+ }+}++export interface WifiDoorsDeps extends Pick<WifiAgentsDeps, 'registry' | 'machineId' | 'displayName' | 'running'> {+ registry: WifiAgentsDeps['registry'] & Pick<typeof registry, 'resolve'>+ /** The socket, once it exists: the windows on this computer, and how an agent is created. */+ socket(): Pick<BackendSocket, 'hasLocalClient' | 'sendFirstLocal' | 'onCreateAgent'> | null+ /** The pane writer lock a device's prompts go through (core/deviceInput.ts). */+ deviceInput(): Pick<AutonomousDeviceInput, 'submit' | 'cancelDelivery' | 'onTurnStarted'>+ /** A device's answer to a question: never a permission dialog's. */+ answer(request: { agentId: string; requestId: string; answers: Record<string, string>; allowPermissions: false }): Promise<{ ok: boolean }>+ /** Stop a live agent's turn, as the stop button does. */+ stop(agentId: string): Promise<boolean>+ /** The dials' walk along the desk and their stroke, which the device borrows. */+ devices(): Pick<DevicesPort, 'stepFocus' | 'scroll'> | null+}++/** The doors the Wi-Fi device's service reaches the core through (`CoreApi.wifi`), each the one call it+ * made when it ran in the core's process. */+export function wifiDoors(deps: WifiDoorsDeps): WifiCoreDeps['doors'] {+ const { registry, machineId, socket } = deps+ const hasWindow = (): boolean => !!socket()?.hasLocalClient()+ return {+ view: async () => wifiView({ ...deps, hasWindow }),+ submit: async (id, text, deliveryId) => {+ const session = registry.resolve(id)+ deps.deviceInput().submit(session?.agentId ?? id, adaptSlashCommand(text, session?.engine ?? 'claude'), deliveryId)+ },+ cancel: (deliveryId) => { deps.deviceInput().cancelDelivery(deliveryId) },+ started: (agentId, text) => deps.deviceInput().onTurnStarted(agentId, text),+ stop: (agentId) => deps.stop(agentId),+ answer: async (agentId, requestId, answers) => (await deps.answer({ agentId, requestId, answers, allowPermissions: false })).ok,+ create: wifiCreate({ registry, machineId, createAgent: () => socket()?.onCreateAgent ?? null }),+ // The dial's walk and stroke: `dial_focus` and `dial_scroll` to the window. Without a window the forward+ // is a no-op, so it says so up front; without the devices there is no desk to walk.+ stepFocus: async (direction, currentAgentId) => {+ if (!hasWindow()) return 'no_app'+ const devices = deps.devices()+ return devices ? devices.stepFocus(direction, currentAgentId) : 'no_agents'+ },+ scroll: (phase, dy, velocity) => {+ if (!hasWindow()) return false+ deps.devices()?.scroll(phase, dy, velocity)+ return true+ },+ focusApp: (agentId, expiresAt, focusRevision) =>+ !!socket()?.sendFirstLocal({ type: 'device_focus', payload: { machineId: machineId(), agentId, expiresAt, focusRevision } }),+ reveal: (operationId, agentId) => { socket()?.sendFirstLocal({ type: 'device_prepare_open', payload: { operationId, machineId: machineId(), agentId } }) },+ }+}diff --git a/cli/src/core/wifiLink.spec.ts b/cli/src/core/wifiLink.spec.tsnew file mode 100644index 000000000..e54ab33de--- /dev/null+++ b/cli/src/core/wifiLink.spec.ts@@ -0,0 +1,130 @@+import { describe, expect, it, vi } from 'vitest'+import { fakeCore } from '../testing/fakeCore.js'+import { createWifiLink, WIFI_WAIT_MS } from './wifiLink.js'+import type { ServiceFrame } from './serviceLinks.js'++function link(answer: Record<string, unknown> = {}) {+ const core = fakeCore()+ const sent: ServiceFrame[] = []+ const call = vi.fn(async () => answer)+ const log = vi.fn()+ const wifi = createWifiLink({ core, notify: (frame) => { sent.push(frame); return true }, call, log })+ const kinds = () => sent.map((frame) => (frame.payload as { kind: string }).kind)+ return { core, sent, call, log, wifi, kinds }+}++describe('the Wi-Fi device in the devices\' process, as the core sees it', () => {+ it('tells it everything as notices, in the order the core said it', async () => {+ const { wifi, sent, kinds } = link()+ const client = { role: 'device' as const, label: 'Desk', identity: 'id', direct: false }+ wifi.port.session('c', client)+ await wifi.port.request('c', { type: 'autonomous_device_request' }, { payload: { type: 'hello' } })+ wifi.port.dropped('c')+ wifi.port.revoked('id')+ await wifi.port.resume({ sessions: [{ connId: 'c', client }], helloed: [], focus: null })+ wifi.port.card({ type: 'commander_event' })+ wifi.port.card({ type: 'commander_event' }, 'whole')+ wifi.port.turnStarted('a')+ wifi.port.turnEnded('a', true)+ wifi.port.stream('a', [])+ wifi.port.transcript('a', 's', 'claude', 'line')+ wifi.port.delivery({ deliveryId: 'd', sessionId: 'a', state: 'delivered' })+ wifi.port.dispatched('a', 'd', 'hi')+ wifi.port.dispatched('a', 'd', 'hi', 's')+ wifi.port.inputStatus({ deliveryId: 'd' } as never)+ wifi.port.agentGone('a')+ await wifi.port.appFocus('m', null, 'w')+ wifi.port.revealed('op', 'a')+ await wifi.port.stop()+ expect(kinds()).toEqual(['session', 'request', 'dropped', 'revoked', 'resume', 'card', 'card', 'turnStarted', 'turnEnded', 'stream',+ 'transcript', 'delivery', 'dispatched', 'dispatched', 'inputStatus', 'agentGone', 'appFocus', 'revealed'])+ expect(sent[0].payload).toEqual({ kind: 'session', connId: 'c', client })+ expect(sent[5].payload).toEqual({ kind: 'card', frame: { type: 'commander_event' } })+ expect(sent[6].payload).toEqual({ kind: 'card', frame: { type: 'commander_event' }, fullText: 'whole' })+ expect(sent[12].payload).toEqual({ kind: 'dispatched', agentId: 'a', deliveryId: 'd', text: 'hi' })+ expect(sent[13].payload).toMatchObject({ sessionId: 's' })+ })++ it('asks it for a receipt with a deadline, and says it is not running when it does not answer', async () => {+ const receipt = { idempotencyKey: 'k', state: 'completed' }+ const answered = link({ receipt })+ expect(await answered.wifi.port.receipt('dev', 'k')).toEqual({ receipt })+ expect(answered.call).toHaveBeenCalledWith('receipt', { deviceId: 'dev', idempotencyKey: 'k' }, WIFI_WAIT_MS)+ expect(await link({}).wifi.port.receipt('dev', 'k')).toEqual({ receipt: null })+ expect(await link({ error: 'SERVICE_UNAVAILABLE' }).wifi.port.receipt('dev', 'k')).toEqual({ unavailable: true })+ })++ it('answers what it asks through the core\'s Wi-Fi doors', async () => {+ const { wifi, core } = link()+ expect(await wifi.answer('machine', {})).toEqual({ id: 'machine-1' })+ expect(await wifi.answer('view', {})).toEqual({ agents: [], store: [], hasWindow: true })+ vi.mocked(core.turns.recent).mockResolvedValueOnce([{ recap: 'done' }] as never)+ expect(await wifi.answer('recent', { agentId: 'a', n: 1 })).toEqual({ turns: [{ recap: 'done' }] })+ expect(core.turns.recent).toHaveBeenLastCalledWith('a', 1)+ await wifi.answer('recent', { agentId: 7 })+ expect(core.turns.recent).toHaveBeenLastCalledWith('', 3)+ expect(await wifi.answer('stop', { agentId: 'a' })).toEqual({ ok: true })+ expect(await wifi.answer('answer', { agentId: 'a', questionRequestId: 'r', answers: { q: 'yes' }, requestId: 'the-link-s-own' })).toEqual({ ok: true })+ expect(core.wifi.answer).toHaveBeenLastCalledWith('a', 'r', { q: 'yes' })+ await wifi.answer('answer', { agentId: 'a', questionRequestId: 'r', answers: ['no'] })+ expect(core.wifi.answer).toHaveBeenLastCalledWith('a', 'r', {})+ expect(await wifi.answer('create', { packageId: 'p', engine: 'claude', cwd: '/w' })).toEqual({ ok: false, error: 'UNSUPPORTED' })+ expect(await wifi.answer('stepFocus', { direction: 'previous', currentAgentId: 'a' })).toEqual({ step: 'no_agents' })+ expect(core.wifi.stepFocus).toHaveBeenLastCalledWith('previous', 'a')+ vi.mocked(core.wifi.stepFocus).mockResolvedValueOnce({ machineId: 'm', agentId: 'b' })+ expect(await wifi.answer('stepFocus', { direction: 'next' })).toEqual({ machineId: 'm', agentId: 'b' })+ expect(core.wifi.stepFocus).toHaveBeenLastCalledWith('next', undefined)+ expect(await wifi.answer('submit', { agentId: 'a', text: 'hi', deliveryId: 'd' })).toEqual({})+ expect(core.wifi.submit).toHaveBeenCalledWith('a', 'hi', 'd')+ expect(await wifi.answer('nothing', {})).toEqual({ error: 'UNKNOWN_QUERY' })+ })++ it('hears what it tells the core without asking, and says when it hears something else', () => {+ const { wifi, core, log } = link()+ wifi.notice({ kind: 'cancel', deliveryId: 'd' })+ wifi.notice({ kind: 'started', agentId: 'a', text: 'hi' })+ wifi.notice({ kind: 'scroll', phase: 'move', dy: 3, velocity: 9 })+ wifi.notice({ kind: 'scroll', phase: 'fling', dy: 3 })+ wifi.notice({ kind: 'scroll', phase: 'up', dy: 'far' })+ wifi.notice({ kind: 'focusApp', agentId: 'a', expiresAt: 5, focusRevision: 'r' })+ wifi.notice({ kind: 'reveal', operationId: 'op', agentId: 'a' })+ wifi.notice({ kind: 'send', connId: 'c', identity: 'id', type: 'autonomous_device_result', payload: { ok: true } })+ wifi.notice({ kind: 'hello', connId: 'c', identity: 'id' })+ wifi.notice({ kind: 'hello', connId: 'c', identity: null })+ wifi.notice({ kind: 'joined' })+ wifi.notice({ kind: 'ready' })+ wifi.notice({ kind: 'unpaired', identity: 'id' })+ wifi.notice({ kind: 'focus', revision: 'r' })+ wifi.notice({ kind: 'transcripts', agentId: 'a', seen: 2 })+ wifi.notice({ kind: 'watching', agentIds: ['a', 4] })+ wifi.notice({ kind: 'streams', agentIds: 'a' })+ expect(core.wifi.cancel).toHaveBeenCalledWith('d')+ expect(core.wifi.started).toHaveBeenCalledWith('a', 'hi')+ expect(core.wifi.scroll).toHaveBeenCalledTimes(2)+ expect(core.wifi.scroll).toHaveBeenCalledWith('move', 3, 9)+ expect(core.wifi.scroll).toHaveBeenLastCalledWith('up', 0, 0)+ expect(core.wifi.focusApp).toHaveBeenCalledWith('a', 5, 'r')+ expect(core.wifi.reveal).toHaveBeenCalledWith('op', 'a')+ expect(core.wifi.send).toHaveBeenCalledWith('c', 'id', 'autonomous_device_result', { ok: true })+ expect(core.wifi.hello).toHaveBeenCalledWith('c', 'id')+ expect(core.wifi.hello).toHaveBeenLastCalledWith('c', null)+ expect(core.wifi.joined).toHaveBeenCalled()+ expect(core.wifi.ready).toHaveBeenCalled()+ expect(core.wifi.unpaired).toHaveBeenCalledWith('id')+ expect(core.wifi.focus).toHaveBeenCalledWith('r')+ expect(core.wifi.transcripts).toHaveBeenCalledWith('a', 2)+ expect(core.wifi.watching).toHaveBeenCalledWith(['a'])+ expect(core.wifi.streams).toHaveBeenCalledWith([])+ wifi.notice({ kind: 'toString' })+ wifi.notice({})+ expect(log).toHaveBeenCalledWith('[services] wifi said toString, which the core does not hear')+ expect(log).toHaveBeenLastCalledWith('[services] wifi said nothing, which the core does not hear')+ })++ it('logs to the console by default', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ createWifiLink({ core: fakeCore(), notify: () => true, call: async () => ({}) }).notice({ kind: 'nope' })+ expect(warn).toHaveBeenCalledWith('[services] wifi said nope, which the core does not hear')+ warn.mockRestore()+ })+})diff --git a/cli/src/core/wifiLink.ts b/cli/src/core/wifiLink.tsnew file mode 100644index 000000000..f7c7f7fd7--- /dev/null+++ b/cli/src/core/wifiLink.ts@@ -0,0 +1,124 @@+/**+ * The Wi-Fi device's service in the devices' process (services/wifiProcess.ts), as the core sees it: the+ * port the core calls (`WifiPort`) and what the core answers when the service asks (step 9, D3).+ *+ * Everything the core tells it is a notice on its link, in the order the core said it, so a request, the+ * prompt it sends and the transcript lines that prove it reach the service as they happened here; dropped+ * while it is down, as a frame lost on the way is, which its devices retry by the same key. What the+ * service needs to start over (the sessions, which of them said hello, the window's focus) the core keeps+ * and says again each time it connects (core/wifi.ts `started`). The one question the core asks it is a+ * person's (`harness device receipt`), with a deadline.+ *+ * What it asks of the core is `CoreApi`'s Wi-Fi doors, as it would call them in the core's process:+ * the agents as it lists them, a stop, an answer, an agent made for a Store harness, a step along the desk+ * and a recent turn, as queries; the rest as notices.+ */+import type { AutonomousDeviceReceipt } from '../lib/autonomous-device/service.js'+import { WIFI_FALLBACKS, readFallback, type CoreApi, type WifiPort, type WifiReceipt } from './api.js'+import type { ServiceFrame } from './serviceLinks.js'++export interface WifiLinkDeps {+ core: CoreApi+ /** A notice for the service's process; false when it is not connected to hear it. */+ notify(frame: ServiceFrame): boolean+ /** A request to the service's process, answered SERVICE_UNAVAILABLE when it is down or slow. */+ call(type: string, payload: Record<string, unknown>, waitMs: number): Promise<Record<string, unknown>>+ log?: (line: string) => void+}++/** How long `harness device receipt` waits for the service. */+export const WIFI_WAIT_MS = 5_000++const text = (value: unknown): string => (typeof value === 'string' ? value : '')+const number = (value: unknown): number => (typeof value === 'number' && Number.isFinite(value) ? value : 0)+const strings = (value: unknown): string[] => (Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [])+const object = (value: unknown): Record<string, unknown> => (value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {})++export function createWifiLink(deps: WifiLinkDeps) {+ const { core } = deps+ const log = deps.log ?? ((line: string) => console.warn(line))+ const event = (kind: string, payload: Record<string, unknown> = {}): void => { deps.notify({ type: 'service_event', payload: { ...payload, kind } }) }++ const port: WifiPort = {+ session: (connId, client) => event('session', { connId, client }),+ request: async (connId, frame, opened) => event('request', { connId, frame, opened }),+ dropped: (connId) => event('dropped', { connId }),+ revoked: (identity) => event('revoked', { identity }),+ resume: async (state) => event('resume', { ...state }),+ card: (frame, fullText) => event('card', { frame, ...(fullText === undefined ? {} : { fullText }) }),+ turnStarted: (agentId) => event('turnStarted', { agentId }),+ turnEnded: (agentId, aborted) => event('turnEnded', { agentId, aborted }),+ stream: (agentId, events) => event('stream', { agentId, events }),+ transcript: (agentId, sessionId, engine, line) => event('transcript', { agentId, sessionId, engine, line }),+ delivery: (delivery) => event('delivery', { event: delivery }),+ dispatched: (agentId, deliveryId, said, sessionId) => event('dispatched', { agentId, deliveryId, text: said, ...(sessionId === undefined ? {} : { sessionId }) }),+ inputStatus: (status) => event('inputStatus', { event: status }),+ agentGone: (agentId) => event('agentGone', { agentId }),+ appFocus: async (machineId, agentId, connId) => event('appFocus', { machineId, agentId, connId }),+ revealed: (operationId, agentId) => event('revealed', { operationId, agentId }),+ receipt: async (deviceId, idempotencyKey) => {+ const answer = await deps.call('receipt', { deviceId, idempotencyKey }, WIFI_WAIT_MS)+ if (typeof answer.error === 'string') return readFallback(WIFI_FALLBACKS.receipt).value as WifiReceipt+ return { receipt: (answer.receipt ?? null) as AutonomousDeviceReceipt | null }+ },+ // Its own process: the master stops it.+ stop: async () => {},+ }++ /** What the service may ask of the core (`service_query`), by name. */+ const queries: Record<string, (payload: Record<string, unknown>) => Record<string, unknown> | Promise<Record<string, unknown>>> = {+ // Which machine this is (the account's id, which every frame to a device carries), asked as it connects.+ machine: () => ({ id: core.machine.id() }),+ view: async () => ({ ...await core.wifi.view() }),+ // Asked, not told: the pane's lock says what became of the prompt as it takes it, and the device's reply+ // carries that, as it did when the service ran in the core's process.+ submit: async ({ agentId, text: said, deliveryId }) => {+ await core.wifi.submit(text(agentId), text(said), text(deliveryId))+ return {}+ },+ recent: async ({ agentId, n }) => ({ turns: await core.turns.recent(text(agentId), typeof n === 'number' ? n : 3) }),+ stop: async ({ agentId }) => ({ ok: await core.wifi.stop(text(agentId)) }),+ // The question's id travels as `questionRequestId`: a query's own `requestId` is the link's.+ answer: async ({ agentId, questionRequestId, answers }) =>+ ({ ok: await core.wifi.answer(text(agentId), text(questionRequestId), object(answers) as Record<string, string>) }),+ create: async ({ packageId, engine, cwd }) => ({ ...await core.wifi.create(text(packageId), text(engine), text(cwd)) }),+ stepFocus: async ({ direction, currentAgentId }) => {+ const step = await core.wifi.stepFocus(direction === 'previous' ? 'previous' : 'next', typeof currentAgentId === 'string' ? currentAgentId : undefined)+ return typeof step === 'string' ? { step } : { ...step }+ },+ }++ /** What the service tells the core without asking (`service_notice`), by kind. */+ const notices: Record<string, (payload: Record<string, unknown>) => void> = {+ cancel: ({ deliveryId }) => core.wifi.cancel(text(deliveryId)),+ started: ({ agentId, text: said }) => core.wifi.started(text(agentId), text(said)),+ scroll: ({ phase, dy, velocity }) => { if (phase === 'down' || phase === 'move' || phase === 'up') core.wifi.scroll(phase, number(dy), number(velocity)) },+ focusApp: ({ agentId, expiresAt, focusRevision }) => { core.wifi.focusApp(text(agentId), number(expiresAt), text(focusRevision)) },+ reveal: ({ operationId, agentId }) => core.wifi.reveal(text(operationId), text(agentId)),+ send: ({ connId, identity, type, payload }) => core.wifi.send(text(connId), text(identity), text(type), object(payload)),+ hello: ({ connId, identity }) => core.wifi.hello(text(connId), typeof identity === 'string' ? identity : null),+ joined: () => core.wifi.joined(),+ ready: () => core.wifi.ready(),+ unpaired: ({ identity }) => core.wifi.unpaired(text(identity)),+ focus: ({ revision }) => core.wifi.focus(text(revision)),+ transcripts: ({ agentId, seen }) => core.wifi.transcripts(text(agentId), number(seen)),+ watching: ({ agentIds }) => core.wifi.watching(strings(agentIds)),+ streams: ({ agentIds }) => core.wifi.streams(strings(agentIds)),+ }++ return {+ port,+ answer(query: string, payload: Record<string, unknown>): Record<string, unknown> | Promise<Record<string, unknown>> {+ const ask = Object.hasOwn(queries, query) ? queries[query] : undefined+ return ask ? ask(payload) : { error: 'UNKNOWN_QUERY' }+ },+ notice(payload: Record<string, unknown>): void {+ const kind = text(payload.kind)+ const tell = Object.hasOwn(notices, kind) ? notices[kind] : undefined+ if (!tell) { log(`[services] wifi said ${kind.slice(0, 40) || 'nothing'}, which the core does not hear`); return }+ tell(payload)+ },+ }+}++export type WifiLink = ReturnType<typeof createWifiLink>diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex 789e2b594..33c839dca 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -356,8 +356,9 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {// The devices (services/devicesProcess.ts): the dials on USB (pure-JS serial, a frame decoder whose buffer// is bounded per dial), the window bridges, the fleet's router and its lane, the voice router's engine// worker (a process of its own, outside this budget). Hardware that speaks whatever its firmware says:- // what it costs, it costs here, never a session.- devices: { services: ['devices'], heapLimitMiB: 256, rssLimitMiB: 512 },+ // what it costs, it costs here, never a session. The Wi-Fi device beside them (services/wifiProcess.ts),+ // on a link of its own: its receipts, its streams and its Store preparations.+ devices: { services: ['devices', 'wifi'], heapLimitMiB: 256, rssLimitMiB: 512 },}/** Every service this build can run outside the core's process: what `HARNESSD_SERVICES` names. */diff --git a/cli/src/lib/autonomous-device/overGateway.ts b/cli/src/lib/autonomous-device/overGateway.tsindex 019f6c188..1ee5b1b75 100644--- a/cli/src/lib/autonomous-device/overGateway.ts+++ b/cli/src/lib/autonomous-device/overGateway.ts@@ -17,6 +17,10 @@ export interface DeviceRelayOverGateway {handle(connId: string, frame: Record<string, unknown>, opened: Record<string, unknown> | null): Promise<void>drop(connId: string): voidrevoke(identity: string): void+ /** The sessions whose app said hello. */+ helloed(): string[]+ /** A session whose app said hello to the service's previous run, served on and told to resync. */+ restore(connId: string, identity: string): void/** Sessions on a direct link that said hello. */directSessions(): numberconnected(): boolean@@ -51,6 +55,8 @@ export function deviceRelayOverGateway(deps: {},drop: (connId) => relay.drop(connId),revoke: (identity) => relay.revoke(identity),+ helloed: () => relay.helloed(),+ restore: (connId, identity) => relay.restore(connId, identity),directSessions: () => relay.count((connId) => deps.client(connId)?.direct === true),connected: () => relay.connected(),emit: (frame, deviceId) => relay.emit(frame, deviceId),diff --git a/cli/src/lib/autonomous-device/relay.spec.ts b/cli/src/lib/autonomous-device/relay.spec.tsindex 9d1b77327..bd0d0faab 100644--- a/cli/src/lib/autonomous-device/relay.spec.ts+++ b/cli/src/lib/autonomous-device/relay.spec.ts@@ -110,3 +110,36 @@ it('delivers correlated summaries by default only to the originating identity, iawait f.request({ type: 'hello', proto: 1, requestId: randomUUID() })f.relay.emit(result); expect(results()).toHaveLength(0)})++describe('a session served on after the service restarted (services/wifi.ts)', () => {+ it('is served without a new hello, told to resync, and said to have said hello', async () => {+ const f = fixture()+ const clients = vi.fn()+ const relay = new AutonomousDeviceRelay({ sessionRole: () => 'device', sessionIdentity: () => 'trusted-device',+ unwrapDown: (_c: string, frame: Record<string, unknown>) => ({ ...frame, payload: (frame.payload as { __e2e: unknown }).__e2e }),+ wrapTarget: (_c: string, type: string, payload: Record<string, unknown>) => ({ type, payload: { __e2e: payload } }) },+ f.send, f.service, 'machine', undefined, undefined, clients)+ expect(relay.helloed()).toEqual([])+ relay.restore('conn', 'trusted-device')+ expect(relay.helloed()).toEqual(['conn'])+ expect(clients).toHaveBeenCalledWith('conn', 'trusted-device')+ expect(f.send.mock.calls.at(-1)?.[1]).toMatchObject({ type: 'autonomous_device_event', payload: { __e2e: { type: 'resync', reason: 'instance_changed' } } })+ // Its requests are answered as after its hello.+ await relay.handle('conn', { type: 'autonomous_device_request', payload: { __e2e: { type: 'agents.list', requestId: randomUUID() } } })+ expect(f.send.mock.calls.at(-1)?.[1]).toMatchObject({ payload: { __e2e: { type: 'agents.list_result', machineId: 'machine' } } })+ // Already served: nothing again.+ f.send.mockClear()+ relay.restore('conn', 'trusted-device')+ expect(f.send).not.toHaveBeenCalled()+ })++ it('is not served when the session is no longer that identity\'s device', () => {+ const f = fixture()+ f.setRole('web')+ f.relay.restore('conn', 'trusted-device')+ f.setRole('device')+ f.relay.restore('conn', 'another-device')+ expect(f.relay.helloed()).toEqual([])+ expect(f.send).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/lib/autonomous-device/relay.ts b/cli/src/lib/autonomous-device/relay.tsindex 785112755..b708d19df 100644--- a/cli/src/lib/autonomous-device/relay.ts+++ b/cli/src/lib/autonomous-device/relay.ts@@ -80,6 +80,22 @@ export class AutonomousDeviceRelay {emit(event: AutonomousDeviceFrame, deviceId?: string): void {for (const [connId, client] of this.clients) if (!deviceId || client.identity === deviceId) this.sendEvent(connId, client.identity, event)}+ /** The sessions whose app said hello, by connection. */+ helloed(): string[] { return [...this.clients.keys()] }+ /**+ * A session whose app said hello to this service's previous run: its process restarted, and the gateway+ * kept the session (services/wifi.ts). It is served on, and told to resync, as a hello naming the previous+ * instance is told (docs/autonomous-device-integration.md: the device re-reads its agents and reconciles+ * its outstanding keys by receipt). Nothing for a session this run already serves, or no longer the+ * identity's device.+ */+ restore(connId: string, identity: string): void {+ if (this.clients.get(connId)?.identity === identity) return+ if (this.crypto.sessionIdentity(connId) !== identity || this.crypto.sessionRole(connId) !== 'device') return+ this.clients.set(connId, { identity, tokens: 20, at: Date.now(), active: 0 })+ this.onClient?.(connId, identity)+ this.service.replay(undefined, event => this.sendEvent(connId, identity, event))+ }drop(connId: string): void {const client = this.clients.get(connId)this.clients.delete(connId)diff --git a/cli/src/lib/autonomous-device/service.ts b/cli/src/lib/autonomous-device/service.tsindex d1e09d88c..7861220a0 100644--- a/cli/src/lib/autonomous-device/service.ts+++ b/cli/src/lib/autonomous-device/service.ts@@ -39,11 +39,13 @@ export interface AutonomousDeviceServiceOptions {* window is connected to scroll.*/scroll?: (phase: 'down' | 'move' | 'up', dy: number, velocity: number) => boolean- submit: (agentId: string, text: string, deliveryId: string) => void+ /** Settles once the pane's lock has taken the prompt: the reply carries what it said of it meanwhile. */+ submit: (agentId: string, text: string, deliveryId: string) => void | Promise<void>cancelDelivery: (deliveryId: string) => booleanstop: (agentId: string) => Promise<boolean>answer: (agentId: string, questionRequestId: string, answers: Record<string, string>) => Promise<boolean>- recent: (agentId: string, n: number) => unknown[]+ /** A promise when the turns are asked of the core from another process (services/wifi.ts). */+ recent: (agentId: string, n: number) => unknown[] | Promise<unknown[]>/*** The newest turn's COMPLETE final answer for an agent, or undefined.*@@ -122,6 +124,10 @@ export class AutonomousDeviceService {}return false}+ /** Whether it still reads this agent's transcript: the core sends its lines only while it does (core/wifi.ts). */+ watchesTranscript(agentId: string): boolean { return this.transcriptAgents.has(agentId) }+ /** The agents whose transcripts it reads. */+ transcriptWatches(): string[] { return [...this.transcriptAgents] }observeTranscript(agentId: string, sessionId: string, engine: string, line: string): void {if (!this.needsTranscript(agentId, sessionId, engine)) returnif (this.transcriptSessions.get(agentId) !== sessionId) {@@ -352,6 +358,8 @@ export class AutonomousDeviceService {private readonly streams: AgentStreams/** Live events of one agent, for its subscribers only. Never recorded in the replay log. */stream(agentId: string, events: readonly LiveEvent[]): void { this.streams.ingest(agentId, events) }+ /** The agents a device subscribed to: the core sends their tools' events too (core/wifi.ts). */+ streamedAgents(): string[] { return this.streams.agents() }/** The device's last link closed: its subscriptions end with it, and a reconnect subscribes again. */deviceOffline(deviceId: string): void { this.streams.dropDevice(deviceId) }@@ -380,8 +388,8 @@ export class AutonomousDeviceService {}private key(deviceId: string, key: string): string { return `${deviceId}:${key}` }/** The newest `recap` turn's headline for an agent, or undefined when no turn has been summarised. */- private latestRecap(agentId: string): string | undefined {- const first = this.options.recent(agentId, 1)[0]+ private async latestRecap(agentId: string): Promise<string | undefined> {+ const first = (await this.options.recent(agentId, 1))[0]const recap = object(first) && typeof first.recap === 'string' ? first.recap.replace(/\s+/g, ' ').trim() : ''return recap ? recap.slice(0, AGENT_RECAP_MAX_CHARS) : undefined}@@ -576,10 +584,10 @@ export class AutonomousDeviceService {if (type === 'scroll') { this.scroll(req); return response({}) }if ('focusRevision' in req && (typeof req.focusRevision !== 'string' || !req.focusRevision)) fail('INVALID_REQUEST', 'focusRevision must be a nonempty string')if (type === 'agents.list') {- return response({ machineId: this.options.machineId, agents: this.options.agents().map(a => {- const recap = this.latestRecap(a.agentId)+ return response({ machineId: this.options.machineId, agents: await Promise.all(this.options.agents().map(async a => {+ const recap = await this.latestRecap(a.agentId)return { ...a, machineId: this.options.machineId, ...(recap ? { recap } : {}) }- }) })+ })) })}if (typeof req.agentId !== 'string' || !req.agentId || typeof req.machineId !== 'string') fail('MISSING_TARGET', 'machineId and agentId are required')if (req.machineId !== this.options.machineId) fail('MACHINE_MISMATCH', 'Only the paired machine is available')@@ -609,7 +617,7 @@ export class AutonomousDeviceService {if (type === 'recap') {const n = req.n ?? 3if (!Number.isInteger(n) || Number(n) < 1 || Number(n) > 5) fail('INVALID_REQUEST', 'n must be from 1 to 5')- return response({ machineId: this.options.machineId, agentId, turns: this.options.recent(agentId, Number(n)) })+ return response({ machineId: this.options.machineId, agentId, turns: await this.options.recent(agentId, Number(n)) })}if (type === 'question.answer' && this.questions.get(agentId)?.requestId !== req.questionRequestId) fail('QUESTION_STALE', 'Question is no longer open')this.reserveCapacity()@@ -618,7 +626,7 @@ export class AutonomousDeviceService {this.entries.set(key, entry); this.deliveries.set(entry.receipt.deliveryId, entry); reserved = entrythis.persist() // durable reservation MUST precede any engine writetry {- if (type === 'turn.send') this.options.submit(agentId, String(req.text), entry.receipt.deliveryId)+ if (type === 'turn.send') await this.options.submit(agentId, String(req.text), entry.receipt.deliveryId)else {const ok = type === 'turn.stop' ? await this.options.stop(agentId) : await this.options.answer(agentId, String(req.questionRequestId), req.answers as Record<string, string>)if (this.entries.get(key) !== entry) {diff --git a/cli/src/lib/autonomous-device/storeRuntime.spec.ts b/cli/src/lib/autonomous-device/storeRuntime.spec.tsindex 16529c0ec..f06518f94 100644--- a/cli/src/lib/autonomous-device/storeRuntime.spec.ts+++ b/cli/src/lib/autonomous-device/storeRuntime.spec.ts@@ -6,14 +6,18 @@ import { randomUUID } from 'node:crypto'import type { RegisteredSession } from '../registry.js'import type { DshRegistryEntry } from '../../dsh/registry.js'const state = vi.hoisted(() => ({ agents: [] as RegisteredSession[], catalog: [] as DshRegistryEntry[] }))-vi.mock('../registry.js', () => ({ registry: { list: () => state.agents, terminalAvailable: () => true } }))+// The core's registry, as the core's Wi-Fi doors read it (core/wifiAgents.ts): the Store runs with the device's+// service, in the devices' process, and reads the agents and makes one through them.+const registry = { list: () => state.agents, advertised: () => state.agents, terminalAvailable: () => true }+const deviceStoreAgents = (machineId: string) => storeAgents({ registry, machineId: () => machineId })vi.mock('../../dsh/catalog.js', () => ({ refreshDshRegistry: async () => state.catalog, catalogEntry: (id: string) => state.catalog.find(e => e.id === id) }))import { env } from '../../config/env.js'import * as engineLaunch from '../engineLaunch.js'import { installDsh } from '../../dsh/install.js'import { installedDsh, invalidateInstalledDsh } from '../../dsh/installed.js'import { materializeWorkspace } from '../../dsh/materialize.js'-import { createDeviceStore, deviceStorePackages, deviceStoreAgents } from './storeRuntime.js'+import { createDeviceStore, deviceStorePackages } from './storeRuntime.js'+import { storeAgents, wifiCreate } from '../../core/wifiAgents.js'import { DeviceStoreResultSchema } from './storeContract.js'import { HARNESS_MONOREPO } from '../../dsh/registry.js'@@ -43,7 +47,8 @@ async function setup() {state.agents.push(session)return { ok: true as const, session }})- const store = createDeviceStore({ dataDir: join(root, 'state'), machineId: 'mac', create })+ const store = createDeviceStore({ dataDir: join(root, 'state'), machineId: 'mac', agents: () => deviceStoreAgents('mac'),+ create: wifiCreate({ registry, machineId: () => 'mac', createAgent: () => create }) })const request = { type: 'agent.prepare', requestId: randomUUID(), machineId: 'mac', packageId: 'test/robot-fixture', workspace: { kind: 'existing', path: cwd }, idempotencyKey: 'prepare' }return { source, cwd, create, store, request }}diff --git a/cli/src/lib/autonomous-device/storeRuntime.ts b/cli/src/lib/autonomous-device/storeRuntime.tsindex b816c40be..257379504 100644--- a/cli/src/lib/autonomous-device/storeRuntime.ts+++ b/cli/src/lib/autonomous-device/storeRuntime.ts@@ -1,9 +1,11 @@/** Narrow adapter onto the SAME Store, project preparation and engine creator used by Desktop.- * Never passes device frames to BackendSocket's generic dispatcher.+ * Never passes device frames to BackendSocket's generic dispatcher. It runs with the Wi-Fi device's+ * service, in the devices' process (services/wifi.ts): the agents it reads and the one it creates are the+ * core's (`CoreApi.wifi.view` and `create`, core/wifiAgents.ts).*/import { realpathSync, statSync } from 'node:fs'import { join } from 'node:path'-import type { BackendSocket } from '../../backendSocket.js'+import type { ForkResult } from '../../core/api.js'import { refreshDshRegistry } from '../../dsh/catalog.js'import { installedDsh, listDshState } from '../../dsh/installed.js'import { runDshDoctor } from '../../dsh/install.js'@@ -11,21 +13,9 @@ import { viewerUse } from '../../dsh/manifest.js'import { HARNESS_MONOREPO, type DshRegistryEntry } from '../../dsh/registry.js'import { mutateDsh } from '../../dsh/service.js'import { prepareProjectFolder, ProjectFolderError } from '../projectFolder.js'-import { registry } from '../registry.js'import { AutonomousDeviceStore, type StoreAgent, type StorePackage } from './store.js'import { DeviceStoreError } from './storeContract.js'-const canonicalPath = (path: string | null): string | null => {- if (!path) return null- try { return realpathSync(path) } catch { return path }-}-export function deviceStoreAgents(machineId: string): StoreAgent[] {- return registry.list().map(s => ({ agentId: s.agentId, machineId, packageId: s.dsh ? installedDsh(s.dsh)?.id ?? s.dsh : null,- engine: s.engine, workspace: canonicalPath(s.cwd), state: s.active ? 'active' : 'inactive',- runtime: !registry.terminalAvailable(s.agentId) || s.launch?.state === 'failed' ? 'unavailable'- : s.launch?.state === 'starting' ? 'starting' : s.active ? (s.launch?.state === 'ready' || s.sessionId || s.engine === 'terminal' ? 'ready' : 'starting') : 'unavailable',- ...(s.launch?.state === 'failed' ? { error: s.launch.detail ?? s.launch.error } : {}) }))-}function trusted(entry: DshRegistryEntry | undefined): boolean {return !!entry && entry.verified === true && entry.repo.replace(/\.git$/, '') === HARNESS_MONOREPO&& entry.id.startsWith('autonomous/') && entry.path === `store/${entry.kind === 'viewer' ? 'viewers' : 'agents'}/${entry.id.slice(11)}`@@ -53,11 +43,21 @@ export async function deviceStorePackages(): Promise<StorePackage[]> {})}-export function createDeviceStore(options: { dataDir: string; machineId: string; create: NonNullable<BackendSocket['onCreateAgent']>; reveal?: (operationId: string, agentId: string) => void }): AutonomousDeviceStore {+export interface DeviceStoreOptions {+ dataDir: string+ machineId: string+ /** Every agent with the Store's evidence on it, as the core last listed them. */+ agents(): StoreAgent[]+ /** The core starts the agent, with the device's fixed launch arguments, unless another works in `cwd`. */+ create(packageId: string, engine: string, cwd: string): Promise<ForkResult>+ reveal?: (operationId: string, agentId: string) => void+}++export function createDeviceStore(options: DeviceStoreOptions): AutonomousDeviceStore {return new AutonomousDeviceStore({directory: join(options.dataDir, 'device-preparations'), machineId: options.machineId, reveal: options.reveal,packages: deviceStorePackages,- agents: () => deviceStoreAgents(options.machineId),+ agents: () => options.agents(),install: async (id, progress) => {const pkg = (await deviceStorePackages()).find(p => p.packageId === id)if (!pkg?.installAllowed) return { ok: false, error: 'PACKAGE_REVIEW_REQUIRED', detail: 'Review this package and its dependencies in Harness Store first.' }@@ -96,11 +96,10 @@ export function createDeviceStore(options: { dataDir: string; machineId: string;create: async (id, cwd) => {const pkg = installedDsh(id)if (!pkg?.manifest.engine || pkg.manifest.kind === 'viewer') return { state: 'failed', error: 'INVALID_DSH' }- // Check again immediately before materialization; never retarget another agent.- if (deviceStoreAgents(options.machineId).some(a => a.workspace === cwd)) return { state: 'failed', error: 'WORKSPACE_IN_USE' }- const result = await options.create({ engine: pkg.manifest.engine, cwd, dsh: id,- bypassPermission: false, permissionMode: null, grid: null, codexHome: null, prompt: null, name: null, agent: null })- if (result.ok) return { state: 'created', agentId: result.session.agentId }+ // The core checks again immediately before materialization, where the agents are: never retarget another agent.+ const result = await options.create(id, pkg.manifest.engine, cwd)+ if (result.ok) return { state: 'created', agentId: result.agentId }+ if (result.error === 'WORKSPACE_IN_USE') return { state: 'failed', error: 'WORKSPACE_IN_USE' }if (['SPAWN_FAILED', 'REGISTRATION_FAILED'].includes(result.error)) return { state: 'unconfirmed' }return { state: 'failed', error: result.error, detail: result.detail }},diff --git a/cli/src/lib/autonomous-device/stream.ts b/cli/src/lib/autonomous-device/stream.tsindex d4d6bf1dd..bfca6dd8a 100644--- a/cli/src/lib/autonomous-device/stream.ts+++ b/cli/src/lib/autonomous-device/stream.ts@@ -118,6 +118,8 @@ export class AgentStreams {}count(): number { return this.subs.size }+ /** The agents subscribed to, each once. */+ agents(): string[] { return [...new Set([...this.subs.values()].map(s => s.agentId))] }private watching(agentId: string, kind?: StreamKind): Subscription[] {const at = this.now()diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.tsindex 2fbdd15d4..639648586 100644--- a/cli/src/serviceProcess.ts+++ b/cli/src/serviceProcess.ts@@ -39,6 +39,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M['gateway', async () => (await import('./gateway/gatewayProcess.js')).runGatewayService],['models', async () => (await import('./services/modelsProcess.js')).runModelsService],['devices', async () => (await import('./services/devicesProcess.js')).runDevicesService],+ ['wifi', async () => (await import('./services/wifiProcess.js')).runWifiService],])export interface ServiceProcessDeps {diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.mdindex 3d8da5bb1..d39b4b113 100644--- a/cli/src/services/AGENTS.md+++ b/cli/src/services/AGENTS.md@@ -45,7 +45,7 @@ A service that can crash natively, hang or leak should run in a process of its othat process. A process per risk, not per feature: search (native `node:sqlite`), the viewers (theirservers) with the Store (its minutes-long installs), each experiment (below), models (grid's installs,downloads and commands), the devices (the dials' serial ports, the fleet's lane, the voice router's-worker), and the edge host, one process for the light services that only answer requests+worker, and the Wi-Fi device), and the edge host, one process for the light services that only answer requests(workspaces, usage, the monitor, the project readers). A fault in one of the edge host's services cancost the others in it, never the core. Every service in `KNOWN_SERVICES` runs out of the core's processby default, unless `HARNESSD_SERVICES` names a subset, by service (`search,usage`) or by process@@ -121,7 +121,11 @@ way back).the process connects, and a dial attaching is shown the open questions and the working tiles. Inside,one device failing is that device's alone: its session's faults and a flood on its port drop it, andits port is looked at again later (src/cable/cableFleet.ts). `e2e/devicesProcess.e2e.ts` proves it,- with fake dials on pseudo-terminals.+ with fake dials on pseudo-terminals. The Wi-Fi device runs beside them on a link of its own+ (src/services/wifiProcess.ts, src/core/wifiLink.ts): its sessions are the gateway's, so the core hands+ their requests on in order and checks where each answer goes, and keeps what it reads in line of the+ service (who said hello, which transcripts and streams it follows, the focus revision) from what the+ service tells it (src/core/wifi.ts). `e2e/wifiDevice.e2e.ts` proves it, with a fake device on the relay.- State built from every change must get every change exactly once. The teams show how(`src/services/teamsProcess.ts`, `src/core/teamsLink.ts`): the core numbers each change and keeps ituntil the process acknowledges it; on each connection the process says what it applied and getsdiff --git a/cli/src/services/devices.ts b/cli/src/services/devices.tsindex a09fe7217..4142f91ed 100644--- a/cli/src/services/devices.ts+++ b/cli/src/services/devices.ts@@ -13,7 +13,8 @@* 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).+ * The Wi-Fi device is a service of its own beside these (services/wifi.ts), in the same process, on a link+ * of its own: it rides the gateway's sessions, and borrows the dial's walk and stroke through the core.*/import { existsSync, writeFileSync } from 'node:fs'import { join } from 'node:path'diff --git a/cli/src/services/devicesProcess.ts b/cli/src/services/devicesProcess.tsindex a4d354b95..be1256573 100644--- a/cli/src/services/devicesProcess.ts+++ b/cli/src/services/devicesProcess.ts@@ -168,6 +168,8 @@ export function runDevicesService(options: DevicesServiceOptions): ServiceProceswindows: () => {},},daemon: DAEMON_UNKNOWN,+ // The Wi-Fi device beside the dials has a link of its own (services/wifiProcess.ts).+ wifi: unasked.wifi,}const ports: CorePorts = emptyPorts()diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.tsindex 64f6e590b..b6b34e48f 100644--- a/cli/src/services/inline.spec.ts+++ b/cli/src/services/inline.spec.ts@@ -12,10 +12,11 @@ import { startSharing } from './sharing.js'import { startStore } from './store.js'import { startUsage } from './usage.js'import { startViewers } from './viewers.js'+import { startWifi } from './wifi.js'import { startWorkspaces } from './workspaces.js'describe('the services the core runs in its own process only when they do not run in theirs', () => {it('are their own starts, unchanged: the same services either way', () => {- expect({ ...inline }).toEqual({ startDevices, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWorkspaces })+ expect({ ...inline }).toEqual({ startDevices, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWorkspaces })})})diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.tsindex 1810938dd..a87750d7a 100644--- a/cli/src/services/inline.ts+++ b/cli/src/services/inline.ts@@ -24,4 +24,5 @@ export { startSharing } from './sharing.js'export { startStore } from './store.js'export { startUsage } from './usage.js'export { startViewers } from './viewers.js'+export { startWifi } from './wifi.js'export { startWorkspaces } from './workspaces.js'diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.tsindex 661e779b1..f0eba8d88 100644--- a/cli/src/services/modelsProcess.ts+++ b/cli/src/services/modelsProcess.ts@@ -118,6 +118,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: Pa...UNASKED.clients,},daemon: DAEMON_UNKNOWN,+ wifi: UNASKED.wifi,}}diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex 13eee8233..fa8432ce9 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -13,7 +13,7 @@* each asked of the core over its link (`ask`). The agents it reads come as the apps are shown them (`service_query shown`): each with its* name, whether its terminal is there and its harness's viewer.*/-import { DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, OBSERVER_KEY_OFF, resolveAgent, TERMINALS_OFF, type CoreApi, type DaemonAddress, type TerminalWatch } from '../core/api.js'+import { DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, OBSERVER_KEY_OFF, resolveAgent, TERMINALS_OFF, WIFI_OFF, type CoreApi, type DaemonAddress, type TerminalWatch } from '../core/api.js'import type { AgentDshContext } from '../lib/agentFrame.js'import type { RegisteredSession } from '../lib/registry.js'import type { turnsLink } from './turnsLink.js'@@ -63,19 +63,21 @@ function keyAnswer(answer: Payload): string {}/**- * 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.+ * What only the devices ask of the core (services/devices.ts, services/wifi.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: () => {} },+ wifi: WIFI_OFF,} satisfies {machine: CoreApi['machine']activityText: CoreApi['agents']['activityText']account: Pick<CoreApi['account'], 'signedIn' | 'environment' | 'machines'>clients: Pick<CoreApi['clients'], 'sendLocal' | 'sendToWindow' | 'hasWindow' | 'devicesChanged' | 'dialWatching'>+ wifi: CoreApi['wifi']}export function processCoreApi(dataDir: string, service: string, view: AgentsView = {}): CoreApi {@@ -163,5 +165,6 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsViemachineId: () => daemon().machineId(),get autonomousEnv() { return daemon().autonomousEnv },},+ wifi: UNASKED.wifi,}}diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.tsindex 4ae80f73b..e8ec0b5f4 100644--- a/cli/src/services/searchProcess.ts+++ b/cli/src/services/searchProcess.ts@@ -79,6 +79,7 @@ export function searchCoreApi(},clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false, ...UNASKED.clients },daemon: DAEMON_UNKNOWN,+ wifi: UNASKED.wifi,}}diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.tsindex 945acb9aa..a4a113f7a 100644--- a/cli/src/services/viewersProcess.ts+++ b/cli/src/services/viewersProcess.ts@@ -85,6 +85,7 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, Re},clients: { viewerChanged: tell, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false, ...UNASKED.clients },daemon: DAEMON_UNKNOWN,+ wifi: UNASKED.wifi,}}diff --git a/cli/src/services/wifi.spec.ts b/cli/src/services/wifi.spec.tsnew file mode 100644index 000000000..aba8ae048--- /dev/null+++ b/cli/src/services/wifi.spec.ts@@ -0,0 +1,288 @@+import { randomUUID } from 'node:crypto'+import { mkdtempSync, 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 { emptyPorts, type CoreApi, type RemoteClient, type WifiPort } from '../core/api.js'+import { AutonomousDeviceService } from '../lib/autonomous-device/service.js'+import { createDeviceStore } from '../lib/autonomous-device/storeRuntime.js'+import type { LiveEvent } from '../lib/normalize.js'+import { fakeCore } from '../testing/fakeCore.js'+import { startWifi } from './wifi.js'++let dataDir: string+beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'wifi-service-')) })+afterEach(() => { rmSync(dataDir, { recursive: true, force: true }); vi.useRealTimers() })++const client: RemoteClient = { role: 'device', label: 'Desk', identity: 'device-1', direct: true }+const agent = { agentId: 'agent', name: 'Agent', engine: 'claude', state: 'idle' }+/** A request as the gateway hands it on: sealed as it came, and as its session opened it. */+const sealed = (req: Record<string, unknown>) => [{ type: 'autonomous_device_request', payload: { __e2e: true } }, { payload: req }] as const+/** What the service sent the device, in order: the core seals each to its session. */+const sent = (core: CoreApi): Array<Record<string, any>> =>+ vi.mocked(core.wifi.send).mock.calls.map(([connId, identity, frame, payload]) => ({ connId, identity, frame, ...payload }))++function started(over: Parameters<typeof fakeCore>[0] = {}) {+ const core = fakeCore({+ dataDir,+ ...over,+ wifi: { view: vi.fn(async () => ({ agents: [agent], store: [], hasWindow: true })), ...over.wifi },+ })+ const ports = emptyPorts()+ startWifi(core, ports)+ const port = ports.wifi as WifiPort+ const ask = async (req: Record<string, unknown>, connId = 'c1') => {+ const [frame, opened] = sealed({ requestId: randomUUID(), ...req })+ await port.request(connId, frame, opened)+ // Answered once the service's own wait (a stop, an answer) is over.+ await vi.waitFor(() => expect(sent(core).some((m) => m.frame === 'autonomous_device_result' && m.requestId === opened.payload.requestId)).toBe(true))+ return sent(core).find((m) => m.requestId === opened.payload.requestId)!+ }+ const hello = async (connId = 'c1') => {+ port.session(connId, client)+ return ask({ type: 'hello', proto: 1 }, connId)+ }+ return { core, port, ask, hello }+}++describe('the Wi-Fi device, with the dials', () => {+ it('answers a device\'s hello through the core, which seals it to the session it came on, and counts it as watching', async () => {+ const { core, hello } = started()+ const answer = await hello()+ expect(answer).toMatchObject({ connId: 'c1', identity: 'device-1', frame: 'autonomous_device_result', type: 'hello_result', proto: 1, machineId: 'machine-1' })+ expect(core.wifi.hello).toHaveBeenCalledWith('c1', 'device-1')+ expect(core.wifi.joined).toHaveBeenCalled()+ })++ it('lists the agents as the core lists them now, each with its last recap', async () => {+ const { core, hello, ask } = started()+ vi.mocked(core.turns.recent).mockResolvedValue([{ recap: ' Fixed the build ' }] as never)+ await hello()+ expect((await ask({ type: 'agents.list' })).agents).toEqual([{ ...agent, machineId: 'machine-1', recap: 'Fixed the build' }])+ expect(core.wifi.view).toHaveBeenCalled()+ expect((await ask({ type: 'recap', machineId: 'machine-1', agentId: 'agent', n: 2 })).turns).toEqual([{ recap: ' Fixed the build ' }])+ expect(core.turns.recent).toHaveBeenLastCalledWith('agent', 2)+ })++ it('types a prompt through the core, follows its transcript, and says when it no longer needs it', async () => {+ const { core, port, hello, ask } = started()+ await hello()+ const reply = await ask({ type: 'turn.send', machineId: 'machine-1', agentId: 'agent', idempotencyKey: 'k1', text: 'hello' })+ expect(reply).toMatchObject({ status: 'accepted', receipt: { state: 'queued' } })+ const deliveryId = vi.mocked(core.wifi.submit).mock.calls[0][2]+ expect(core.wifi.submit).toHaveBeenCalledWith('agent', 'hello', deliveryId)+ // The core typed it: the service reads the agent's transcript until the turn is proven.+ port.dispatched('agent', deliveryId, 'hello', 's1')+ expect(core.wifi.transcripts).not.toHaveBeenCalled()+ port.transcript('agent', 's1', 'claude', '{"type":"user","message":{"content":"not ours"},"timestamp":"2026-10-06T00:00:00Z"}')+ // An agent it never sent anything to: done with it at once, as of the one prompt the core told of.+ port.dispatched('other', 'unknown-delivery', 'hi')+ expect(core.wifi.transcripts).toHaveBeenCalledWith('other', 1)+ port.transcript('other', 's2', 'claude', '{}')+ expect(core.wifi.transcripts).toHaveBeenLastCalledWith('other', 1)+ port.agentGone('agent')+ expect(core.wifi.transcripts).toHaveBeenLastCalledWith('agent', 1)+ port.agentGone('never-told')+ expect(core.wifi.transcripts).toHaveBeenLastCalledWith('never-told', 0)+ })++ it('tells the core which agents a device subscribed to before the subscription\'s answer leaves', async () => {+ const { core, hello, ask } = started()+ await hello()+ vi.mocked(core.wifi.streams).mockClear()+ const order: string[] = []+ vi.mocked(core.wifi.streams).mockImplementation((ids) => { order.push(`streams ${ids.join(',')}`) })+ vi.mocked(core.wifi.send).mockImplementation((_c, _i, _t, payload) => { order.push(String(payload.type)) })+ await ask({ type: 'agent.subscribe', machineId: 'machine-1', agentId: 'agent' }).catch(() => {})+ expect(order.slice(0, 2)).toEqual(['streams agent', 'agent.subscribe_result'])+ // Told once: the next answer finds the same subscriptions.+ await ask({ type: 'focus.get' })+ expect(core.wifi.streams).toHaveBeenCalledTimes(1)+ })++ it('reads the turn\'s whole answer off a summary card, and passes the agents\' turns and live events on', async () => {+ const { core, port, hello } = started()+ await hello()+ vi.mocked(core.wifi.send).mockClear()+ port.card({ type: 'commander_event', agentId: 'agent', payload: { kind: 'summary', text: 'short' } }, 'the whole answer')+ expect(sent(core).at(-1)).toMatchObject({ frame: 'autonomous_device_event', kind: 'turn.summary', payload: { text: 'short', fullText: 'the whole answer' } })+ port.card({ type: 'commander_event', agentId: 'agent', payload: { kind: 'tool', text: 'Read' } })+ expect(sent(core).at(-1)).toMatchObject({ kind: 'turn.tool' })+ port.turnStarted('agent')+ expect(sent(core).at(-1)).toMatchObject({ kind: 'turn.started' })+ port.turnEnded('agent', true)+ expect(sent(core).at(-1)).toMatchObject({ kind: 'turn.error' })+ port.stream('agent', [{ type: 'turn_started', payload: {} } as unknown as LiveEvent])+ port.delivery({ deliveryId: 'nobody', sessionId: 'agent', state: 'delivered' })+ port.inputStatus({ deliveryId: 'nobody', sessionId: 'agent', mode: 'queued', phase: 'waiting' } as never)+ port.revealed('op', 'agent')+ })++ it('moves the window\'s focus in order, against the agents as they are, and tells the core the revision before anything carries it', async () => {+ const { core, port } = started()+ const order: string[] = []+ vi.mocked(core.wifi.focus).mockImplementation((revision) => { order.push(`focus ${revision}`) })+ await port.appFocus('machine-1', 'agent', 'w1')+ expect(core.wifi.view).toHaveBeenCalled()+ expect(order).toEqual([expect.stringMatching(/^focus .+:1$/)])+ await port.appFocus('machine-1', null, 'w1')+ expect(order.at(-1)).toMatch(/:2$/)+ })++ it('lets a focus move that fails cost that move alone, and the next one is applied', async () => {+ const { core, port } = started()+ vi.mocked(core.wifi.focus).mockImplementationOnce(() => { throw new Error('the core went away') })+ await expect(port.appFocus('machine-1', 'agent', 'w1')).rejects.toThrow('the core went away')+ await port.appFocus('machine-1', null, 'w1')+ expect(core.wifi.focus).toHaveBeenLastCalledWith(expect.stringMatching(/:2$/))+ // A move the core held for a restarted service fails the same way, and the service resumes.+ vi.mocked(core.wifi.focus).mockImplementation((revision) => { if (revision.endsWith(':3')) throw new Error('not now') })+ await port.resume({ sessions: [], helloed: [], focus: { machineId: 'machine-1', agentId: 'agent', connId: 'w2' } })+ expect(core.wifi.ready).toHaveBeenCalled()+ })++ it('says a device\'s request that fails, and answers the next', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { core, port, hello } = started()+ port.session('c1', client)+ vi.mocked(core.wifi.send).mockImplementationOnce(() => { throw new Error('sealing failed') })+ const [frame, opened] = sealed({ type: 'hello', proto: 1, requestId: randomUUID() })+ await port.request('c1', frame, opened)+ await vi.waitFor(() => expect(warn).toHaveBeenCalledWith('[wifi] a device\'s request failed · sealing failed'))+ vi.mocked(core.wifi.send).mockImplementationOnce(() => { throw 'no session' })+ const [again, openedAgain] = sealed({ type: 'hello', proto: 1, requestId: randomUUID() })+ await port.request('c1', again, openedAgain)+ await vi.waitFor(() => expect(warn).toHaveBeenCalledWith('[wifi] a device\'s request failed · no session'))+ expect(await hello()).toMatchObject({ type: 'hello_result' })+ warn.mockRestore()+ })++ it('serves the sessions a previous run served, told to resync, and lets go of those the core no longer holds', async () => {+ const { core, port, hello } = started()+ await hello('stale')+ vi.mocked(core.wifi.send).mockClear()+ vi.mocked(core.wifi.hello).mockClear()+ await port.resume({ sessions: [{ connId: 'c9', client }], helloed: [{ connId: 'c9', identity: 'device-1' }], focus: { machineId: 'machine-1', agentId: 'agent', connId: 'w' } })+ // The stale session is let go of; the one the core holds is served on, and told to resync.+ expect(core.wifi.hello).toHaveBeenCalledWith('stale', null)+ expect(core.wifi.hello).toHaveBeenCalledWith('c9', 'device-1')+ expect(sent(core)).toContainEqual(expect.objectContaining({ connId: 'c9', frame: 'autonomous_device_event', type: 'resync', reason: 'instance_changed' }))+ expect(core.wifi.joined).toHaveBeenCalled()+ expect(core.wifi.ready).toHaveBeenCalled()+ expect(core.wifi.watching).toHaveBeenCalledWith([])+ expect(core.wifi.streams).toHaveBeenCalledWith([])+ expect(core.wifi.focus).toHaveBeenCalled()+ // A session this run already serves is served on as it is: not dropped, not told to resync again.+ vi.mocked(core.wifi.send).mockClear()+ vi.mocked(core.wifi.hello).mockClear()+ await port.resume({ sessions: [{ connId: 'c9', client }], helloed: [{ connId: 'c9', identity: 'device-1' }], focus: null })+ expect(core.wifi.hello).not.toHaveBeenCalled()+ expect(sent(core).filter((m) => m.type === 'resync')).toEqual([])+ // Nothing held, nothing restored, nobody to join.+ vi.mocked(core.wifi.joined).mockClear()+ await port.resume({ sessions: [], helloed: [], focus: null })+ expect(core.wifi.joined).not.toHaveBeenCalled()+ })++ it('forgets a closed connection and an unpaired device, and answers a receipt', async () => {+ const { core, port, hello, ask } = started()+ await hello()+ await ask({ type: 'turn.send', machineId: 'machine-1', agentId: 'agent', idempotencyKey: 'k2', text: 'hi' })+ expect(await port.receipt('device-1', 'k2')).toMatchObject({ receipt: { idempotencyKey: 'k2', state: 'queued' } })+ expect(await port.receipt('device-1', 'nope')).toEqual({ receipt: null })+ port.revoked('device-1')+ expect(core.wifi.cancel).toHaveBeenCalled()+ expect(await port.receipt('device-1', 'k2')).toEqual({ receipt: null })+ await hello('c2')+ port.dropped('c2')+ expect(core.wifi.hello).toHaveBeenLastCalledWith('c2', null)+ // A session the gateway no longer holds is sent nothing.+ port.session('c3', client)+ port.session('c3', null)+ vi.mocked(core.wifi.send).mockClear()+ const [frame, opened] = sealed({ type: 'hello', proto: 1, requestId: randomUUID() })+ await port.request('c3', frame, opened)+ expect(core.wifi.send).not.toHaveBeenCalled()+ await port.stop()+ })++ it('answers a request with the agents it last had when the core cannot be asked', async () => {+ const view = vi.fn(async () => ({ agents: [agent], store: [], hasWindow: true }))+ const { hello, ask } = started({ wifi: { view } })+ await hello()+ view.mockRejectedValueOnce(new Error('the core went away'))+ expect((await ask({ type: 'agents.list' })).agents).toEqual([{ ...agent, machineId: 'machine-1' }])+ })++ it('reaches the core for a stop, an answer, a step along the desk, a stroke and the window\'s focus', async () => {+ const { core, hello, ask } = started()+ await hello()+ expect(await ask({ type: 'turn.stop', machineId: 'machine-1', agentId: 'agent', idempotencyKey: 's1' })).toMatchObject({ receipt: { state: 'completed' } })+ expect(core.wifi.stop).toHaveBeenCalledWith('agent')+ // No window took the ask: said at once.+ vi.mocked(core.wifi.focusApp).mockReturnValueOnce(false)+ expect(await ask({ type: 'focus.ensure' })).toMatchObject({ error: { code: 'FOCUS_UNAVAILABLE' } })+ expect(core.wifi.focusApp).toHaveBeenCalledWith('agent', expect.any(Number), expect.any(String))+ expect(await ask({ type: 'scroll', phase: 'down', dy: 1, velocity: 2 })).not.toHaveProperty('error')+ expect(core.wifi.scroll).toHaveBeenCalledWith('down', 1, 2)+ const focus = (await ask({ type: 'focus.get' })).focusRevision+ expect(await ask({ type: 'focus.step', direction: 'next', idempotencyKey: 'f1', focusRevision: focus })).toMatchObject({ error: { code: 'NO_AGENTS' } })+ expect(core.wifi.stepFocus).toHaveBeenCalledWith('next', undefined)+ })++ it('gives the Store the agents the core listed, and makes and shows its agents through the core', async () => {+ const core = fakeCore({ dataDir, wifi: { view: vi.fn(async () => ({ agents: [], store: [{ agentId: 'a' } as never], hasWindow: true })) } })+ let given: Parameters<typeof createDeviceStore>[0] | undefined+ const ports = emptyPorts()+ startWifi(core, ports, { store: (options) => { given = options; return createDeviceStore(options) } })+ expect(given!.agents()).toEqual([])+ await ports.wifi!.appFocus('machine-1', null, 'w')+ expect(given!.agents()).toEqual([{ agentId: 'a' }])+ await given!.create('autonomous/robot', 'claude', '/w')+ expect(core.wifi.create).toHaveBeenCalledWith('autonomous/robot', 'claude', '/w')+ given!.reveal!('op', 'a')+ expect(core.wifi.reveal).toHaveBeenCalledWith('op', 'a')+ })++ it('hands the core the device\'s answers to questions and the prompts its transcript proved started', async () => {+ const core = fakeCore({ dataDir })+ let given: ConstructorParameters<typeof AutonomousDeviceService>[0] | undefined+ startWifi(core, emptyPorts(), { service: (options) => { given = options; return new AutonomousDeviceService(options) } })+ given!.inputConsumed!('agent', 'hello')+ expect(core.wifi.started).toHaveBeenCalledWith('agent', 'hello')+ expect(await given!.answer('agent', 'r', { q: 'yes' })).toBe(true)+ expect(core.wifi.answer).toHaveBeenCalledWith('agent', 'r', { q: 'yes' })+ })++ it('gives up a pairing the device asked to give up, over its own session', async () => {+ const { core, hello, ask } = started()+ await hello()+ expect(await ask({ type: 'pair.revoke' })).toMatchObject({ revoked: true })+ expect(core.wifi.unpaired).toHaveBeenCalledWith('device-1')+ })++ it('leaves the Wi-Fi device off, and the devices on, when its journal cannot be read', () => {+ writeFileSync(join(dataDir, 'device-results.json'), '{"version": 1, "entries": [', { mode: 0o600 })+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const ports = emptyPorts()+ expect(() => startWifi(fakeCore({ dataDir }), ports)).toThrow('the Wi-Fi device service could not be started')+ expect(ports.wifi).toBeNull()+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('the Wi-Fi device service could not be started'))+ warn.mockRestore()+ })++ it('says a focus change that carries no revision to nobody', () => {+ const emits: Array<(frame: Record<string, unknown>) => void> = []+ const core = fakeCore({ dataDir })+ const ports = emptyPorts()+ startWifi(core, ports, {+ service: (options) => {+ emits.push((frame) => options.emit?.(frame as never))+ return { focusSnapshot: () => ({ focus: null, focusRevision: 'x:0' }) } as unknown as AutonomousDeviceService+ },+ })+ emits[0]({ type: 'event', kind: 'focus.changed', payload: {} })+ emits[0]({ type: 'event', kind: 'focus.changed' })+ expect(core.wifi.focus).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/services/wifi.ts b/cli/src/services/wifi.tsnew file mode 100644index 000000000..c8d10c8e6--- /dev/null+++ b/cli/src/services/wifi.ts@@ -0,0 +1,186 @@+/**+ * The Wi-Fi device (lib/autonomous-device/, docs/autonomous-device-integration.md): a paired device that+ * speaks its own protocol over an E2EE session the gateway holds. Its service, its Store preparations and+ * its relay run here, with the dials in the devices' process (step 9, D3), on `CoreApi` alone: a fault in+ * it costs the devices, never a session (docs/design/2026-10-06-core-boundary-next.md).+ *+ * What the service reads in line while it answers (the agents, the Store's evidence on them, whether a+ * window is there) is the core's answer to `view`, asked again before each request and each move of the+ * window's focus, so what it answers is as fresh as when it ran in the core. What the core reads in line+ * of it (which devices said hello, which transcripts and streams it follows, the focus revision) it is+ * told before anything that depends on it leaves here (core/wifi.ts).+ */+import { join } from 'node:path'+import type { CoreApi, CorePorts, RemoteClient, WifiPort, WifiView } from '../core/api.js'+import { startDevicePart } from '../lib/autonomous-device/parts.js'+import { deviceRelayOverGateway } from '../lib/autonomous-device/overGateway.js'+import { DeviceResultJournal } from '../lib/autonomous-device/resultJournal.js'+import { AutonomousDeviceService, type AutonomousDeviceFrame } from '../lib/autonomous-device/service.js'+import { createDeviceStore } from '../lib/autonomous-device/storeRuntime.js'++export { WIFI_FALLBACKS } from '../core/api.js'++export interface WifiDeps {+ /** Swapped in tests, to reach what the service and the Store are given. */+ service?: (options: ConstructorParameters<typeof AutonomousDeviceService>[0]) => AutonomousDeviceService+ store?: typeof createDeviceStore+}++const same = (a: readonly string[], b: readonly string[]): boolean => a.length === b.length && a.every((item, i) => item === b[i])++export function startWifi(core: CoreApi, ports: CorePorts, deps: WifiDeps = {}): void {+ const machineId = core.machine.id()+ let view: WifiView = { agents: [], store: [], hasWindow: false }+ /** One ask of the core at a time: requests arriving together share it, and are answered in order. */+ let viewing: Promise<void> | null = null+ const refresh = (): Promise<void> => {+ viewing ??= core.wifi.view()+ .then((next) => { view = next })+ .catch(() => { /* the core went away: the next ask is answered by its next connection */ })+ .finally(() => { viewing = null })+ return viewing+ }++ /** The device sessions the gateway holds, as the core said. */+ const sessions = new Map<string, RemoteClient>()+ /** A summary card's whole answer, while the service reads it. */+ let fullText: string | undefined+ /** How many of an agent's prompts the core told of: the core stops sending its lines as of the count. */+ const seen = new Map<string, number>()+ let streamed: string[] = []++ const store = (deps.store ?? createDeviceStore)({+ dataDir: core.dataDir, machineId,+ agents: () => view.store,+ create: (packageId, engine, cwd) => core.wifi.create(packageId, engine, cwd),+ reveal: (operationId, agentId) => core.wifi.reveal(operationId, agentId),+ })++ // Built before the relay that speaks for it; a journal that does not parse leaves the Wi-Fi device off,+ // and the devices on (lib/autonomous-device/parts.ts says why).+ const build = deps.service ?? ((options) => new AutonomousDeviceService(options))+ const service = startDevicePart('Wi-Fi device service', () => build({+ store,+ resultJournal: new DeviceResultJournal(join(core.dataDir, 'device-results.json')),+ inputConsumed: (agentId, text) => core.wifi.started(agentId, text),+ machineId,+ requestAppFocus: (agentId, expiresAt, focusRevision) => core.wifi.focusApp(agentId, expiresAt, focusRevision),+ stepFocus: (direction, currentAgentId) => core.wifi.stepFocus(direction, currentAgentId),+ scroll: (phase, dy, velocity) => core.wifi.scroll(phase, dy, velocity),+ agents: () => view.agents,+ submit: (agentId, text, deliveryId) => core.wifi.submit(agentId, text, deliveryId),+ // Told, not asked: the one caller (an unpairing) goes on whatever the answer.+ cancelDelivery: (deliveryId) => { core.wifi.cancel(deliveryId); return true },+ stop: (agentId) => core.wifi.stop(agentId),+ answer: (agentId, requestId, answers) => core.wifi.answer(agentId, requestId, answers),+ recent: (agentId, n) => core.turns.recent(agentId, n),+ fullText: () => fullText,+ emit: (frame, deviceId) => emit(frame, deviceId),+ }))+ if (!service) throw new Error('the Wi-Fi device service could not be started')++ /** Which streams and which transcripts it follows, told to the core as they change. */+ const reportStreams = (): void => {+ const now = service.streamedAgents().sort()+ if (same(now, streamed)) return+ streamed = now+ core.wifi.streams(now)+ }+ const reportTranscript = (agentId: string): void => {+ if (!service.watchesTranscript(agentId)) core.wifi.transcripts(agentId, seen.get(agentId) ?? 0)+ }++ const relay = deviceRelayOverGateway({+ client: (connId) => sessions.get(connId),+ // Only to a session it found here (`client` above): the core checks it is still that identity's.+ send: (connId, type, payload) => {+ // A subscription's answer leaves after the core knows to send its agent's tool events.+ reportStreams()+ core.wifi.send(connId, sessions.get(connId)!.identity, type, payload)+ },+ service, machineId,+ onReady: () => core.wifi.joined(),+ onRemoteRevoke: (identity) => core.wifi.unpaired(identity),+ onClient: (connId, identity) => core.wifi.hello(connId, identity),+ })+ function emit(frame: AutonomousDeviceFrame, deviceId?: string): void {+ // The revision a window's delayed selection is checked against, before anything that carries it.+ if (frame.kind === 'focus.changed') {+ const revision = (frame.payload as { focusRevision?: unknown } | undefined)?.focusRevision+ if (typeof revision === 'string') core.wifi.focus(revision)+ }+ relay.emit(frame, deviceId)+ }++ /** The window's focus moves in the order the windows moved it, each against the agents as they are. */+ let focusing: Promise<void> = Promise.resolve()++ const port: WifiPort = {+ session: (connId, client) => {+ if (client) sessions.set(connId, client)+ else sessions.delete(connId)+ },+ // Answered against the agents as they are now; taken (the relay opens it before its first wait) before+ // anything the core says after it, as it was in the core's process.+ request: async (connId, frame, opened) => {+ await refresh()+ // Answered on its own time; one that fails is that request's, said, and the next is answered.+ relay.handle(connId, frame, opened).catch((error: unknown) => {+ console.warn(`[wifi] a device's request failed · ${error instanceof Error ? error.message : String(error)}`)+ })+ },+ dropped: (connId) => relay.drop(connId),+ revoked: (identity) => relay.revoke(identity),+ resume: async ({ sessions: held, helloed, focus }) => {+ sessions.clear()+ for (const { connId, client } of held) sessions.set(connId, client)+ // A session this run served that the core no longer holds (the core restarted, and the relay with it).+ const kept = new Set(helloed.map(({ connId }) => connId))+ for (const connId of relay.helloed()) if (!kept.has(connId)) relay.drop(connId)+ // The core starts over from what this run follows (it has forgotten, or never knew).+ seen.clear()+ core.wifi.watching(service.transcriptWatches())+ streamed = service.streamedAgents().sort()+ core.wifi.streams(streamed)+ core.wifi.focus(service.focusSnapshot().focusRevision)+ if (focus) port.appFocus(focus.machineId, focus.agentId, focus.connId).catch(() => { /* said by the move itself */ })+ await refresh()+ for (const { connId, identity } of helloed) relay.restore(connId, identity)+ if (helloed.length) core.wifi.joined()+ core.wifi.ready()+ },+ card: (frame, text) => {+ fullText = text+ try { service.commander(frame) } finally { fullText = undefined }+ },+ turnStarted: (agentId) => service.turnStarted(agentId),+ turnEnded: (agentId, aborted) => service.turnEnded(agentId, aborted),+ stream: (agentId, events) => service.stream(agentId, events),+ transcript: (agentId, sessionId, engine, line) => {+ service.observeTranscript(agentId, sessionId, engine, line)+ reportTranscript(agentId)+ },+ delivery: (event) => service.delivery(event),+ dispatched: (agentId, deliveryId, text, sessionId) => {+ seen.set(agentId, (seen.get(agentId) ?? 0) + 1)+ service.inputDispatched(agentId, deliveryId, text, sessionId)+ reportTranscript(agentId)+ },+ inputStatus: (event) => service.inputStatus(event),+ agentGone: (agentId) => {+ service.agentGone(agentId)+ reportTranscript(agentId)+ },+ appFocus: (machineId, agentId, connId) => {+ const moved = focusing.then(refresh).then(() => service.appFocus(machineId, agentId, connId))+ // A move that fails is that move's: the next waits for it, not on it.+ focusing = moved.catch(() => {})+ return moved+ },+ revealed: (operationId, agentId) => store.acknowledgeReveal(operationId, agentId),+ receipt: async (deviceId, idempotencyKey) => ({ receipt: service.receipt(deviceId, idempotencyKey) }),+ stop: async () => store.stopUiDelivery(),+ }+ store.startUiDelivery()+ ports.wifi = port+}diff --git a/cli/src/services/wifiProcess.spec.ts b/cli/src/services/wifiProcess.spec.tsnew file mode 100644index 000000000..5a72943ac--- /dev/null+++ b/cli/src/services/wifiProcess.spec.ts@@ -0,0 +1,309 @@+// The Wi-Fi device in the devices' process (services/wifiProcess.ts): the core API it runs on across its link,+// built once the core names the machine, what the core tells it reaching its port in order, and the receipt+// the core asks of it.+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { CoreApi, CorePorts, WifiPort } from '../core/api.js'+import type { CoreConnection, ServiceProcessOptions } from './process.js'+import { runWifiService } from './wifiProcess.js'++// The real service and the real link, as a process started by the master runs them: stood in for here.+const real = vi.hoisted(() => ({ started: 0, options: null as ServiceProcessOptions | null }))+vi.mock('./wifi.js', () => ({ startWifi: () => { real.started++ } }))+vi.mock('./process.js', () => ({ runServiceProcess: (options: ServiceProcessOptions) => { real.options = options; return { stop: () => {} } } }))++/** A Wi-Fi port that records what reached it, in order. */+function wifiPort(machineId: string, log: string[]) {+ const record = (name: string) => (...args: unknown[]) => { log.push(`${machineId} ${name} ${JSON.stringify(args)}`) }+ const port: WifiPort = {+ session: record('session'), dropped: record('dropped'), revoked: record('revoked'), card: record('card'),+ turnStarted: record('turnStarted'), turnEnded: record('turnEnded'), stream: record('stream'), transcript: record('transcript'),+ delivery: record('delivery'), dispatched: record('dispatched'), inputStatus: record('inputStatus'), agentGone: record('agentGone'),+ revealed: record('revealed'),+ // A request is taken only once the agents are listed: what the core says after it waits.+ request: vi.fn(async (...args: unknown[]) => { await new Promise((resolve) => setTimeout(resolve, 5)); record('request')(...args) }),+ appFocus: vi.fn(async (...args: unknown[]) => { record('appFocus')(...args) }),+ resume: vi.fn(async (...args: unknown[]) => { record('resume')(...args) }),+ receipt: vi.fn(async () => ({ receipt: null })),+ stop: vi.fn(async () => { log.push(`${machineId} stop`) }),+ }+ return port+}++function setup(over: { startThrows?: boolean; leavesOff?: boolean } = {}) {+ const log: string[] = []+ const ports: WifiPort[] = []+ let api!: CoreApi+ const start = vi.fn((core: CoreApi, given: CorePorts) => {+ if (over.startThrows) throw new Error('journal unreadable')+ api = core+ if (over.leavesOff) return+ const port = wifiPort(core.machine.id(), log)+ ports.push(port)+ given.wifi = port+ })+ let options!: ServiceProcessOptions+ const stop = vi.fn()+ const run = vi.fn((given: ServiceProcessOptions) => { options = given; return { stop } })+ const service = runWifiService({ dataDir: '/data', socketPath: '/sock', machineId: 'computer-9', token: 't', start, run })+ const notices: Array<[string, Record<string, unknown> | undefined]> = []+ let answers: Record<string, unknown> = { machine: { id: 'machine-1' } }+ const connection: CoreConnection = {+ query: vi.fn(async (query: string) => {+ const answer = answers[query]+ if (answer instanceof Error) throw answer+ return (answer ?? {}) as Record<string, unknown>+ }),+ notice: (kind, payload) => { notices.push([kind, payload]) },+ }+ const settled = () => new Promise((resolve) => setTimeout(resolve, 30))+ return {+ service, start, log, ports, api: () => api, options: () => options, stop, notices, connection, settled,+ answer: (query: string, value: unknown) => { answers = { ...answers, [query]: value } },+ connect: () => options.onConnected!(connection),+ disconnect: () => options.onDisconnected!(),+ event: (payload: Record<string, unknown>) => options.onEvent!(payload),+ }+}++afterEach(() => vi.restoreAllMocks())++describe('the Wi-Fi device in the devices\' process', () => {+ it('runs on a link of its own, and builds its service once the core names the machine', async () => {+ const f = setup()+ expect(f.options()).toMatchObject({ name: 'wifi', socketPath: '/sock', machineId: 'computer-9', token: 't' })+ // Nothing the core says reaches a service that is not built yet.+ f.event({ kind: 'turnStarted', agentId: 'a' })+ f.connect()+ f.event({ kind: 'resume', sessions: [{ connId: 'c', client: { role: 'device' } }], helloed: 'nope', focus: { machineId: 'm', agentId: 'a', connId: 'w' } })+ await f.settled()+ expect(f.start).toHaveBeenCalledTimes(1)+ expect(f.api().machine.id()).toBe('machine-1')+ expect(f.api().machine.computerId()).toBe('computer-9')+ expect(f.api().machine.name()).toBe('')+ expect(f.log).toEqual([`machine-1 resume [{"sessions":[{"connId":"c","client":{"role":"device"}}],"helloed":[],"focus":{"machineId":"m","agentId":"a","connId":"w"}}]`])+ // The same machine on the next connection: the same service, resumed.+ f.event({ kind: 'resume' })+ await f.settled()+ expect(f.start).toHaveBeenCalledTimes(1)+ expect(f.log.at(-1)).toBe('machine-1 resume [{"sessions":[],"helloed":[],"focus":null}]')+ })++ it('waits for its link to open before it answers the core\'s resume, which comes a moment before', async () => {+ const f = setup()+ f.event({ kind: 'resume' })+ await f.settled()+ expect(f.start).not.toHaveBeenCalled()+ f.connect()+ await f.settled()+ expect(f.start).toHaveBeenCalledTimes(1)+ // Gone and back: the next resume waits for the next link.+ f.disconnect()+ f.event({ kind: 'resume' })+ await f.settled()+ expect(f.log.filter((line) => line.includes('resume'))).toHaveLength(1)+ f.connect()+ await f.settled()+ expect(f.log.filter((line) => line.includes('resume'))).toHaveLength(2)+ })++ it('builds it again for another machine, and stops the old one', async () => {+ const f = setup()+ f.connect()+ f.event({ kind: 'resume' })+ await f.settled()+ f.answer('machine', { id: 'machine-2' })+ f.event({ kind: 'resume' })+ await f.settled()+ expect(f.start).toHaveBeenCalledTimes(2)+ expect(f.log).toContain('machine-1 stop')+ expect(f.api().machine.id()).toBe('machine-2')+ })++ it('hands everything the core says to the service in the order it was said, a request taken before what follows it', async () => {+ const f = setup()+ f.connect()+ f.event({ kind: 'resume' })+ f.event({ kind: 'session', connId: 'c', client: { role: 'device', identity: 'i' } })+ f.event({ kind: 'session', connId: 'c', client: 'gone' })+ f.event({ kind: 'request', connId: 'c', frame: { type: 'autonomous_device_request' }, opened: { payload: { type: 'hello' } } })+ f.event({ kind: 'request', connId: 'c', frame: 'x', opened: 'y' })+ f.event({ kind: 'card', frame: { type: 'commander_event' }, fullText: 'whole' })+ f.event({ kind: 'card', frame: { type: 'commander_event' }, fullText: 3 })+ f.event({ kind: 'turnStarted', agentId: 'a' })+ f.event({ kind: 'turnEnded', agentId: 'a', aborted: true })+ f.event({ kind: 'turnEnded', agentId: 'a' })+ f.event({ kind: 'stream', agentId: 'a', events: [{ type: 'text_delta' }] })+ f.event({ kind: 'stream', agentId: 'a', events: 'none' })+ f.event({ kind: 'transcript', agentId: 'a', sessionId: 's', engine: 'claude', line: '{}' })+ f.event({ kind: 'delivery', event: { deliveryId: 'd' } })+ f.event({ kind: 'dispatched', agentId: 'a', deliveryId: 'd', text: 'hi', sessionId: 's' })+ f.event({ kind: 'dispatched', agentId: 'a', deliveryId: 'd', text: 'hi' })+ f.event({ kind: 'inputStatus', event: { deliveryId: 'd' } })+ f.event({ kind: 'agentGone', agentId: 'a' })+ f.event({ kind: 'appFocus', machineId: 'm', agentId: 'a', connId: 'w' })+ f.event({ kind: 'appFocus', machineId: 'm', agentId: null, connId: 'w' })+ f.event({ kind: 'revealed', operationId: 'op', agentId: 'a' })+ f.event({ kind: 'dropped', connId: 'c' })+ f.event({ kind: 'revoked', identity: 'i' })+ f.event({ kind: 'toString' })+ f.event({})+ await f.settled()+ expect(f.log.slice(1)).toEqual([+ 'machine-1 session ["c",{"role":"device","identity":"i"}]',+ 'machine-1 session ["c",null]',+ 'machine-1 request ["c",{"type":"autonomous_device_request"},{"payload":{"type":"hello"}}]',+ 'machine-1 request ["c",{},null]',+ 'machine-1 card [{"type":"commander_event"},"whole"]',+ 'machine-1 card [{"type":"commander_event"},null]',+ 'machine-1 turnStarted ["a"]',+ 'machine-1 turnEnded ["a",true]',+ 'machine-1 turnEnded ["a",false]',+ 'machine-1 stream ["a",[{"type":"text_delta"}]]',+ 'machine-1 stream ["a",[]]',+ 'machine-1 transcript ["a","s","claude","{}"]',+ 'machine-1 delivery [{"deliveryId":"d"}]',+ 'machine-1 dispatched ["a","d","hi","s"]',+ 'machine-1 dispatched ["a","d","hi",null]',+ 'machine-1 inputStatus [{"deliveryId":"d"}]',+ 'machine-1 agentGone ["a"]',+ 'machine-1 appFocus ["m","a","w"]',+ 'machine-1 appFocus ["m",null,"w"]',+ 'machine-1 revealed ["op","a"]',+ 'machine-1 dropped ["c"]',+ 'machine-1 revoked ["i"]',+ ])+ })++ it('reaches the core through its Wi-Fi doors: asked, or told', async () => {+ const f = setup()+ f.connect()+ f.event({ kind: 'resume' })+ await f.settled()+ const wifi = f.api().wifi+ f.answer('view', { agents: [{ agentId: 'a' }], store: 'no', hasWindow: true })+ expect(await wifi.view()).toEqual({ agents: [{ agentId: 'a' }], store: [], hasWindow: true })+ expect(wifi.scroll('move', 2, 3)).toBe(true)+ expect(wifi.focusApp('a', 9, 'r')).toBe(true)+ f.answer('view', {})+ await wifi.view()+ // Without a window in the view the request being answered asked for, nothing is sent to one.+ expect(wifi.scroll('down', 0, 0)).toBe(false)+ expect(wifi.focusApp('a', 9, 'r')).toBe(false)+ f.answer('recent', { turns: [{ recap: 'x' }] })+ expect(await f.api().turns.recent('a', 2)).toEqual([{ recap: 'x' }])+ f.answer('stop', { ok: true })+ expect(await wifi.stop('a')).toBe(true)+ f.answer('answer', { ok: 'yes' })+ expect(await wifi.answer('a', 'r', { q: '1' })).toBe(false)+ // The question's id under a name of its own: the link's query has a `requestId` of its own.+ expect(f.connection.query).toHaveBeenCalledWith('answer', { agentId: 'a', questionRequestId: 'r', answers: { q: '1' } })+ f.answer('create', { requestId: 'x', ok: true, agentId: 'made' })+ expect(await wifi.create('p', 'claude', '/w')).toEqual({ ok: true, agentId: 'made' })+ f.answer('stepFocus', { step: 'no_app' })+ expect(await wifi.stepFocus('next')).toBe('no_app')+ f.answer('stepFocus', { step: 'no_agents' })+ expect(await wifi.stepFocus('previous', 'a')).toBe('no_agents')+ f.answer('stepFocus', { machineId: 'm', agentId: 'b' })+ expect(await wifi.stepFocus('next', 'a')).toEqual({ machineId: 'm', agentId: 'b' })+ f.answer('stepFocus', { machineId: 7 })+ expect(await wifi.stepFocus('next')).toEqual({ machineId: '', agentId: '' })+ await wifi.submit('a', 'hi', 'd')+ expect(f.connection.query).toHaveBeenCalledWith('submit', { agentId: 'a', text: 'hi', deliveryId: 'd' })+ wifi.cancel('d')+ wifi.started('a', 'hi')+ wifi.reveal('op', 'a')+ wifi.send('c', 'i', 'autonomous_device_result', { ok: true })+ wifi.hello('c', 'i')+ wifi.joined()+ wifi.ready()+ wifi.unpaired('i')+ wifi.focus('r')+ wifi.transcripts('a', 1)+ wifi.watching(['a'])+ wifi.streams(['a'])+ expect(f.notices.map(([kind]) => kind)).toEqual(['scroll', 'focusApp', 'cancel', 'started', 'reveal', 'send', 'hello', 'joined',+ 'ready', 'unpaired', 'focus', 'transcripts', 'watching', 'streams'])+ expect(f.notices[0][1]).toEqual({ phase: 'move', dy: 2, velocity: 3 })+ expect(f.notices.find(([kind]) => kind === 'send')![1]).toEqual({ connId: 'c', identity: 'i', type: 'autonomous_device_result', payload: { ok: true } })+ // The core gone: asked, it says so; told, nothing goes.+ f.disconnect()+ await expect(wifi.stop('a')).rejects.toThrow('the Wi-Fi device is not connected to the core')+ wifi.joined()+ expect(f.notices).toHaveLength(14)+ })++ it('answers the core\'s receipt question once what it said before is heard, and says unavailable with no service', async () => {+ const f = setup()+ const receipt = f.options().requests!.receipt+ expect(await receipt({ deviceId: 'd', idempotencyKey: 'k' }, { local: false, owner: false })).toEqual({ error: 'SERVICE_UNAVAILABLE' })+ f.connect()+ f.event({ kind: 'resume' })+ expect(await receipt({ deviceId: 'd', idempotencyKey: 'k' }, { local: false, owner: false })).toEqual({ receipt: null })+ expect(f.ports[0].receipt).toHaveBeenCalledWith('d', 'k')+ })++ it('leaves the Wi-Fi device off when its service does not start, and says why', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const f = setup({ startThrows: true })+ f.connect()+ f.event({ kind: 'resume' })+ f.event({ kind: 'turnStarted', agentId: 'a' })+ await f.settled()+ expect(warn).toHaveBeenCalledWith('[wifi] did not start · journal unreadable')+ expect(await f.options().requests!.receipt({ deviceId: 'd', idempotencyKey: 'k' }, { local: false, owner: false })).toEqual({ error: 'SERVICE_UNAVAILABLE' })+ // A start that leaves its port empty is off too, and is tried again on the next connection.+ const g = setup({ leavesOff: true })+ g.connect()+ g.event({ kind: 'resume' })+ await g.settled()+ g.event({ kind: 'resume' })+ await g.settled()+ expect(g.start).toHaveBeenCalledTimes(2)+ // A start that throws something that is not an Error.+ const h = setup()+ h.start.mockImplementationOnce(() => { throw 'no' })+ h.connect()+ h.event({ kind: 'resume' })+ await h.settled()+ expect(warn).toHaveBeenCalledWith('[wifi] did not start · no')+ })++ it('logs what fails while it hears the core, and goes on with what follows', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const f = setup()+ f.connect()+ f.answer('machine', new Error('the core went away'))+ f.event({ kind: 'resume' })+ await f.settled()+ expect(warn).toHaveBeenCalledWith('[wifi] the core went away')+ f.answer('machine', { id: 'machine-1' })+ f.event({ kind: 'resume' })+ await f.settled()+ expect(f.start).toHaveBeenCalledTimes(1)+ vi.mocked(f.ports[0].appFocus).mockRejectedValueOnce('not an error')+ f.event({ kind: 'appFocus', machineId: 'm', agentId: 'a', connId: 'w' })+ f.event({ kind: 'turnStarted', agentId: 'a' })+ await f.settled()+ expect(warn).toHaveBeenCalledWith('[wifi] not an error')+ expect(f.log.at(-1)).toBe('machine-1 turnStarted ["a"]')+ })++ it('stops its link and its service', async () => {+ const f = setup()+ await f.service.stop()+ expect(f.stop).toHaveBeenCalled()+ f.connect()+ f.event({ kind: 'resume' })+ await f.settled()+ await f.service.stop()+ expect(f.log.at(-1)).toBe('machine-1 stop')+ })++ it('runs the real service and link by default', async () => {+ runWifiService({ dataDir: '/data', socketPath: '/sock', machineId: 'c', token: 't' })+ real.options!.onConnected!({ query: async () => ({ id: 'machine-1' }) })+ real.options!.onEvent!({ kind: 'resume' })+ await new Promise((resolve) => setTimeout(resolve, 10))+ expect(real.started).toBe(1)+ })+})diff --git a/cli/src/services/wifiProcess.ts b/cli/src/services/wifiProcess.tsnew file mode 100644index 000000000..da284813c--- /dev/null+++ b/cli/src/services/wifiProcess.ts@@ -0,0 +1,187 @@+/**+ * The Wi-Fi device's service in the devices' process (`harness __service devices,wifi`, harnessd/services.ts),+ * on a link of its own to the core (core/wifiLink.ts; step 9, D3). Its sessions are the gateway's, its+ * requests and every answer to them pass through the core, which checks where each answer goes.+ *+ * It is built on its first connection, once the core has said which machine this is (the account's id,+ * which every frame it sends a device carries), and built again if a later core says another: a sign-in+ * restarts the core, not this process. A core that restarts keeps the same service, which then serves+ * whichever devices the new core's gateway brings.+ */+import type { RecentTurn } from '../cable/cableHost.js'+import { emptyPorts, type CoreApi, type CorePorts, type ForkResult, type RemoteClient, type WifiPort, type WifiResume, type WifiView } from '../core/api.js'+import type { AutonomousDeviceDelivery } from '../lib/autonomous-device/service.js'+import type { LiveEvent } from '../lib/normalize.js'+import { runServiceProcess, type CoreConnection, type ServiceProcess, type ServiceProcessOptions } from './process.js'+import { processCoreApi } from './processCoreApi.js'+import { startWifi } from './wifi.js'++export interface WifiServiceOptions {+ dataDir: string+ socketPath: string+ machineId: string+ token: string+ /** For this service's tests: its start and its link. */+ start?: typeof startWifi+ run?: (options: ServiceProcessOptions) => ServiceProcess+}++const text = (value: unknown): string => (typeof value === 'string' ? value : '')+const object = (value: unknown): Record<string, unknown> => (value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {})+const list = <T>(value: unknown): T[] => (Array.isArray(value) ? value as T[] : [])++export function runWifiService(options: WifiServiceOptions): ServiceProcess {+ let core: CoreConnection | null = null+ /** The core says `resume` as it takes the link, a moment before it says the link is open: what answers it+ * asks the core, and so waits for that (found end to end: the ask failed, and the service never built). */+ let linked!: () => void+ let link = new Promise<void>((resolve) => { linked = resolve })+ let built: { machineId: string; port: WifiPort } | null = null+ /** What the core last listed: whether a window is there to show the device's choice. */+ let lastView: WifiView = { agents: [], store: [], hasWindow: false }++ const ask = async (query: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> => {+ if (!core) throw new Error('the Wi-Fi device is not connected to the core')+ return core.query(query, payload)+ }+ const tell = (kind: string, payload: Record<string, unknown> = {}): void => { core?.notice?.(kind, payload) }++ const api = (machineId: string): CoreApi => {+ const unasked = processCoreApi(options.dataDir, 'wifi')+ return {+ ...unasked,+ machine: { id: () => machineId, computerId: () => options.machineId, name: () => '' },+ turns: { ...unasked.turns, recent: async (agentId, n) => list<RecentTurn>((await ask('recent', { agentId, n })).turns) },+ wifi: {+ view: async () => {+ const answer = await ask('view')+ lastView = { agents: list(answer.agents), store: list(answer.store), hasWindow: answer.hasWindow === true }+ return lastView+ },+ submit: async (agentId, said, deliveryId) => { await ask('submit', { agentId, text: said, deliveryId }) },+ cancel: (deliveryId) => tell('cancel', { deliveryId }),+ started: (agentId, said) => tell('started', { agentId, text: said }),+ stop: async (agentId) => (await ask('stop', { agentId })).ok === true,+ // Not `requestId`: the link's query carries its own under that name.+ answer: async (agentId, questionRequestId, answers) => (await ask('answer', { agentId, questionRequestId, answers })).ok === true,+ create: async (packageId, engine, cwd) => {+ const { requestId: _id, ...result } = await ask('create', { packageId, engine, cwd })+ return result as unknown as ForkResult+ },+ stepFocus: async (direction, currentAgentId) => {+ const answer = await ask('stepFocus', { direction, ...(currentAgentId ? { currentAgentId } : {}) })+ if (answer.step === 'no_agents' || answer.step === 'no_app') return answer.step+ return { machineId: text(answer.machineId), agentId: text(answer.agentId) }+ },+ // Read against the view the request being answered just asked for, as the core read its own sockets.+ scroll: (phase, dy, velocity) => {+ if (!lastView.hasWindow) return false+ tell('scroll', { phase, dy, velocity })+ return true+ },+ focusApp: (agentId, expiresAt, focusRevision) => {+ if (!lastView.hasWindow) return false+ tell('focusApp', { agentId, expiresAt, focusRevision })+ return true+ },+ reveal: (operationId, agentId) => tell('reveal', { operationId, agentId }),+ send: (connId, identity, type, payload) => tell('send', { connId, identity, type, payload }),+ hello: (connId, identity) => tell('hello', { connId, identity }),+ joined: () => tell('joined'),+ ready: () => tell('ready'),+ unpaired: (identity) => tell('unpaired', { identity }),+ focus: (revision) => tell('focus', { revision }),+ transcripts: (agentId, seen) => tell('transcripts', { agentId, seen }),+ watching: (agentIds) => tell('watching', { agentIds }),+ streams: (agentIds) => tell('streams', { agentIds }),+ },+ }+ }++ /** The service for this machine, built (again) when the core names another. */+ const build = (machineId: string): WifiPort | null => {+ if (built?.machineId === machineId) return built.port+ if (built) void built.port.stop()+ built = null+ const ports: CorePorts = emptyPorts()+ try {+ ;(options.start ?? startWifi)(api(machineId), ports)+ } catch (error) {+ console.warn(`[wifi] did not start · ${error instanceof Error ? error.message : String(error)}`)+ return null+ }+ built = ports.wifi ? { machineId, port: ports.wifi } : null+ return built?.port ?? null+ }++ /** What the core tells the service (`service_event`), by kind: the port's own calls, across the link. */+ const heard: Record<string, (port: WifiPort, payload: Record<string, unknown>) => unknown> = {+ session: (port, { connId, client }) => port.session(text(connId), client && typeof client === 'object' ? client as RemoteClient : null),+ request: (port, { connId, frame, opened }) => port.request(text(connId), object(frame), opened && typeof opened === 'object' ? opened as Record<string, unknown> : null),+ dropped: (port, { connId }) => port.dropped(text(connId)),+ revoked: (port, { identity }) => port.revoked(text(identity)),+ card: (port, { frame, fullText }) => port.card(object(frame), typeof fullText === 'string' ? fullText : undefined),+ turnStarted: (port, { agentId }) => port.turnStarted(text(agentId)),+ turnEnded: (port, { agentId, aborted }) => port.turnEnded(text(agentId), aborted === true),+ stream: (port, { agentId, events }) => port.stream(text(agentId), list<LiveEvent>(events)),+ transcript: (port, { agentId, sessionId, engine, line }) => port.transcript(text(agentId), text(sessionId), text(engine), text(line)),+ delivery: (port, { event }) => port.delivery(object(event) as unknown as AutonomousDeviceDelivery),+ dispatched: (port, { agentId, deliveryId, text: said, sessionId }) =>+ port.dispatched(text(agentId), text(deliveryId), text(said), typeof sessionId === 'string' ? sessionId : undefined),+ inputStatus: (port, { event }) => port.inputStatus(object(event) as unknown as Parameters<WifiPort['inputStatus']>[0]),+ agentGone: (port, { agentId }) => port.agentGone(text(agentId)),+ appFocus: (port, { machineId, agentId, connId }) => port.appFocus(text(machineId), typeof agentId === 'string' ? agentId : null, text(connId)),+ revealed: (port, { operationId, agentId }) => port.revealed(text(operationId), text(agentId)),+ }++ /** Everything the core says, in the order it said it: a request is taken, the window's focus applied+ * and the service resumed (each against the agents as the core lists them then) before what came after. */+ let heardSoFar: Promise<unknown> = Promise.resolve()+ const inOrder = (run: () => unknown): void => {+ heardSoFar = heardSoFar.then(run).catch((error: unknown) => console.warn(`[wifi] ${error instanceof Error ? error.message : String(error)}`))+ }+ /** The core's first word on each connection: which machine this is, then what it holds for the service. */+ const connected = async (state: Record<string, unknown>): Promise<void> => {+ await link+ const machine = await ask('machine')+ const port = build(text(machine.id))+ await port?.resume({+ sessions: list<WifiResume['sessions'][number]>(state.sessions),+ helloed: list<WifiResume['helloed'][number]>(state.helloed),+ focus: state.focus && typeof state.focus === 'object' ? state.focus as WifiResume['focus'] : null,+ })+ }++ const service = (options.run ?? runServiceProcess)({+ name: 'wifi',+ socketPath: options.socketPath,+ machineId: options.machineId,+ token: options.token,+ requests: {+ // `harness device receipt`, asked by the core (core/wifiLink.ts) under a type only the core sends.+ receipt: async ({ deviceId, idempotencyKey }) => {+ await heardSoFar+ if (!built) return { error: 'SERVICE_UNAVAILABLE' }+ return { ...await built.port.receipt(text(deviceId), text(idempotencyKey)) }+ },+ },+ onEvent: (payload) => {+ const kind = text(payload.kind)+ if (kind === 'resume') { inOrder(() => connected(payload)); return }+ if (!Object.hasOwn(heard, kind)) return+ inOrder(() => (built ? heard[kind](built.port, payload) : undefined))+ },+ onConnected: (connection) => { core = connection; linked() },+ onDisconnected: () => {+ core = null+ link = new Promise<void>((resolve) => { linked = resolve })+ },+ })+ return {+ stop: async () => {+ service.stop()+ await built?.port.stop()+ },+ }+}+diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.tsindex 80c59cedd..1ad864f09 100644--- a/cli/src/services/workspacesProcess.ts+++ b/cli/src/services/workspacesProcess.ts@@ -87,6 +87,7 @@ export function workspacesCoreApi(},clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false, ...UNASKED.clients },daemon: DAEMON_UNKNOWN,+ wifi: UNASKED.wifi,}}diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.tsindex 56e7260b0..57b825cd3 100644--- a/cli/src/testing/fakeCore.ts+++ b/cli/src/testing/fakeCore.ts@@ -74,5 +74,15 @@ export function fakeCore(over: Overrides = {}): CoreApi {...over.clients,},daemon: { command: 'harness', port: 18473, machineId: () => 'machine-1', autonomousEnv: 'prod', ...over.daemon },+ wifi: {+ view: vi.fn(async () => ({ agents: [], store: [], hasWindow: true })),+ submit: vi.fn(async () => {}), cancel: vi.fn(), started: vi.fn(),+ stop: vi.fn(async () => true), answer: vi.fn(async () => true),+ create: vi.fn(async () => ({ ok: false as const, error: 'UNSUPPORTED' })),+ stepFocus: vi.fn(async () => 'no_agents' as const), scroll: vi.fn(() => true), focusApp: vi.fn(() => true), reveal: vi.fn(),+ send: vi.fn(), hello: vi.fn(), joined: vi.fn(), ready: vi.fn(), unpaired: vi.fn(), focus: vi.fn(),+ transcripts: vi.fn(), watching: vi.fn(), streams: vi.fn(),+ ...over.wifi,+ },}}diff --git a/cli/src/testing/teamFixture.ts b/cli/src/testing/teamFixture.tsindex 69e129022..a70e837c3 100644--- a/cli/src/testing/teamFixture.ts+++ b/cli/src/testing/teamFixture.ts@@ -77,6 +77,7 @@ export function attachTeams<T extends BackendSocket>(socket: T): T & TeamFixture...UNASKED.clients,},daemon: { command: 'harness', port: env.PORT, machineId: () => socket.machineId, autonomousEnv: 'prod' },+ wifi: UNASKED.wifi,})/** Built at its first use, from what the spec set by then. */const collaboration = (): Teams => teams ??= startCollaboration(core(), {diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex db62655ea..65abfa591 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -294,7 +294,22 @@ The steps, each a pull request with its end-to-end proof:same handlers answer. A crash in the native serial code then costs the dial alone, and the masterstarts it again. It is proven end to end with a fake dial on a pseudo-terminal, speaking the cableprotocol (the fake dial and the two-machine fleet from D0's proof are there to reuse).-- **D3, the Wi-Fi device**, with the relay.+- **D3, the Wi-Fi device, with the dials (done, 6 October).** Its service, its relay, its receipts and+ streams and its Store preparations run beside the dials in the devices' process, on a link of their own+ (services/wifi.ts, services/wifiProcess.ts; the core's side is core/wifi.ts and core/wifiLink.ts). Its+ sessions stay the gateway's (step 10): the core hands their requests on, in order, and seals each answer+ to the session it came from only while that session is still the identity's device. What the core reads+ of it in line is kept in the core from what the service tells it: which devices said hello (presence),+ which agents' transcripts and tool events it follows (only those are sent across, and an agent's lines+ from the moment the core types the device's prompt), and the focus revision a window's late selection is+ checked against. What it reads of the core in line (the agents with the Store's evidence on them,+ whether a window is there) is asked before each request and each move of the window's focus. A prompt+ is asked, not told, so the reply carries what the pane's lock said of it as it took it, as before; the+ Store's agent is made by the core, with the device's fixed launch arguments. Its process restarting is+ its devices' too: the gateway keeps their sessions, the core hands them back, and each is told to+ resync (the documented way back after a daemon restart) and served on without a new hello; its receipts+ are in its journal. Proven by e2e/wifiDevice.e2e.ts (a fake device through the fake relay, beside two+ fake dials) and by e2e/deviceCompat.e2e.ts, which hears the same answers and events from main's build.### Models