Skip to content

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.

Record agent creation outcomes for safe recovery

dee3585051ec175
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 331d5ff3f..206578a05 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -7,6 +7,7 @@ import type { TerminalStreamManager } from './lib/terminalStreamManager.js'
import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.js'
import { registry, type RegisteredSession } from './lib/registry.js'
import * as mediaPreview from './lib/mediaPreview.js'
+import { randomUUID } from 'node:crypto'
const wsMock = vi.hoisted(() => {
const instances: MockWebSocket[] = []
@@ -544,6 +545,126 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('recovers a delayed creation on the same connection without starting another agent', async () => {
+ const socket = new BackendSocket('token')
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:receipt', {
+ sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,
+ })
+ const pending: RegisteredSession = {
+ schemaVersion: 2, active: true, launch: { state: 'starting' },
+ agentId: 'receipt-agent', sessionId: '', boundAt: null, engine: 'claude',
+ transcriptPath: null, projectDir: 'work', cwd: '/tmp/work',
+ runtimes: [{ backend: 'tmux', paneId: '%receipt' }], primaryRuntimeKey: 'tmux/%receipt', tmuxPane: '%receipt',
+ source: null, title: null, model: null, cliVersion: null, processIdentity: null,
+ registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1,
+ }
+ const lookup = vi.spyOn(registry, 'byAgent').mockReturnValue(pending)
+ let finish!: () => void
+ const create = vi.fn(() => new Promise<{ ok: true; session: RegisteredSession }>((resolve) => {
+ finish = () => resolve({ ok: true, session: pending })
+ }))
+ socket.onCreateAgent = create
+ const creationId = randomUUID()
+ const ask = (type: string, requestId: string, choices = {}) => socket.handleLocalFrame('local:receipt', {
+ type, payload: { requestId, creationId, ...choices },
+ })
+ try {
+ ask('agent_create', 'first', { engine: 'claude', cwd: '/tmp/work' })
+ await vi.waitFor(() => expect(create).toHaveBeenCalledTimes(1))
+ ask('agent_create_status', 'while-pending')
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'agent_create_status_result', payload: { requestId: 'while-pending', creationId, state: 'pending' },
+ }))
+ // New transport request id, same deliberate creation intent.
+ ask('agent_create', 'retry', { engine: 'claude', cwd: '/tmp/work' })
+ finish()
+ for (const requestId of ['first', 'retry']) {
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({
+ type: 'agent_create_result', payload: expect.objectContaining({ requestId, creationId, state: 'created', agent: expect.objectContaining({ id: pending.agentId }) }),
+ })))
+ }
+ expect(create).toHaveBeenCalledTimes(1)
+ ask('agent_create_status', 'recovered')
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({
+ type: 'agent_create_status_result', payload: expect.objectContaining({ requestId: 'recovered', creationId, state: 'created', agent: expect.objectContaining({ id: pending.agentId }) }),
+ })))
+ ask('agent_create', 'changed', { engine: 'codex', cwd: '/tmp/work' })
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({
+ type: 'agent_create_result', payload: expect.objectContaining({ requestId: 'changed', error: 'CREATION_CONFLICT' }),
+ })))
+ lookup.mockReturnValue(undefined)
+ ask('agent_create', 'deleted', { engine: 'claude', cwd: '/tmp/work' })
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({
+ type: 'agent_create_result', payload: expect.objectContaining({ requestId: 'deleted', creationId, state: 'unavailable' }),
+ })))
+ expect(create).toHaveBeenCalledTimes(1)
+ } finally {
+ finish?.()
+ await socket.unregisterLocalClient('local:receipt')
+ await socket.stop()
+ }
+ })
+
+ it('checks an unknown creation without spawning and rejects malformed creation ids before launch', async () => {
+ const socket = new BackendSocket('token')
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:missing-receipt', {
+ sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,
+ })
+ const create = vi.fn(async () => ({ ok: false as const, error: 'CWD_NOT_FOUND' }))
+ socket.onCreateAgent = create
+ const creationId = randomUUID()
+ try {
+ socket.handleLocalFrame('local:missing-receipt', {
+ type: 'agent_create_status', payload: { requestId: 'missing', creationId },
+ })
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'agent_create_status_result', payload: { requestId: 'missing', creationId, state: 'missing' },
+ }))
+ socket.handleLocalFrame('local:missing-receipt', {
+ type: 'agent_create', payload: { requestId: 'invalid', creationId: '../bad', engine: 'claude', cwd: '/tmp/work' },
+ })
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({
+ type: 'agent_create_result', payload: expect.objectContaining({ requestId: 'invalid', error: 'INVALID_CREATION_ID' }),
+ })))
+ expect(create).not.toHaveBeenCalled()
+ } finally {
+ await socket.unregisterLocalClient('local:missing-receipt')
+ await socket.stop()
+ }
+ })
+
+ it.each([
+ ['CWD_NOT_FOUND', 'failed'],
+ ['SPAWN_FAILED', 'unconfirmed'],
+ ['REGISTRATION_FAILED', 'unconfirmed'],
+ ])('does not relaunch a recorded %s outcome', async (error, state) => {
+ const socket = new BackendSocket('token')
+ const frames: Array<Record<string, unknown>> = []
+ socket.registerLocalClient('local:refusal', {
+ sendFrame: (frame) => { frames.push(frame); return true }, sendBinary: () => true,
+ })
+ const create = vi.fn(async () => ({ ok: false as const, error }))
+ socket.onCreateAgent = create
+ const creationId = randomUUID()
+ try {
+ for (const requestId of ['initial', 'retry']) {
+ socket.handleLocalFrame('local:refusal', {
+ type: 'agent_create', payload: { requestId, creationId, engine: 'claude', cwd: '/tmp/work' },
+ })
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'agent_create_result',
+ payload: { requestId, creationId, state, ...(state === 'failed' ? { failure: { code: error } } : {}) },
+ }))
+ }
+ expect(create).toHaveBeenCalledTimes(1)
+ } finally {
+ await socket.unregisterLocalClient('local:refusal')
+ await socket.stop()
+ }
+ })
+
it('sends a device focus request to one desktop window only', async () => {
const socket = new BackendSocket('token')
const first = vi.fn(() => true), second = vi.fn(() => true)
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index de339e6e0..59946e6bb 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -30,6 +30,7 @@ import { linkCodexProfile, listCodexProfiles } from './lib/codexProfiles.js'
import { parseGridLaunchOverride, type GridLaunchOverride } from './lib/gridLaunch.js'
import { readAccountUsage, type AccountUsageReading } from './lib/accountUsage.js'
import { probeEngines } from './lib/engineProbe.js'
+import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationStatus } from './lib/agentCreationReceipt.js'
import { engineInstallRecipe } from './lib/engineInstall.js'
import { agentFrame, type AgentFrame } from './lib/agentFrame.js'
import { routeVoiceTask } from './lib/voiceRouter.js'
@@ -329,6 +330,7 @@ export class BackendSocket {
codexHome: string | null
}) =>
Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null
+ 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
/**
@@ -1539,12 +1541,27 @@ export class BackendSocket {
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' })
+ }
+ return
+ }
+
case 'agent_create': {
const engine = payload.engine as AgentEngine | undefined
- const cwd = payload.cwd as string | undefined
- if (!engine || !ENGINES.includes(engine)) { reply(type, requestId, { error: 'INVALID_ENGINE' }); return }
- if (!cwd || !isAbsolute(cwd)) { reply(type, requestId, { error: 'INVALID_CWD' }); return }
+ const cwd = payload.cwd
+ if (typeof engine !== 'string' || !ENGINES.includes(engine)) { reply(type, requestId, { error: 'INVALID_ENGINE' }); return }
+ if (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
+ }
// 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.
@@ -1562,13 +1579,36 @@ export class BackendSocket {
reply(type, requestId, { error: 'INVALID_CODEX_HOME', detail: 'codexHome is only valid for codex, without a grid' })
return
}
- const result = await this.onCreateAgent({
+ const input = {
engine,
cwd,
bypassPermission: payload.bypassPermission === true,
grid: grid.state === 'ok' ? grid.override : null,
codexHome,
- })
+ }
+ 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(input), async () => {
+ const result = await create(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, ...(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.
+ 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) {
@@ -1777,6 +1817,22 @@ 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) }
+ : { 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', failure: { code: status.error, ...(status.detail ? { detail: status.detail } : {}) } }
+ }
+ return status
+ }
+
/** Map a registered tmux session onto the web's Project shape (tabs in ProjectTabs). */
private toProject(s: RegisteredSession): Promise<AgentFrame> {
return agentFrame(s, {
diff --git a/cli/src/lib/agentCreationReceipt.spec.ts b/cli/src/lib/agentCreationReceipt.spec.ts
new file mode 100644
index 000000000..9e2344cfc
--- /dev/null
+++ b/cli/src/lib/agentCreationReceipt.spec.ts
@@ -0,0 +1,99 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { AgentCreationReceipts, creationFingerprint, type AgentCreationOutcome } from './agentCreationReceipt.js'
+
+const roots: string[] = []
+function fixture() {
+ const root = mkdtempSync(join(tmpdir(), 'harness-create-receipt-'))
+ roots.push(root)
+ const directory = join(root, 'receipts')
+ return { root, directory, receipts: new AgentCreationReceipts(directory) }
+}
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+const id = 'creation-intent-0001'
+const fingerprint = creationFingerprint({ engine: 'claude', cwd: '/work', bypassPermission: false })
+
+describe('agent creation receipts', () => {
+ it('shares an in-flight launch and recovers its result after a lost reply and daemon restart', async () => {
+ const { directory, receipts } = fixture()
+ let finish!: (outcome: AgentCreationOutcome) => void
+ const create = vi.fn(() => new Promise<AgentCreationOutcome>((resolve) => { finish = resolve }))
+ const first = receipts.run(id, fingerprint, create)
+ const retry = receipts.run(id, fingerprint, create)
+ await Promise.resolve()
+ expect(create).toHaveBeenCalledTimes(1)
+ expect(receipts.status(id)).toEqual({ state: 'pending' })
+ // A second daemon cannot claim a reservation whose result is still unknown.
+ const other = new AgentCreationReceipts(directory)
+ expect(await other.run(id, fingerprint, create)).toEqual({ state: 'unconfirmed' })
+ finish({ state: 'created', agentId: 'agent-1' })
+ expect(await first).toEqual({ state: 'created', agentId: 'agent-1' })
+ expect(await retry).toEqual(await first)
+ expect(await new AgentCreationReceipts(directory).run(id, fingerprint, create)).toEqual(await first)
+ expect(create).toHaveBeenCalledTimes(1)
+ })
+
+ it('refuses changed settings on the same intent, but permits an explicit fresh intent', async () => {
+ const { receipts } = fixture()
+ const create = vi.fn(async () => ({ state: 'created' as const, agentId: 'agent-1' }))
+ const first = receipts.run(id, fingerprint, create)
+ const changed = creationFingerprint({ engine: 'codex', cwd: '/work' })
+ expect(() => receipts.run(id, changed, create)).toThrow('CREATION_CONFLICT')
+ await first
+ expect(() => receipts.run(id, changed, create)).toThrow('CREATION_CONFLICT')
+ await receipts.run('creation-intent-0002', changed, create)
+ expect(create).toHaveBeenCalledTimes(2)
+ })
+
+ it('remembers known failures and refuses to retry an ambiguous exception', async () => {
+ const { directory, receipts } = fixture()
+ const refused = vi.fn(async () => ({ state: 'failed' as const, error: 'CWD_NOT_FOUND' }))
+ await receipts.run(id, fingerprint, refused)
+ expect(await new AgentCreationReceipts(directory).run(id, fingerprint, refused)).toEqual({ state: 'failed', error: 'CWD_NOT_FOUND' })
+ expect(refused).toHaveBeenCalledTimes(1)
+ const crashed = vi.fn(async () => { throw new Error('connection lost after spawn') })
+ expect(await receipts.run('creation-intent-0002', fingerprint, crashed)).toEqual({ state: 'unconfirmed' })
+ expect(await new AgentCreationReceipts(directory).run('creation-intent-0002', fingerprint, crashed)).toEqual({ state: 'unconfirmed' })
+ expect(crashed).toHaveBeenCalledTimes(1)
+ })
+
+ it('retains the result in memory if completion cannot be saved, with a fail-closed reservation after restart', async () => {
+ const { root, directory, receipts } = fixture()
+ const moved = join(root, 'unavailable-disk')
+ const create = vi.fn(async () => {
+ renameSync(directory, moved)
+ return { state: 'created' as const, agentId: 'agent-1' }
+ })
+ await receipts.run(id, fingerprint, create)
+ expect(receipts.status(id)).toEqual({ state: 'created', agentId: 'agent-1' })
+ renameSync(moved, directory)
+ expect(await new AgentCreationReceipts(directory).run(id, fingerprint, create)).toEqual({ state: 'unconfirmed' })
+ expect(create).toHaveBeenCalledTimes(1)
+ })
+
+ it('distinguishes missing from corrupt receipts and never launches without a valid reservation', async () => {
+ const { directory, receipts } = fixture()
+ const create = vi.fn(async () => ({ state: 'created' as const, agentId: 'agent-1' }))
+ expect(receipts.status(id)).toEqual({ state: 'missing' })
+ writeFileSync(join(directory, `${id}.json`), '{partial', { mode: 0o600 })
+ expect(() => receipts.run(id, fingerprint, create)).toThrow('CREATION_STORAGE_FAILED')
+ expect(() => receipts.run('../invalid-id', fingerprint, create)).toThrow('INVALID_CREATION_ID')
+ expect(create).not.toHaveBeenCalled()
+ })
+
+ it('keeps launch settings out of private receipts and canonicalizes equivalent requests', async () => {
+ const { directory, receipts } = fixture()
+ const launch = { cwd: '/private/work', grid: { token: 'fixture-secret', url: 'https://example.invalid' } }
+ const reordered = { grid: { url: 'https://example.invalid', token: 'fixture-secret' }, cwd: '/private/work' }
+ expect(creationFingerprint(launch)).toEqual(creationFingerprint(reordered))
+ await receipts.run(id, creationFingerprint(launch), async () => ({ state: 'created', agentId: 'agent-1' }))
+ const file = join(directory, `${id}.json`)
+ const text = readFileSync(file, 'utf8')
+ expect(text).not.toContain('fixture-secret')
+ expect(text).not.toContain('/private/work')
+ expect(statSync(directory).mode & 0o777).toBe(0o700)
+ expect(statSync(file).mode & 0o777).toBe(0o600)
+ })
+})
diff --git a/cli/src/lib/agentCreationReceipt.ts b/cli/src/lib/agentCreationReceipt.ts
new file mode 100644
index 000000000..ebde79314
--- /dev/null
+++ b/cli/src/lib/agentCreationReceipt.ts
@@ -0,0 +1,147 @@
+import { createHash, randomUUID } from 'node:crypto'
+import { closeSync, constants, fsyncSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { readPrivateStateFile, secureStateDirectory } from './secureState.js'
+
+export type AgentCreationOutcome =
+ | { state: 'created'; agentId: string }
+ | { state: 'failed'; error: string; detail?: string }
+ | { state: 'unconfirmed' }
+
+export type AgentCreationStatus = AgentCreationOutcome
+ | { state: 'pending' | 'missing' }
+
+type Receipt = {
+ version: 1
+ fingerprint: string
+ outcome: AgentCreationOutcome | { state: 'pending' }
+}
+
+export class AgentCreationReceiptError extends Error {
+ constructor(readonly code: 'INVALID_CREATION_ID' | 'CREATION_CONFLICT' | 'CREATION_STORAGE_FAILED') {
+ super(code)
+ }
+}
+
+export function validCreationId(value: unknown): value is string {
+ return typeof value === 'string' && /^[a-zA-Z0-9_-]{16,96}$/.test(value)
+}
+
+/** Only a hash is retained: launch credentials and folder/profile choices do not
+ * become a second copy of the launch configuration in the receipt directory. */
+export function creationFingerprint(value: unknown): string {
+ const canonical = (item: unknown): unknown => Array.isArray(item)
+ ? item.map(canonical)
+ : item && typeof item === 'object'
+ ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, child]) => [key, canonical(child)]))
+ : item
+ return createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex')
+}
+
+/**
+ * Reserve an intent before starting its process. A lost reply, reconnect, or
+ * daemon restart never turns that same intent into another process launch.
+ *
+ * Pending receipts survive crashes. If the daemon stopped between starting a
+ * process and saving its result, its outcome is unconfirmed; we never guess
+ * that nothing started and run the operation again. Receipts are not evicted by
+ * age: even an old retry must not silently become a fresh launch.
+ */
+export class AgentCreationReceipts {
+ private readonly inFlight = new Map<string, { fingerprint: string; result: Promise<AgentCreationStatus> }>()
+ // A failed outcome write must not forget an agent we already know was created.
+ // The on-disk reservation still prevents a duplicate after a later restart.
+ private readonly unsaved = new Map<string, Receipt>()
+
+ constructor(private readonly directory: string) {}
+
+ status(id: string): AgentCreationStatus {
+ const receipt = this.read(id)
+ if (!receipt) return { state: 'missing' }
+ return receipt.outcome.state === 'pending' && !this.inFlight.has(id)
+ ? { state: 'unconfirmed' }
+ : receipt.outcome
+ }
+
+ run(id: string, fingerprint: string, create: () => Promise<AgentCreationOutcome>): Promise<AgentCreationStatus> {
+ const running = this.inFlight.get(id)
+ if (running) {
+ if (running.fingerprint !== fingerprint) throw new AgentCreationReceiptError('CREATION_CONFLICT')
+ return running.result
+ }
+ const receipt = this.read(id)
+ if (receipt) {
+ if (receipt.fingerprint !== fingerprint) throw new AgentCreationReceiptError('CREATION_CONFLICT')
+ return Promise.resolve(this.status(id))
+ }
+ // O_EXCL is also the guard against another daemon reaching the same intent.
+ // A partial/corrupt reservation is refused, never treated as a missing one.
+ try {
+ this.write(id, { version: 1, fingerprint, outcome: { state: 'pending' } }, true)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
+ const existing = this.read(id)
+ if (existing?.fingerprint !== fingerprint) throw new AgentCreationReceiptError('CREATION_CONFLICT')
+ return Promise.resolve(this.status(id))
+ }
+ throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')
+ }
+ const result = Promise.resolve().then(async (): Promise<AgentCreationStatus> => {
+ let outcome: AgentCreationOutcome
+ try { outcome = await create() }
+ catch { outcome = { state: 'unconfirmed' } }
+ const completed: Receipt = { version: 1, fingerprint, outcome }
+ try { this.write(id, completed, false) }
+ catch { this.unsaved.set(id, completed) }
+ return outcome
+ }).finally(() => { this.inFlight.delete(id) })
+ this.inFlight.set(id, { fingerprint, result })
+ return result
+ }
+
+ private file(id: string): string {
+ if (!validCreationId(id)) throw new AgentCreationReceiptError('INVALID_CREATION_ID')
+ return join(this.directory, `${id}.json`)
+ }
+
+ private read(id: string): Receipt | null {
+ const file = this.file(id)
+ const unsaved = this.unsaved.get(id)
+ if (unsaved) return unsaved
+ try { secureStateDirectory(this.directory) }
+ catch { throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED') }
+ try {
+ const value = JSON.parse(readPrivateStateFile(file, 16_384)) as Partial<Receipt>
+ const outcome = value.outcome
+ if (value.version !== 1 || !/^[a-f0-9]{64}$/.test(value.fingerprint ?? '') || !outcome ||
+ !['pending', 'unconfirmed', 'created', 'failed'].includes(outcome.state) ||
+ (outcome.state === 'created' && (typeof outcome.agentId !== 'string' || !outcome.agentId)) ||
+ (outcome.state === 'failed' && typeof outcome.error !== 'string')) {
+ throw new Error('Invalid creation receipt')
+ }
+ return value as Receipt
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')
+ }
+ }
+
+ private write(id: string, receipt: Receipt, exclusive: boolean): void {
+ const file = this.file(id)
+ const writing = exclusive ? file : `${file}.${process.pid}.${randomUUID()}.tmp`
+ let opened = false
+ try {
+ const fd = openSync(writing, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ opened = true
+ try { writeFileSync(fd, JSON.stringify(receipt)); fsyncSync(fd) }
+ finally { closeSync(fd) }
+ if (!exclusive) renameSync(writing, file)
+ const directoryFd = openSync(dirname(file), constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
+ try { fsyncSync(directoryFd) } finally { closeSync(directoryFd) }
+ } finally {
+ // Failed reservations stay on disk so a partial write cannot permit a
+ // duplicate. Only this write's private replacement file is disposable.
+ if (!exclusive && opened) rmSync(writing, { force: true })
+ }
+ }
+}
diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.ts
index 3450c5cc8..ec4b30003 100644
--- a/cli/src/lib/e2ee/core.test.ts
+++ b/cli/src/lib/e2ee/core.test.ts
@@ -132,6 +132,8 @@ describe('e2ee core — codes + fingerprint + classification', () => {
expect(C.isEncryptedUpType('node_status')).toBe(false)
expect(C.isEncryptedDownType('agents_list')).toBe(true)
expect(C.isEncryptedDownType('agent_update')).toBe(true)
+ expect(C.isEncryptedDownType('agent_create_status')).toBe(true)
+ expect(C.isEncryptedRpcResultType('agent_create_status_result')).toBe(true)
// A machine's account usage names what the person spends and on whose subscription. Missing from
// either list the request would not fail — it would time out, which is harder to find.
expect(C.isEncryptedDownType('usage_read')).toBe(true)
@@ -201,6 +203,6 @@ describe('e2ee core — interop keystone', () => {
it('core.ts still hashes to the pinned value shared with the other implementations', () => {
const here = dirname(fileURLToPath(import.meta.url))
const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')
- expect(actual).toBe('76b0171f0dd53a1a00e5e321f376ae956faacf3db85cd95b644ef3dd9f91e78c')
+ expect(actual).toBe('f4bc05b2ee97b2a6b014bbf38728b4e4c76e4156d48180ff3bf63eb6a2d96d4d')
})
})
diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.ts
index b333ed27c..67a2baffa 100644
--- a/cli/src/lib/e2ee/core.ts
+++ b/cli/src/lib/e2ee/core.ts
@@ -349,7 +349,7 @@ export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>([
'e2ee_pairings_unpair_all_result', 'e2ee_browser_link_create_result',
// Device RPC replies that carry adapter content (recap headline/body, new agent name). Must be
// ciphertext so the backend relay can't read them — device↔adapter E2EE parity with web.
- 'agent_recent_result', 'agent_create_result', 'agent_restart_result',
+ 'agent_recent_result', 'agent_create_result', 'agent_create_status_result', 'agent_restart_result',
// A remote-machine directory listing (New Agent folder browser) — leaks filesystem layout if plaintext.
'fs_list_dir_result',
// Same reasoning as fs_list_dir_result: reveals Codex profile folder names/paths on this machine.
@@ -367,7 +367,7 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>([
// as "no session/answers", the pane dialog was never keyed, and the CLI waited on question 1 forever.
'question_response',
'agents_list', 'sessions_list', 'session_get', 'models_list',
- 'agent_create', 'agent_delete', 'agent_restart', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file',
+ 'agent_create', 'agent_create_status', 'agent_delete', 'agent_restart', 'agent_recent', 'agent_update', 'agent_files', 'agent_read_file',
'fs_list_dir', 'codex_profiles_list', 'codex_profile_link',
// Asks this machine to read its own agent accounts' usage (lib/accountUsage.ts). ⚠️ Missing here it
// would not fail loudly — the same trap `question_response` once fell into: the payload would stay
diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.ts
index 35f28972a..71aaa79e2 100644
--- a/cli/src/lib/e2ee/relayLink.spec.ts
+++ b/cli/src/lib/e2ee/relayLink.spec.ts
@@ -130,6 +130,17 @@ describe('remote-password link + relay session crypto (interop with the real E2e
expect(decrypted).not.toBeNull()
expect((decrypted!.payload as Record<string, unknown>).foo).toBe('bar')
+ // Creation recovery must take the same encrypted route as creation; its result contains
+ // the agent's name and working folder. The relay sees neither the receipt nor those fields.
+ const checking = { requestId: 'check-1', creationId: 'creation-fixture-001' }
+ const statusRequest = crypto.wrapOutgoing({ type: 'agent_create_status', payload: checking })
+ expect(statusRequest.payload).not.toHaveProperty('creationId')
+ expect(manager.unwrapDown('session-conn', statusRequest)?.payload).toEqual(checking)
+ const status = { ...checking, state: 'created', agent: { id: 'agent-1', cwd: '/private/work' } }
+ const statusReply = manager.wrapTarget('session-conn', 'agent_create_status_result', status)!
+ expect(statusReply.payload).not.toHaveProperty('agent')
+ expect(crypto.unwrapIncoming(statusReply)?.payload).toEqual(status)
+
const lowerDown = crypto.wrapOutgoing({ type: 'terminal_resize', payload: { streamId: 's', cols: 80 } })
const higherDown = crypto.wrapOutgoing({ type: 'terminal_resize', payload: { streamId: 's', cols: 120 } })
expect((manager.unwrapDown('session-conn', higherDown)?.payload as Record<string, unknown>).cols).toBe(120)
diff --git a/docs/harness-agent-creation.md b/docs/harness-agent-creation.md
new file mode 100644
index 000000000..dba023dcc
--- /dev/null
+++ b/docs/harness-agent-creation.md
@@ -0,0 +1,55 @@
+# Recovering agent creation
+
+The desktop must not interpret a lost reply as proof that no agent started.
+Otherwise a second click can create a duplicate persistent session. This is
+separate from the proposed Archive/Resume lifecycle; it stops no existing agent.
+
+## Protocol
+
+- A deliberate creation has a random `creationId`, independent of transport
+ `requestId`. A retry retains it; an explicit fresh New agent action changes it.
+- `agent_create` accepts an optional `creationId`. The CLI reserves it before
+ calling the launcher. The same id and launch choices reuse its outcome;
+ different choices return `CREATION_CONFLICT`.
+- `agent_create_status` only reads the receipt. Replies echo `creationId` and
+ report `missing`, `pending`, `created`, `failed`, `unconfirmed` or `unavailable`.
+ `created` includes the current agent frame. `failed` carries `failure.code`
+ and optional `failure.detail`, separate from RPC/transport errors.
+- A missing receipt reported by a supporting CLI permits retry with the same
+ id. An unsupported request, malformed reply or transport failure does not.
+ Do not use a `checkOnly` flag on `agent_create`: old CLIs would launch it.
+- Receipt-aware creation is detached from the connection's ordered request
+ chain, so a status request can be answered while creation is still pending.
+- The receipt is private machine-local state under `agent-creations`. It stores
+ a hash of launch choices, the agent identity or a bounded failure, never a
+ second copy of launch credentials. Reservations and replacements are fsynced;
+ old receipts are not evicted and then interpreted as new requests.
+- A receipt surviving a daemon interruption without a confirmed result is
+ `unconfirmed`. A tmux spawn timeout or failed registration cleanup also cannot
+ prove that nothing started. Those intents never launch again automatically.
+ If only the completion write failed, the live daemon retains the known result.
+- If an agent was subsequently deleted, replay returns `unavailable`; it does
+ not create a replacement runtime.
+- Both the status request and response use pairwise E2EE on relayed machines.
+ The core classification hash changes only for the added frame types; the
+ cryptographic format and existing frame classifications are unchanged. The
+ browser/device copies in other repositories need these classifications only
+ when adopting this new RPC.
+
+## Compatibility and verification
+
+Legacy callers without `creationId` keep the existing create response. An older
+CLI can also handle a new desktop's first create, ignoring the additional field.
+The desktop must check status before resending an uncertain request, including
+on old CLIs where status may be unsupported or time out.
+
+September 14 CLI checkpoint: 150 affected checks pass (receipt storage,
+BackendSocket creation, existing launch helper, E2EE and relay fixtures), along
+with TypeScript checking and CLI bundling. The new BackendSocket recovery tests
+failed before integration. All launch callbacks use fakes and all state/sockets
+are disposable. The CLI bundle was not installed or restarted.
+
+The desktop recovery UI is the next part of this checkpoint. Real process
+creation across a remote disconnect remains to be verified. A crash between
+launch and receipt completion is conservatively unconfirmed, not automatically
+reconciled with the runtime registry. Native benchmarking remains deferred.