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
Answer an agent before a long install, and never start its harness twice (#1220)
Dee6ab085e1f099
diff --git a/cli/e2e/agentClient.e2e.ts b/cli/e2e/agentClient.e2e.tsindex 1ec9e5571..6afbb878d 100644--- a/cli/e2e/agentClient.e2e.ts+++ b/cli/e2e/agentClient.e2e.ts@@ -109,7 +109,8 @@ describe('Harness for agents, end to end', () => {expect(started.out).toContain(`Created kid on this computer in ${join(d.env.HOME!, 'harnesses', 'kid')}.`)expect(started.out).toContain('Read it: harness show kid · wait for it: harness wait kid')expect(started.out).not.toContain('harness send')- const ledger = readFileSync(join(d.dataDir, 'agent-client', 'started.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line))+ // Started lines: a create the machine answers pending first also writes a pending one (agentClient/ledger.ts).+ const ledger = readFileSync(join(d.dataDir, 'agent-client', 'started.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line)).filter((row) => row.child)expect(ledger).toEqual([expect.objectContaining({ depth: 1, by: expect.objectContaining({ agentId: lead.id, name: 'lead' }), child: expect.objectContaining({ name: 'kid' }) })])// It waits for it, then reads its answer.@@ -215,7 +216,8 @@ describe('Harness for agents, end to end', () => {// Nothing can message an agent with no pane: no `send` in what to do next.expect(started.out).toContain('Read it: harness show helper · wait for it: harness wait helper')expect(started.out).not.toContain('harness send')- const ledger = readFileSync(join(d.dataDir, 'agent-client', 'started.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line))+ // Started lines: a create the machine answers pending first also writes a pending one (agentClient/ledger.ts).+ const ledger = readFileSync(join(d.dataDir, 'agent-client', 'started.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line)).filter((row) => row.child)expect(ledger).toEqual([expect.objectContaining({ depth: 1, by: expect.objectContaining({ agentId: 'claude-code:outside-session', name: 'Claude Code' }), child: expect.objectContaining({ name: 'helper' }) })])// No harness started it, so no window has one to open it beside.const helper = ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents).find((a) => a.name === 'helper')@@ -270,7 +272,8 @@ describe('Harness for agents, end to end', () => {expect(started.text).toContain(`Created mcpkid on this computer in ${join(d.env.HOME!, 'harnesses', 'mcp-kid')}.`)// Its next steps are named as the tools: an MCP client may have no shell to run `harness show` in.expect(started.text).toContain('Read it: harness_read (name: "mcpkid") · wait for it: harness_wait (names: "mcpkid")')- const ledger = readFileSync(join(d.dataDir, 'agent-client', 'started.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line))+ // Started lines: a create the machine answers pending first also writes a pending one (agentClient/ledger.ts).+ const ledger = readFileSync(join(d.dataDir, 'agent-client', 'started.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line)).filter((row) => row.child)expect(ledger).toEqual([expect.objectContaining({ by: expect.objectContaining({ agentId: expect.stringMatching(/^agent:cursor:mcp-\d+$/), name: 'Cursor' }) })])const waited = await server.call('harness_wait', { names: ['mcpkid'], timeout_seconds: 120 })expect(waited).toEqual({ text: 'mcpkid: idle · read it: harness_read (name: "mcpkid")', isError: false })diff --git a/cli/e2e/freshMachineEngines.e2e.ts b/cli/e2e/freshMachineEngines.e2e.tsindex eeb6a8612..5a05aa48e 100644--- a/cli/e2e/freshMachineEngines.e2e.ts+++ b/cli/e2e/freshMachineEngines.e2e.ts@@ -12,6 +12,7 @@* the install and then starts it, or says why it could not be installed, and leaves no folder behind either way.*/import { spawn } from 'node:child_process'+import { createInterface } from 'node:readline'import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { pathToFileURL } from 'node:url'@@ -145,20 +146,23 @@ it('says what a launch still held after a minute waits for, and cancels it so it} finally { client.close() }}, 180_000)-it('installs a missing Codex for a new project and starts it there, or says why it could not, leaving no folder', async (context) => {- // A computer with nothing: no codex, npm or node in the system folders the login shell's PATH names below.- const system = ['/usr/bin', '/bin', '/usr/sbin', '/sbin']- if (system.some((dir) => ['codex', 'npm', 'node'].some((name) => existsSync(join(dir, name))))) context.skip()- let offline = ''- const d = await boot((d) => {- const bin = join(d.root, 'bin'), tools = join(d.root, 'tools'), installed = join(d.root, 'codex-package')- offline = join(d.root, 'npm-offline')- // What `npm install -g @openai/codex` puts in the prefix is the fake engine's own wrapper; until then, no codex- // anywhere, so the daemon installs it with the recipe it would use on a person's computer.- renameSync(join(bin, 'codex'), installed)- delete d.env.CODEX_PATH- symlinkSync(process.execPath, join(bin, 'node'))- writeFileSync(join(bin, 'npm'), `#!/bin/sh+/** The system folders a login shell's PATH names on a computer with nothing installed. */+const SYSTEM = ['/usr/bin', '/bin', '/usr/sbin', '/sbin']+/** A computer that has a codex, npm or node in its system folders is not one with nothing installed. */+const notBare = (): boolean => SYSTEM.some((dir) => ['codex', 'npm', 'node'].some((name) => existsSync(join(dir, name))))++/**+ * No codex anywhere, so the daemon installs it with the recipe it would use on a person's computer, through an `npm`+ * that puts the fake engine's own wrapper in the prefix: after the seconds in `npm-seconds` (3 by default), or failing+ * as an offline npm does while `npm-offline` exists.+ */+function withoutCodex(d: IsolatedDaemon): void {+ const bin = join(d.root, 'bin'), tools = join(d.root, 'tools'), installed = join(d.root, 'codex-package')+ const offline = join(d.root, 'npm-offline'), seconds = join(d.root, 'npm-seconds')+ renameSync(join(bin, 'codex'), installed)+ delete d.env.CODEX_PATH+ symlinkSync(process.execPath, join(bin, 'node'))+ writeFileSync(join(bin, 'npm'), `#!/bin/shcase "$1" inprefix) printf '%s\\n' "\${npm_config_prefix:-$HOME/.local}"; exit 0 ;;install) ;;@@ -169,17 +173,22 @@ if [ -f ${JSON.stringify(offline)} ]; thenecho 'npm error network request to https://registry.npmjs.org/@openai%2fcodex failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org' >&2exit 1fi-sleep 3+sleep "$(cat ${JSON.stringify(seconds)} 2>/dev/null || echo 3)"mkdir -p "$npm_config_prefix/bin" && cp ${JSON.stringify(installed)} "$npm_config_prefix/bin/codex" && chmod 755 "$npm_config_prefix/bin/codex"`, { mode: 0o755 })- mkdirSync(tools)- symlinkSync(resolveBinaryOnPath('tmux')!, join(tools, 'tmux'))- // The daemon's own PATH too: no codex of the developer's may be found and run.- const path = [bin, tools, ...system].join(':')- d.env.PATH = path- writeFileSync(join(d.env.HOME!, '.zshrc'), `export PATH=${path}\n`)- writeFileSync(join(d.env.HOME!, '.bash_profile'), `export PATH=${path}\n`)- })+ mkdirSync(tools)+ symlinkSync(resolveBinaryOnPath('tmux')!, join(tools, 'tmux'))+ // The daemon's own PATH too: no codex of the developer's may be found and run.+ const path = [bin, tools, ...SYSTEM].join(':')+ d.env.PATH = path+ writeFileSync(join(d.env.HOME!, '.zshrc'), `export PATH=${path}\n`)+ writeFileSync(join(d.env.HOME!, '.bash_profile'), `export PATH=${path}\n`)+}++it('installs a missing Codex for a new project and starts it there, or says why it could not, leaving no folder', async (context) => {+ if (notBare()) context.skip()+ const d = await boot(withoutCodex)+ const offline = join(d.root, 'npm-offline')const home = d.env.HOME!, folder = join(home, 'harnesses', 'scratch1')const run = () => harness(d, ['new', 'codex', 'scratch1', '--name', 'cx', '--', 'Reply with pong'])// Offline: it says it is installing, then why Codex could not be installed, and no folder blocks the same command.@@ -205,3 +214,58 @@ mkdir -p "$npm_config_prefix/bin" && cp ${JSON.stringify(installed)} "$npm_confiexpect(agents[0]).toMatchObject({ name: 'cx' })} finally { client.close() }}, 180_000)++/** `harness mcp` as Codex starts it: requests in on stdin, answers by id from stdout. */+function mcp(d: IsolatedDaemon) {+ const child = spawn(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'mcp'], { cwd: CLI_ROOT, env: { ...d.env, TMUX_PANE: '' }, stdio: ['pipe', 'pipe', 'pipe'] })+ const waiting = new Map<number, (reply: Record<string, any>) => void>()+ createInterface({ input: child.stdout }).on('line', (line) => { const reply = JSON.parse(line); waiting.get(reply.id)?.(reply) })+ let next = 1+ const request = (method: string, params: Record<string, unknown> = {}): Promise<Record<string, any>> => {+ const id = next+++ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`)+ return new Promise((done) => waiting.set(id, done))+ }+ return {+ request,+ async call(name: string, args: Record<string, unknown>): Promise<{ text: string; isError: boolean; ms: number }> {+ const began = Date.now()+ const reply = await request('tools/call', { name, arguments: args })+ return { text: reply.result.content.map((c: { text: string }) => c.text).join('\n'), isError: reply.result.isError === true, ms: Date.now() - began }+ },+ close: () => child.stdin.end(),+ }+}++it('answers an MCP agent within Codex\'s tool timeout while Codex installs, starts that harness by itself, and never a second', async (context) => {+ if (notBare()) context.skip()+ const d = await boot((d) => { withoutCodex(d); writeFileSync(join(d.root, 'npm-seconds'), '55') })+ const server = mcp(d)+ try {+ await server.request('initialize', { protocolVersion: '2025-06-18', clientInfo: { name: 'codex-mcp-client' }, capabilities: {} })+ const task = { name: 'cx', agent: 'codex', project: 'scratch1', task: 'Reply with pong' }+ // Codex ends a tool call at 60 s unless told otherwise; the install takes 55 s here, and the answer comes first.+ const started = await server.call('harness_start', task)+ expect(started.isError, started.text).toBe(false)+ expect(started.ms).toBeLessThan(50_000)+ expect(started.text).toBe('Harness is installing Codex; the harness "cx" starts by itself once it is installed. '+ + 'Check on it with harness_list or harness_wait (names: "cx"); do not start it again.')+ // It follows it by name, and asking again is answered with it.+ const listed = await server.call('harness_list', {})+ expect(listed.text).toMatch(/\ncx +Codex +installing +you /)+ const again = await server.call('harness_start', task)+ expect(again.text).toBe('"cx" is already starting: Harness is installing Codex. It starts by itself; wait for it with harness_wait (names: "cx"). Do not start it again.')+ // It starts by itself once installed, and is waited on to its answer.+ let waited = await server.call('harness_wait', { names: ['cx'] })+ for (let i = 0; i < 4 && !/^cx: idle/.test(waited.text); i++) waited = await server.call('harness_wait', { names: ['cx'] })+ expect(waited.text).toBe('cx: idle · read it: harness_read (name: "cx")')+ } finally { server.close() }+ const client = await LocalClient.connect(d)+ try {+ const rows = (await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents+ expect(rows.map((row) => row.name)).toEqual(['cx'])+ } finally { client.close() }+ // Recorded as the MCP agent's, by the creation it was asked by.+ const ledger = readFileSync(join(d.dataDir, 'agent-client', 'started.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line))+ expect(ledger.find((row) => row.child)).toMatchObject({ by: { agentId: expect.stringMatching(/^agent:codex/) }, child: { name: 'cx', creationId: expect.any(String) } })+}, 240_000)diff --git a/cli/src/agentClient/commands.spec.ts b/cli/src/agentClient/commands.spec.tsindex 5a9ef3b04..550b38c87 100644--- a/cli/src/agentClient/commands.spec.ts+++ b/cli/src/agentClient/commands.spec.ts@@ -688,6 +688,29 @@ describe('harness new, run by an agent', () => {expect(spawnRefusal(lead, new Set(), quick, 'm', NOW)).toBe('You started 20 harnesses in 10 minutes. Wait, or work with the ones you have.')})+ it('counts harnesses asked for and still installing as running, toward every limit', () => {+ // Each starts by itself once its engine is installed: asked for meanwhile, they passed every limit and started at once.+ const lead = { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }+ const waiting = (n: number, machineId = 'm', at = NOW) => Array.from({ length: n }, (_, i) => ({ at, depth: 1, by: lead,+ creation: { machineId, creationId: `w${i}`, name: `w${i}`, engine: 'codex' } }))+ const empty = new Ledger(ledgerPath(mkdtempSync(join(dir, 'waiting-'))))+ expect(spawnRefusal(lead, new Set(), empty, 'm', NOW, waiting(SPAWN_LIMITS.livePerHarness - 1))).toBeNull()+ expect(spawnRefusal(lead, new Set(), empty, 'm', NOW, waiting(SPAWN_LIMITS.livePerHarness)))+ .toBe('You have 8 harnesses running or starting. Close one you are done with first (harness close <name>).')+ const crowd = new Ledger(ledgerPath(mkdtempSync(join(dir, 'crowd-waiting-'))))+ const busy = new Set<string>()+ for (let i = 0; i < SPAWN_LIMITS.livePerMachine - 1; i++) {+ crowd.append({ at: 0, depth: 1, by: { ...lead, agentId: `p${i}` }, child: { machineId: 'm', agentId: `c${i}`, name: `c${i}` } })+ busy.add(`m/c${i}`)+ }+ expect(spawnRefusal(lead, busy, crowd, 'm', NOW, waiting(1, 'mini'))).toBeNull()+ expect(spawnRefusal(lead, busy, crowd, 'm', NOW, waiting(1))).toMatch(/^Agents have 39 harnesses running on this machine/)+ const quick = new Ledger(ledgerPath(mkdtempSync(join(dir, 'quick-waiting-'))))+ for (let i = 0; i < SPAWN_LIMITS.perWindow - SPAWN_LIMITS.livePerHarness + 1; i++) started(quick, 'lead', `q${i}`, 'm', NOW - 60_000)+ expect(spawnRefusal(lead, new Set(), quick, 'm', NOW, waiting(SPAWN_LIMITS.livePerHarness - 1))).toBe('You started 20 harnesses in 10 minutes. Wait, or work with the ones you have.')+ expect(spawnRefusal(lead, new Set(), quick, 'm', NOW, waiting(SPAWN_LIMITS.livePerHarness - 1, 'm', NOW - 11 * 60_000))).toBeNull()+ })+it('counts what it started on other machines as those machines say, and a day of them when one cannot be asked', async () => {const d = new FakeDaemon()d.frames = [frame('lead')]@@ -711,3 +734,230 @@ describe('harness new, run by an agent', () => {await expect((await agentOrigin(harness(d, { others: { mini: odd } }).deps))!.check()).rejects.toThrow(/You have 8 harnesses running/)})})++describe('a harness asked for that has not started (its engine still installing)', () => {+ const asked = (ledger: Ledger, name: string, creationId: string, machineId = 'm', at = NOW) => ledger.append({+ at, depth: 1, by: { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }, creation: { machineId, creationId, name, engine: 'codex' },+ })+ const installing = { state: 'pending', held: { service: 'install', detail: 'Installing Codex. The harness starts once it is installed.' } }++ it('lists it by its name as installing, and records it as the caller\'s once its machine has made it', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' })]+ const statuses: Record<string, Record<string, unknown>> = { c1: installing, c2: { state: 'cancelled' }, c3: { state: 'failed', failure: { code: 'ENGINE_INSTALL_FAILED', detail: 'Codex could not be installed: offline' } } }+ d.extra.agent_create_status = (p) => statuses[String(p.creationId)] ?? { state: 'missing' }+ const h = harness(d, { env: { HARNESS_VIA_MCP: '1' } })+ asked(h.ledger, 'cx', 'c1'); asked(h.ledger, 'gone', 'c2'); asked(h.ledger, 'broke', 'c3'); asked(h.ledger, 'old', 'c4', 'm', NOW - 31 * 60_000)+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)+ const text = h.out.join('\n')+ expect(text).toMatch(/\ncx +Codex +installing +you \(you\)|\ncx +Codex +installing +you /)+ expect(text).toContain('cx has not started yet: Harness is installing Codex. It starts by itself; wait for it with harness_wait (names: "cx").')+ expect(text).toMatch(/\nbroke +Codex +failed +you /)+ expect(text).toContain('broke never started: Codex could not be installed: offline.')+ expect(text).not.toContain('gone')+ // A line older than any install is not asked after.+ expect(d.requests.filter((r) => r.type === 'agent_create_status').map((r) => r.payload.creationId)).toEqual(['c1', 'c2', 'c3'])+ // Made now: the caller's, by the creation it was asked for, and no longer listed as installing.+ statuses.c1 = { state: 'created', agent: frame('k1', { name: 'cx' }) }+ d.frames.push(frame('k1', { name: 'cx' }))+ h.out.length = 0+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n')).toMatch(/\ncx +Codex +idle +you /)+ expect(h.ledger.parentOf({ machineId: 'm', agentId: 'k1' })).toMatchObject({ at: NOW, by: { agentId: 'lead' }, child: { name: 'cx', creationId: 'c1' } })+ })++ it('waits for it to start, then for its turn; says how one that never started ended, and one still installing', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' })]+ let asks = 0+ d.extra.agent_create_status = (p) => {+ if (p.creationId !== 'c1') return p.creationId === 'c2' ? { state: 'failed', failure: { code: 'ENGINE_INSTALL_FAILED', detail: 'Codex could not be installed: offline' } } : installing+ if (++asks < 4) return installing+ // Made: in the list from now on, as the daemon lists what it made.+ if (!d.frames.some((f) => f.id === 'k1')) d.frames.push(frame('k1', { name: 'cx' }))+ return { state: 'created', agent: frame('k1', { name: 'cx' }) }+ }+ d.pages.set('s-k1', [{ events: [ev('user_message', { content: 'go' }), ev('text_delta', { content: 'done' })], hasMore: false }])+ const h = harness(d)+ asked(h.ledger, 'cx', 'c1')+ expect(await waitCommand(['cx'], h.deps)).toBe(EXIT.ok)+ expect(h.out).toEqual(['cx: idle · read it: harness show cx'])+ expect(h.ledger.parentOf({ machineId: 'm', agentId: 'k1' })?.child.creationId).toBe('c1')+ asked(h.ledger, 'broke', 'c2')+ h.out.length = 0+ expect(await waitCommand(['broke'], h.deps)).toBe(EXIT.stopped)+ expect(h.out).toEqual(['broke: failed · it never started: Codex could not be installed: offline'])+ asked(h.ledger, 'slow', 'c3')+ h.out.length = 0+ expect(await waitCommand(['slow', '--timeout', '5s', '--json'], h.deps)).toBe(EXIT.timeout)+ expect(JSON.parse(h.out[0])).toEqual({ harnesses: [{ name: 'slow', id: 'c3', state: 'installing', detail: 'Installing Codex. The harness starts once it is installed.' }] })+ h.out.length = 0+ expect(await waitCommand(['slow', '--timeout', '2s'], h.deps)).toBe(EXIT.timeout)+ expect(h.out).toEqual(['slow: installing · slow has not started yet: Harness is installing Codex. It starts by itself; wait for it with harness wait slow.'])+ })++ it('answers show with what it waits for, and close by cancelling it before it starts', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' })]+ let cancel: Record<string, unknown> = { state: 'cancelled' }+ d.extra.agent_create_status = () => installing+ d.extra.agent_create_cancel = () => cancel+ const h = harness(d)+ asked(h.ledger, 'cx', 'c1')+ expect(await showCommand(['cx'], h.deps)).toBe(EXIT.failed)+ expect(h.err).toEqual(['cx has not started yet: Harness is installing Codex. It starts by itself; wait for it with harness wait cx.'])+ expect(await closeCommand(['cx'], h.deps)).toBe(EXIT.ok)+ expect(h.out).toEqual(['Cancelled cx before it started.'])+ expect(d.requests.find((r) => r.type === 'agent_create_cancel')?.payload.creationId).toBe('c1')+ cancel = { state: 'unconfirmed' }+ h.err.length = 0+ expect(await closeCommand(['cx'], h.deps)).toBe(EXIT.failed)+ expect(h.err).toEqual(['cx is starting now, so it was not cancelled. Close it once it has: harness close cx.'])+ })++ it('follows one on another machine through that machine', async () => {+ const d = new FakeDaemon(), mini = new FakeDaemon('mini')+ d.frames = [frame('lead', { engine: 'claude' })]+ mini.extra.agent_create_status = () => ({ state: 'pending', held: { service: 'native', detail: 'Waiting to confirm the engine’s native hooks.' } })+ const h = harness(d, { others: { mini } })+ asked(h.ledger, 'far', 'c9', 'mini')+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n')).toContain('far has not started yet: it is starting (Waiting to confirm the engine’s native hooks). It starts by itself; wait for it with harness wait far.')+ expect(mini.closed).toBe(true)+ // A machine that cannot be asked keeps it as starting.+ asked(h.ledger, 'away', 'c8', 'offline')+ h.out.length = 0+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n')).toMatch(/\naway +Codex +starting +you /)+ })+})++describe('a harness that started by itself, recorded and followed', () => {+ const install = { state: 'pending', held: { service: 'install', detail: 'Installing Codex.' } }+ const asking = (ledger: Ledger, by: string, name: string, creationId: string, machineId = 'm') => ledger.append({+ at: NOW, depth: 1, by: { machineId: 'm', agentId: by, name: by, engine: 'claude' }, creation: { machineId, creationId, name, engine: 'codex' },+ })++ it('is recorded as started by who asked by any verb on its machine, there and on its own machine', async () => {+ const d = new FakeDaemon(), mini = new FakeDaemon('mini')+ d.frames = [frame('lead', { engine: 'claude' }), frame('kid', { name: 'kid' })]+ d.extra.agent_create_status = () => ({ state: 'created', agent: frame('kid') })+ mini.extra.agent_create_status = () => ({ state: 'created', agent: frame('far1', { name: 'far' }) })+ const sent: unknown[] = []+ // The person runs ps: the harness another agent asked for here is that agent's, and so is its depth.+ const h = harness(d, { pane: undefined, others: { mini }, record: async (to, body) => { sent.push([to, body]); return {} } })+ asking(h.ledger, 'other', 'kid', 'c1')+ asking(h.ledger, 'other', 'far', 'c2', 'mini')+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)+ expect(h.ledger.parentOf({ machineId: 'm', agentId: 'kid' })).toMatchObject({ by: { agentId: 'other' }, child: { creationId: 'c1' } })+ expect(h.ledger.depthOf({ machineId: 'm', agentId: 'kid' })).toBe(1)+ // Another's on another machine is theirs to ask.+ expect(mini.requests).toEqual([])+ const mine = harness(d, { others: { mini }, record: async (to, body) => { sent.push([to, body]); return {} } })+ asking(mine.ledger, 'lead', 'far', 'c3', 'mini')+ expect(await psCommand([], mine.deps)).toBe(EXIT.ok)+ expect(mine.ledger.parentOf({ machineId: 'mini', agentId: 'far1' })?.child.creationId).toBe('c3')+ expect(sent).toEqual([[{ port: 1, dataDir: dir, machineId: 'mini' }, { action: 'started', row: expect.objectContaining({ child: expect.objectContaining({ agentId: 'far1', creationId: 'c3' }) }) }]])+ // Recorded once: asked again, nothing more is written or sent.+ expect(await psCommand([], mine.deps)).toBe(EXIT.ok)+ expect(mine.ledger.all().filter((row) => row.child.agentId === 'far1')).toHaveLength(1)+ expect(sent).toHaveLength(1)+ })++ it('is found by exactly its name before a running harness whose name only starts so, and by its creation when unnamed', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('reviewer-old', { name: 'reviewer-old' })]+ d.extra.agent_create_status = () => install+ const h = harness(d)+ started(h.ledger, 'lead', 'reviewer-old')+ asking(h.ledger, 'lead', 'reviewer', 'c1')+ asking(h.ledger, 'lead', '', 'abcdef123456')+ expect(await showCommand(['reviewer'], h.deps)).toBe(EXIT.failed)+ expect(h.err.at(-1)).toBe('reviewer has not started yet: Harness is installing Codex. It starts by itself; wait for it with harness wait reviewer.')+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n')).toMatch(/\nabcdef12 +Codex +installing +you /)+ expect(await showCommand(['abcdef12'], h.deps)).toBe(EXIT.failed)+ expect(h.err.at(-1)).toBe('abcdef12 has not started yet: Harness is installing Codex. It starts by itself; wait for it with harness wait abcdef12.')+ })++ it('says how close went when the harness started meanwhile, never did, or could not be cancelled', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' })]+ let cancel: Record<string, unknown> = { state: 'created', agent: frame('k1') }+ d.extra.agent_create_status = () => install+ d.extra.agent_create_cancel = () => cancel+ const h = harness(d)+ asking(h.ledger, 'lead', 'cx', 'c1')+ expect(await closeCommand(['cx'], h.deps)).toBe(EXIT.failed)+ expect(h.err.at(-1)).toBe('cx is starting now, so it was not cancelled. Close it once it has: harness close cx.')+ cancel = { state: 'failed', failure: { code: 'ENGINE_INSTALL_FAILED', detail: 'Codex could not be installed: offline' } }+ expect(await closeCommand(['cx'], h.deps)).toBe(EXIT.failed)+ expect(h.err.at(-1)).toBe('cx never started: Codex could not be installed: offline. Nothing to close.')+ cancel = { error: 'UNSUPPORTED' }+ expect(await closeCommand(['cx', '--json'], h.deps)).toBe(EXIT.failed)+ expect(JSON.parse(h.out.at(-1)!)).toEqual({ error: 'UNSUPPORTED', detail: 'cx could not be cancelled (UNSUPPORTED). Check it with harness ps.' })+ cancel = {}+ expect(await closeCommand(['cx'], h.deps)).toBe(EXIT.failed)+ expect(h.err.at(-1)).toBe('cx could not be cancelled. Check it with harness ps.')+ })++ it('keeps waiting on one whose machine is out of reach for a moment', async () => {+ const d = new FakeDaemon(), mini = new FakeDaemon('mini')+ d.frames = [frame('lead', { engine: 'claude' })]+ let reachable = false+ mini.extra.agent_create_status = () => { if (!reachable) throw new AgentClientError('DISCONNECTED', 'gone'); return install }+ const h = harness(d, { others: { mini } })+ asking(h.ledger, 'lead', 'far', 'c9', 'mini')+ const waited = waitCommand(['far', '--timeout', '6s'], h.deps)+ expect(await waited).toBe(EXIT.timeout)+ expect(h.out).toEqual(['far: starting · far has not started yet: it is starting. It starts by itself; wait for it with harness wait far.'])+ reachable = true+ expect(await waitCommand(['far', '--timeout', '2s'], h.deps)).toBe(EXIT.timeout)+ expect(h.out.at(-1)).toBe('far: installing · far has not started yet: Harness is installing Codex. It starts by itself; wait for it with harness wait far.')+ })+})++describe('an agent asking again for a harness it already has', () => {+ it('is answered with the one still installing or running by that name, and starts a new one otherwise', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('k1', { name: 'reviewer' }), frame('k2', { name: 'old', status: 'stopped' })]+ d.extra.agent_create_status = (p) => p.creationId === 'c1' ? { state: 'pending', held: { service: 'install', detail: 'Installing Codex.' } }+ : { state: 'failed', failure: { code: 'ENGINE_INSTALL_FAILED', detail: 'offline' } }+ const h = harness(d, { env: { HARNESS_VIA_MCP: '1' } })+ h.ledger.append({ at: NOW, depth: 1, by: { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }, creation: { machineId: 'm', creationId: 'c1', name: 'cx', engine: 'codex' } })+ h.ledger.append({ at: NOW, depth: 1, by: { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }, creation: { machineId: 'm', creationId: 'c2', name: 'broke', engine: 'codex' } })+ started(h.ledger, 'lead', 'k1', 'm', NOW - 3 * 60_000)+ h.ledger.append({ at: NOW - 2 * 60_000, depth: 1, by: { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }, child: { machineId: 'm', agentId: 'k1', name: 'reviewer' } })+ started(h.ledger, 'lead', 'k2', 'm', NOW - 60_000)+ const origin = (await agentOrigin(h.deps))!+ const codexHere = { machineId: 'm', engine: 'codex' }+ expect(await origin.existing!('CX', codexHere)).toEqual({ name: 'cx', machineId: 'm', state: 'starting',+ note: '"cx" is already starting: Harness is installing Codex. It starts by itself; wait for it with harness_wait (names: "cx"). Do not start it again.' })+ expect(await origin.existing!('reviewer', codexHere)).toEqual({ name: 'reviewer', machineId: 'm', agentId: 'k1', state: 'running',+ note: '"reviewer" is already running: you started it 2 min ago. Wait for it with harness_wait (names: "reviewer") or read it with harness_read (name: "reviewer"). '+ + 'Do not start it again; to start a new one by that name, close it first (harness_close (name: "reviewer")).' })+ // A store harness is judged by the machine alone: it is recorded by the engine it runs on.+ expect(await origin.existing!('cx', { machineId: 'm', engine: 'acme/notes' })).toMatchObject({ name: 'cx' })+ // One that never started, one stopped, one by another name, none at all, another agent or machine: started anew.+ for (const name of ['broke', 'k2', 'other', null, ' ']) expect(await origin.existing!(name, codexHere)).toBeNull()+ expect(await origin.existing!('cx', { machineId: 'm', engine: 'claude' })).toBeNull()+ expect(await origin.existing!('reviewer', { machineId: 'm', engine: 'claude' })).toBeNull()+ expect(await origin.existing!('cx', { machineId: 'mini', engine: 'codex' })).toBeNull()+ // Started more than ten minutes ago: new work by an old name, not a retry.+ const later = harness(d, { env: {}, now: () => NOW + 11 * 60_000 })+ expect(await (await agentOrigin(later.deps))!.existing!('reviewer', codexHere)).toBeNull()+ })++ it('records a harness asked for before it starts, and its creation once it has', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' })]+ const h = harness(d)+ const origin = (await agentOrigin(h.deps))!+ origin.pending!('m', { creationId: 'c5', name: 'cx', engine: 'codex' })+ expect(h.ledger.pendingOf({ machineId: 'm', agentId: 'lead' }, NOW)).toEqual([{ at: NOW, depth: 1,+ by: { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }, creation: { machineId: 'm', creationId: 'c5', name: 'cx', engine: 'codex' } }])+ await origin.created('m', { id: 'k5', name: 'cx' }, 'c5')+ expect(h.ledger.pendingOf({ machineId: 'm', agentId: 'lead' }, NOW)).toEqual([])+ expect(h.ledger.parentOf({ machineId: 'm', agentId: 'k5' })?.child).toEqual({ machineId: 'm', agentId: 'k5', name: 'cx', creationId: 'c5' })+ })+})diff --git a/cli/src/agentClient/commands.ts b/cli/src/agentClient/commands.tsindex 23515439d..1d785452d 100644--- a/cli/src/agentClient/commands.ts+++ b/cli/src/agentClient/commands.ts@@ -21,7 +21,7 @@ import { MAX_FIRST_PROMPT_CHARS } from '../lib/engineLaunch.js'import type { NewOrigin } from '../lib/newCommand.js'import { engineName } from '../messages/model.js'import { AgentClientError, openDaemon, whereFor, type Daemon, type Where } from './daemon.js'-import { Ledger, ledgerPath, type Started } from './ledger.js'+import { Ledger, ledgerPath, type Pending, type Started } from './ledger.js'import { messagesRpc, type Rpc } from '../messages/rpc.js'import { callerOf, clip, isAgent, lastTurn, matching, outsideCaller, rowsOf, stateOf, STOPPED_WITHIN_MS, type Caller, type Frame, type HistoryEvent, type Row, type State } from './model.js'@@ -38,6 +38,8 @@ export interface ClientDeps {sleep?: (ms: number) => Promise<void>/** How often `wait` looks. */intervalMs?: number+ /** How a start is recorded on another machine (the messages service's `started`). */+ record?: Rpc}export const PS_USAGE = `Usage: harness ps [--all] [--json]@@ -91,8 +93,17 @@ export const AGENTS_START_AGENTS_OFF = 'The person has turned off agents startinconst ORPHAN = 'This pane\'s harness is no longer running, so nothing here may close or start harnesses. Only the person can.'+/**+ * A harness the caller asked for that has not started, as its machine says now: still on its way (`installing` while+ * Harness installs its engine), or never started (`failed`, with why). `harness new` answers before an install is done,+ * so an agent follows such a harness by its name with `ps` and `wait` until it starts by itself.+ */+export interface Asked { row: Pending; state: 'installing' | 'starting' | 'failed'; detail: string }+interface Opened {where: Where; daemon: Daemon; frames: Frame[]; caller: Caller | null; ledger: Ledger; machine: string+ /** The caller's harnesses asked for and not started (`Asked`). */+ asked: Asked[]/** Run from a pane Harness made whose harness it no longer knows (closed, forgotten): what is left of an agent,* a background job it started, say. Never the person: it may look, not close or start. */orphan: boolean@@ -112,6 +123,7 @@ function setup(deps: ClientDeps) {now: deps.now ?? Date.now,sleep: deps.sleep ?? ((ms: number) => new Promise<void>((done) => setTimeout(done, ms))),intervalMs: deps.intervalMs ?? DEFAULT_INTERVAL_MS,+ record: deps.record ?? messagesRpc,}}type Setup = ReturnType<typeof setup>@@ -148,10 +160,87 @@ async function opened(s: Setup, includeStopped = false): Promise<Opened> {const orphan = !!s.pane && !!where.harnessPane && !inPane && !terminal// Not a harness: an agent outside Harness when its shell says so, even in a terminal of Harness's own.const caller = inPane ?? (orphan ? null : outsideCaller(s.env, where.machineId))- return { where, daemon, frames, caller, orphan, stopped: includeStopped, ledger: s.ledger(where.dataDir), machine: machineNameOf(where.dataDir) }+ const ledger = s.ledger(where.dataDir)+ const asked = await askAfter(s, where, daemon, ledger, caller)+ return { where, daemon, frames, caller, orphan, stopped: includeStopped, ledger, machine: machineNameOf(where.dataDir), asked }} catch (error) { daemon.close(); throw error }}+/** What a held creation waits for, in the machine's words (`held.detail`). */+const heldDetail = (status: Record<string, unknown>): string => {+ const held = status.held as { detail?: unknown } | undefined+ return typeof held?.detail === 'string' ? held.detail.replace(/[\x00-\x1f\x7f]/g, ' ').trim().slice(0, 500) : ''+}++/** How it stands, from a creation's status: null once there is nothing left to follow (made, cancelled, unknown). */+export function askedOf(row: Pending, status: Record<string, unknown>): Asked | null {+ if (status.state === 'pending') {+ const install = (status.held as { service?: unknown } | undefined)?.service === 'install'+ return { row, state: install ? 'installing' : 'starting', detail: heldDetail(status) }+ }+ if (status.state !== 'failed') return null+ const failure = (status.failure ?? {}) as { code?: unknown; detail?: unknown }+ const detail = typeof failure.detail === 'string' && failure.detail ? failure.detail : typeof failure.code === 'string' ? failure.code : ''+ return { row, state: 'failed', detail: detail.slice(0, 500) }+}++/**+ * Records a harness asked for and made since as started by who asked (`Started`, with its creation), here and, for one+ * on another machine, there too, as `harness new` does (`created`): there its limits and depth start from it.+ */+async function recordMade(s: Setup, where: Where, ledger: Ledger, row: Pending, agent: Frame): Promise<void> {+ const started: Started = { at: row.at, by: row.by, depth: row.depth,+ child: { machineId: row.creation.machineId, agentId: agent.id, name: agent.name || row.creation.name, creationId: row.creation.creationId } }+ if (ledger.parentOf(started.child)) return+ ledger.record(started)+ if (row.creation.machineId !== where.machineId) {+ await s.record({ port: where.port, dataDir: where.dataDir, machineId: row.creation.machineId }, { action: 'started', row: started }, 10_000).catch(() => {})+ }+}++/**+ * The pending lines (ledger.ts `Pending`) asked of their machines. One now made is recorded as started by who asked, as+ * `harness new` would have had it not answered first: anyone's on this machine, so a harness that started by itself+ * has its depth before it runs a verb of its own, and the caller's anywhere. The rest of the caller's are what it still+ * follows. A machine that cannot be asked keeps its line as starting: a second harness by that name is the risk here.+ */+async function askAfter(s: Setup, where: Where, daemon: Daemon, ledger: Ledger, caller: Caller | null): Promise<Asked[]> {+ const asked: Asked[] = []+ const mine = (row: Pending) => !!caller && row.by.machineId === caller.machineId && row.by.agentId === caller.agentId+ for (const row of ledger.pendingOf(null, s.now())) {+ const here = row.creation.machineId === where.machineId+ if (!here && !mine(row)) continue+ let line: Daemon | null = here ? daemon : null+ try {+ line ??= await s.open(where, row.creation.machineId)+ const status = await line.request('agent_create_status', { creationId: row.creation.creationId }, 8_000)+ const agent = (status.agent ?? {}) as Frame+ if (status.state === 'created' && typeof agent.id === 'string' && agent.id) { await recordMade(s, where, ledger, row, agent); continue }+ const now = mine(row) ? askedOf(row, status) : null+ if (now) asked.push(now)+ } catch { if (mine(row)) asked.push({ row, state: 'starting', detail: '' }) }+ finally { if (!here) line?.close() }+ }+ return asked+}++/** How a harness asked for is called: its name, else its creation's start. */+const askedName = (a: Asked): string => a.row.creation.name || a.row.creation.creationId.slice(0, 8)++/** What the caller asked for by [name] that has not started: the latest, by the name it was given or its creation's start. */+const askedNamed = (o: Opened, name: string): Asked | undefined => {+ const wanted = name.trim().toLowerCase()+ return o.asked.filter((a) => askedName(a).toLowerCase() === wanted || (wanted.length >= 6 && a.row.creation.creationId.toLowerCase().startsWith(wanted))).at(-1)+}++/** One line on a harness that has not started: what it waits for, or why it never will. */+function askedLine(env: NodeJS.ProcessEnv, a: Asked): string {+ const name = askedName(a), engine = engineName(a.row.creation.engine)+ if (a.state === 'failed') return `${name} never started: ${a.detail || 'its machine refused it'}.`+ const why = a.state === 'installing' ? `Harness is installing ${engine}` : `it is starting${a.detail ? ` (${a.detail.replace(/\.$/, '')})` : ''}`+ return `${name} has not started yet: ${why}. It starts by itself; wait for it with ${step(env, 'wait', name)}.`+}+interface Target { daemon: Daemon; frame: Frame; machineId: string; machine: string; yours: boolean; remote: boolean }/**@@ -164,6 +253,10 @@ async function target(s: Setup, o: Opened, name: string): Promise<Target> {const parent = o.ledger.parentOf({ machineId, agentId })return !!o.caller && !!parent && parent.by.agentId === o.caller.agentId && parent.by.machineId === o.caller.machineId}+ // Asked for by exactly this name and not started: it, before a harness whose name merely starts so.+ const pending = askedNamed(o, name)+ const exactly = (f: Frame) => f.name?.toLowerCase() === name.trim().toLowerCase() || f.id.toLowerCase() === name.trim().toLowerCase()+ if (pending && !named(o.frames).some(exactly)) throw new AgentClientError(pending.state === 'failed' ? 'NEVER_STARTED' : 'NOT_STARTED', askedLine(s.env, pending))let found = matching(name, named(o.frames))// No live one by that name: the stopped ones too, read once.if (!found.length && !o.stopped) {@@ -193,6 +286,8 @@ async function target(s: Setup, o: Opened, name: string): Promise<Target> {if (!frame) { daemon.close(); throw new AgentClientError('GONE', `${elsewhere[0].name} is no longer on its machine.`) }return { daemon, frame, machineId: row.child.machineId, machine: row.child.machineId.slice(0, 8), yours: true, remote: true }}+ const asked = askedNamed(o, name)+ if (asked) throw new AgentClientError(asked.state === 'failed' ? 'NEVER_STARTED' : 'NOT_STARTED', askedLine(s.env, asked))throw new AgentClientError('UNKNOWN_HARNESS', `No harness named "${name}" on this machine. \`${step(s.env, 'ps')}\` lists them.`)}@@ -316,6 +411,12 @@ export function psCommand(argv: readonly string[], deps: ClientDeps = {}): Promiif (asks.length) row.asks = asks.map((a) => clip(a.replace(/\s+/g, ' ').trim(), 200))if (about.length) row.about = about.join(' / ')}))+ // Asked for and not started yet: listed by the name it was given, and what it waits for.+ rows.unshift(...o.asked.map((a): Row => ({+ name: askedName(a), id: a.row.creation.creationId, agent: engineName(a.row.creation.engine),+ machine: a.row.creation.machineId === o.where.machineId ? o.machine : a.row.creation.machineId.slice(0, 8), state: a.state,+ folder: null, branch: null, startedBy: 'you', yours: true, self: false, lastActive: new Date(a.row.at).toISOString(), about: askedLine(s.env, a),+ })))s.out(flags.has('--json') ? JSON.stringify({ you: o.caller ? o.caller.name : null, machine: o.machine, harnesses: rows }, null, 1) : formatRows(rows, o.caller, s.now()))return EXIT.ok} finally { o.daemon.close() }@@ -366,7 +467,7 @@ export function showCommand(argv: readonly string[], deps: ClientDeps = {}): Pro// ── wait ───────────────────────────────────────────────────────────────────────────────────────────-type Settled = 'idle' | 'needs-input' | 'stopped' | 'gone' | 'timeout'+type Settled = 'idle' | 'needs-input' | 'stopped' | 'gone' | 'timeout' | 'failed'export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Promise<number> {return run(WAIT_USAGE, deps, wantsJson, argv, async (s) => {@@ -376,11 +477,43 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Proconst timeoutMs = flags.has('--timeout') ? parseDuration(String(flags.get('--timeout'))) : DEFAULT_TIMEOUT_MSconst o = await opened(s)const targets: Target[] = []+ /** Harnesses asked for that have not started (`Asked`): followed by their creation until they start, then waited on+ * as any other. `harness new` answers an agent before an engine's install is done, and the harness starts by itself. */+ const following: Asked[] = []+ const gave = new Map<Asked, Settled>()try {for (const name of wanted) {- const t = await target(s, o, name)+ let t: Target+ try { t = await target(s, o, name) } catch (error) {+ const asked = error instanceof AgentClientError && (error.code === 'NOT_STARTED' || error.code === 'NEVER_STARTED') ? askedNamed(o, name) : undefined+ if (!asked) throw error+ if (!following.includes(asked)) following.push(asked)+ if (asked.state === 'failed') gave.set(asked, 'failed')+ continue+ }if (!targets.some((x) => x.machineId === t.machineId && x.frame.id === t.frame.id)) targets.push(t)}+ /** Asks a creation how it stands: made, it joins the harnesses waited on, recorded as the caller's. */+ const follow = async (a: Asked): Promise<void> => {+ const here = a.row.creation.machineId === o.where.machineId+ const line = here ? o.daemon : await s.open(o.where, a.row.creation.machineId)+ let kept = false+ try {+ const status = await line.request('agent_create_status', { creationId: a.row.creation.creationId }, 8_000)+ const frame = (status.agent ?? {}) as Frame+ if (status.state === 'created' && typeof frame.id === 'string' && frame.id) {+ await recordMade(s, o.where, o.ledger, a.row, frame)+ targets.push({ daemon: line, frame: { ...frame, name: frame.name || a.row.creation.name }, machineId: a.row.creation.machineId,+ machine: here ? o.machine : a.row.creation.machineId.slice(0, 8), yours: true, remote: !here })+ following.splice(following.indexOf(a), 1)+ kept = true+ return+ }+ const now = askedOf(a.row, status)+ if (!now) gave.set(a, 'gone')+ else { a.state = now.state; a.detail = now.detail; if (now.state === 'failed') gave.set(a, 'failed') }+ } finally { if (!here && !kept) line.close() }+ }const deadline = timeoutMs > 0 ? s.now() + timeoutMs : Infinityconst settled = new Map<Target, Settled>()const sawWorking = new Set<Target>()@@ -412,6 +545,14 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Proreturn age > STARTING_MS && looks >= QUIET_LOOKS ? 'idle' : null}for (;;) {+ for (const a of [...following]) {+ if (gave.has(a)) continue+ // Its machine out of reach for a moment (a timeout, a relay): asked again next round, as `ps` keeps it starting.+ await follow(a).catch((error) => {+ if (error instanceof AgentClientError) return+ throw error+ })+ }// One list per machine a round, however many harnesses are waited on there.const lists = new Map<Daemon, Promise<Frame[]>>()for (const t of targets) {@@ -425,23 +566,38 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Pro})if (result) settled.set(t, result)}- const done = flags.has('--any') ? settled.size > 0 : settled.size === targets.length+ const total = targets.length + following.length+ const count = settled.size + gave.size+ const done = flags.has('--any') ? count > 0 : count === totalif (done) break- if (s.now() >= deadline) { for (const t of targets) if (!settled.has(t)) settled.set(t, 'timeout'); break }+ if (s.now() >= deadline) {+ for (const t of targets) if (!settled.has(t)) settled.set(t, 'timeout')+ for (const a of following) if (!gave.has(a)) gave.set(a, 'timeout')+ break+ }await s.sleep(Math.min(s.intervalMs, Math.max(0, deadline - s.now())))}- const results = targets.filter((t) => settled.has(t)).map((t) => ({ name: t.frame.name ?? t.frame.id.slice(0, 8), id: t.frame.id, state: settled.get(t)! }))+ const results: Array<{ name: string; id: string; state: Settled | 'installing' | 'starting'; detail?: string }> = [+ ...targets.filter((t) => settled.has(t)).map((t) => ({ name: t.frame.name ?? t.frame.id.slice(0, 8), id: t.frame.id, state: settled.get(t)! })),+ // Not started yet when the wait ended: said as what it waits for, which is what the agent waits on.+ ...following.filter((a) => gave.has(a)).map((a) => {+ const given = gave.get(a)!+ return { name: askedName(a), id: a.row.creation.creationId, state: given === 'timeout' && a.state !== 'failed' ? a.state : given, detail: a.detail }+ }),+ ]if (flags.has('--json')) s.out(JSON.stringify({ harnesses: results }, null, 1))else for (const r of results) {const next = r.state === 'idle' ? `read it: ${step(s.env, 'show', r.name)}`: r.state === 'needs-input' ? 'it waits for the person (a question or a permission); only the person answers it': r.state === 'timeout' ? `still working; wait again or read it: ${step(s.env, 'show', r.name)}`+ : r.state === 'installing' || r.state === 'starting' ? `${askedLine(s.env, following.find((a) => a.row.creation.creationId === r.id)!)}`+ : r.state === 'failed' ? `it never started: ${r.detail || 'its machine refused it'}`: r.state === 'stopped' ? 'it was stopped' : 'it is gone's.out(`${r.name}: ${r.state} · ${next}`)}const states = results.map((r) => r.state)- return states.includes('timeout') ? EXIT.timeout : states.includes('needs-input') ? EXIT.needsInput- : states.some((x) => x === 'stopped' || x === 'gone') ? EXIT.stopped : EXIT.ok+ return states.some((x) => x === 'timeout' || x === 'installing' || x === 'starting') ? EXIT.timeout : states.includes('needs-input') ? EXIT.needsInput+ : states.some((x) => x === 'stopped' || x === 'gone' || x === 'failed') ? EXIT.stopped : EXIT.ok} finally {for (const t of targets) if (t.remote) t.daemon.close()o.daemon.close()@@ -458,7 +614,27 @@ export function closeCommand(argv: readonly string[], deps: ClientDeps = {}): Prconst o = await opened(s)let t: Target | null = nulltry {- t = await target(s, o, names[0])+ try { t = await target(s, o, names[0]) } catch (error) {+ // Asked for and not started: closing it is not starting it. Cancelled by its creation, which its machine takes only+ // before the launch is claimed (lib/agentCreationReceipt.ts `cancelIntent`).+ const asked = error instanceof AgentClientError && error.code === 'NOT_STARTED' ? askedNamed(o, names[0]) : undefined+ if (!asked) throw error+ const name = askedName(asked), here = asked.row.creation.machineId === o.where.machineId+ const line = here ? o.daemon : await s.open(o.where, asked.row.creation.machineId)+ try {+ const reply = await line.request('agent_create_cancel', { creationId: asked.row.creation.creationId }, 20_000)+ const refused = askedOf(asked.row, reply)+ if (reply.state === 'created' || reply.state === 'unconfirmed') {+ throw new AgentClientError('STARTING', `${name} is starting now, so it was not cancelled. Close it once it has: ${step(s.env, 'close', name)}.`)+ }+ if (refused?.state === 'failed') throw new AgentClientError('NEVER_STARTED', `${name} never started: ${refused.detail || 'its machine refused it'}. Nothing to close.`)+ if (reply.state !== 'cancelled') {+ throw new AgentClientError(typeof reply.error === 'string' ? reply.error : 'NOT_CANCELLED', `${name} could not be cancelled${typeof reply.error === 'string' ? ` (${reply.error})` : ''}. Check it with ${step(s.env, 'ps')}.`)+ }+ } finally { if (!here) line.close() }+ s.out(flags.has('--json') ? JSON.stringify({ name, id: asked.row.creation.creationId, cancelled: true }) : `Cancelled ${name} before it started.`)+ return EXIT.ok+ }const name = t.frame.name ?? t.frame.id.slice(0, 8)if (o.orphan) throw new AgentClientError('NOT_YOURS', ORPHAN)if (o.caller && o.caller.agentId === t.frame.id && t.machineId === o.where.machineId) {@@ -485,6 +661,9 @@ export function closeCommand(argv: readonly string[], deps: ClientDeps = {}): Pr/** Limits on starting harnesses (the design's "Limits"): runaway spawning is the risk. */export const SPAWN_LIMITS = { livePerHarness: 8, livePerMachine: 40, depth: 2, perWindow: 20, windowMs: 10 * 60_000 } as const+/** How long a harness the caller started by a name stops it starting another by that name: a retry, not new work. */+export const DUPLICATE_WITHIN_MS = 10 * 60_000+/** A harness by machine and id, as the limits count the live ones. */const memberKey = (machineId: string, agentId: string): string => `${machineId}/${agentId}`@@ -492,20 +671,23 @@ const memberKey = (machineId: string, agentId: string): string => `${machineId}/* Why [caller] may not start another harness now, or null. [live] holds the live harnesses the limits count: this* machine's, and the caller's on the other machines it reached.*/-export function spawnRefusal(caller: Caller, live: ReadonlySet<string>, ledger: Ledger, localMachineId: string, now: number): string | null {+export function spawnRefusal(caller: Caller, live: ReadonlySet<string>, ledger: Ledger, localMachineId: string, now: number, waiting: readonly Pending[] = []): string | null {if (ledger.depthOf(caller) >= SPAWN_LIMITS.depth) {return 'A harness started this far down may not start more. Do the work yourself, or say so in your answer.'}+ // Harnesses asked for and not started yet ([waiting]) count as running: each starts by itself once its engine is+ // installed, and an agent asking for more meanwhile would otherwise pass every limit until they all started at once.const mine = ledger.childrenOf(caller)const liveMine = new Set(mine.filter((row) => live.has(memberKey(row.child.machineId, row.child.agentId))).map((row) => memberKey(row.child.machineId, row.child.agentId)))- if (liveMine.size >= SPAWN_LIMITS.livePerHarness) {- return `You have ${liveMine.size} harnesses running. Close one you are done with first (harness close <name>).`+ const running = liveMine.size + waiting.length+ if (running >= SPAWN_LIMITS.livePerHarness) {+ return `You have ${running} harnesses running${waiting.length ? ' or starting' : ''}. Close one you are done with first (harness close <name>).`}const machineWide = new Set(ledger.all().filter((row) => row.child.machineId === localMachineId && live.has(memberKey(localMachineId, row.child.agentId))).map((row) => row.child.agentId))- if (machineWide.size >= SPAWN_LIMITS.livePerMachine) {+ if (machineWide.size + waiting.filter((row) => row.creation.machineId === localMachineId).length >= SPAWN_LIMITS.livePerMachine) {return `Agents have ${machineWide.size} harnesses running on this machine, the most allowed. Close some first.`}- if (mine.filter((row) => now - row.at < SPAWN_LIMITS.windowMs).length >= SPAWN_LIMITS.perWindow) {+ if (mine.filter((row) => now - row.at < SPAWN_LIMITS.windowMs).length + waiting.filter((row) => now - row.at < SPAWN_LIMITS.windowMs).length >= SPAWN_LIMITS.perWindow) {return `You started ${SPAWN_LIMITS.perWindow} harnesses in 10 minutes. Wait, or work with the ones you have.`}return null@@ -579,9 +761,43 @@ export async function agentOrigin(deps: ClientDeps = {}, record: Rpc = messagesR// A harness in a pane here: the new one is opened beside it in the windows. An agent outside Harness has no pane....(caller.outside ? {} : { parentAgentId: caller.agentId }),check: async () => {- const refusal = spawnRefusal(caller, await liveFor(s, o, caller), o.ledger, o.where.machineId, s.now())+ const refusal = spawnRefusal(caller, await liveFor(s, o, caller), o.ledger, o.where.machineId, s.now(),+ o.asked.filter((a) => a.state !== 'failed').map((a) => a.row))if (refusal) throw new AgentClientError('SPAWN_LIMIT', refusal)},+ existing: async (name, asking) => {+ if (!name?.trim()) return null+ const wanted = name.trim().toLowerCase()+ // The same name for the same agent on the same machine: a retry. Another machine or agent is other work.+ // A store harness (owner/name) is asked for by its id and recorded by the engine it runs on: the machine decides.+ const same = (machineId: string, engine?: string) => machineId === asking.machineId && (!engine || asking.engine.includes('/') || engine === asking.engine)+ // Still on its way: an agent whose call to `harness new` timed out (an MCP client's minute) and asked again got a+ // second harness for the same work once both launches went ahead.+ const asked = o.asked.filter((a) => a.state !== 'failed' && a.row.creation.name.toLowerCase() === wanted+ && same(a.row.creation.machineId, a.row.creation.engine)).at(-1)+ if (asked) {+ const called = asked.row.creation.name+ return { name: called, machineId: asked.row.creation.machineId, state: 'starting',+ note: `"${called}" is already starting: ${asked.state === 'installing' ? `Harness is installing ${engineName(asked.row.creation.engine)}` : asked.detail.replace(/\.$/, '') || 'it has not started yet'}. `+ + `It starts by itself; wait for it with ${step(s.env, 'wait', called)}. Do not start it again.` }+ }+ // Started by the caller a few minutes ago and running: the same retry, a little later.+ const engineOf = (row: Started) => row.child.machineId === o.where.machineId ? o.frames.find((f) => f.id === row.child.agentId)?.engine : undefined+ const recent = o.ledger.childrenOf(caller).filter((row) => s.now() - row.at < DUPLICATE_WITHIN_MS && row.child.name.toLowerCase() === wanted+ && same(row.child.machineId, engineOf(row)))+ if (!recent.length) return null+ const live = await liveFor(s, o, caller)+ const running = recent.findLast((row) => live.has(memberKey(row.child.machineId, row.child.agentId)))+ if (!running) return null+ const called = running.child.name, minutes = Math.max(1, Math.round((s.now() - running.at) / 60_000))+ return { name: called, machineId: running.child.machineId, agentId: running.child.agentId, state: 'running',+ note: `"${called}" is already running: you started it ${minutes} min ago. Wait for it with ${step(s.env, 'wait', called)} `+ + `or read it with ${step(s.env, 'show', called)}. Do not start it again; to start a new one by that name, close it first (${step(s.env, 'close', called)}).` }+ },+ pending: (machineId, creation) => {+ o.ledger.append({ at: s.now(), by: { machineId: caller.machineId, agentId: caller.agentId, name: caller.name, engine: caller.engine },+ creation: { machineId, ...creation }, depth: o.ledger.depthOf(caller) + 1 })+ },prompt: (text, machineId) => {// Said once, at the top: the task is from an agent, not the person (a teammate's tmux paste read as the// owner's). It reads the answer itself (`show`): an invitation to reply had the first eval's agent send its@@ -604,17 +820,17 @@ export async function agentOrigin(deps: ClientDeps = {}, record: Rpc = messagesRconst room = MAX_FIRST_PROMPT_CHARS - header.length - lead.length - 1return `${header}${lead}${clip(text, room)}`},- created: async (machineId, agent) => {+ created: async (machineId, agent, creationId) => {const id = typeof agent.id === 'string' ? agent.id : ''if (!id) return nullconst name = typeof agent.name === 'string' ? agent.name : ''const row: Started = {at: s.now(),by: { machineId: caller.machineId, agentId: caller.agentId, name: caller.name, engine: caller.engine },- child: { machineId, agentId: id, name },+ child: { machineId, agentId: id, name, ...(creationId ? { creationId } : {}) },depth: o.ledger.depthOf(caller) + 1,}- o.ledger.append(row)+ o.ledger.record(row)if (machineId === o.where.machineId) return null// The other machine keeps the line too: there the new harness's limits and depth start from it. Without it a// harness started on another machine was one the person started there, and a chain hopping between machines haddiff --git a/cli/src/agentClient/ledger.spec.ts b/cli/src/agentClient/ledger.spec.tsindex 5c681d785..b48328980 100644--- a/cli/src/agentClient/ledger.spec.ts+++ b/cli/src/agentClient/ledger.spec.ts@@ -2,7 +2,7 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSyncimport { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'-import { Ledger, ledgerPath, parseStarted, ROTATE_BYTES, type Started } from './ledger.js'+import { Ledger, ledgerPath, parsePending, parseStarted, PENDING_WITHIN_MS, ROTATE_BYTES, type Pending, type Started } from './ledger.js'const dirs: string[] = []const fresh = (): Ledger => {@@ -69,4 +69,32 @@ describe('the ledger of who started which harness', () => {const bare = { at: 1, depth: 1, by: { machineId: 'm', agentId: 'a' }, child: { machineId: 'm', agentId: 'b' } }expect(parseStarted(JSON.stringify(bare))).toEqual({ at: 1, depth: 1, by: { machineId: 'm', agentId: 'a', name: '', engine: '' }, child: { machineId: 'm', agentId: 'b', name: '' } })})++ it('keeps a harness asked for and not started until it has a started line, for half an hour, one line a creation', () => {+ const ledger = fresh()+ const lead = { machineId: 'm', agentId: 'lead' }+ const asked = (creationId: string, at = 10, name = 'cx'): Pending => ({ at, depth: 1, by: { ...lead, name: 'lead', engine: 'claude' },+ creation: { machineId: 'm', creationId, name, engine: 'codex' } })+ ledger.append(asked('c1')); ledger.append(asked('c1', 20, 'cx2')); ledger.append(asked('c2')); ledger.append(asked('c3', 10 - PENDING_WITHIN_MS))+ ledger.append(row('other', 'x'))+ expect(ledger.pendingOf(lead, 10).map((p) => [p.creation.creationId, p.creation.name])).toEqual([['c1', 'cx2'], ['c2', 'cx']])+ expect(ledger.pendingOf({ machineId: 'm', agentId: 'other' }, 10)).toEqual([])+ // Started: its line names the creation, and it is no longer pending. Older readers see only started lines.+ ledger.append({ ...row('lead', 'k1'), child: { machineId: 'm', agentId: 'k1', name: 'cx', creationId: 'c1' } })+ expect(ledger.pendingOf(lead, 10).map((p) => p.creation.creationId)).toEqual(['c2'])+ expect(ledger.all().map((r) => r.child.agentId)).toEqual(['x', 'k1'])+ expect(ledger.parentOf({ machineId: 'm', agentId: 'k1' })?.child.creationId).toBe('c1')+ // Recorded once, whichever verb sees it made first.+ ledger.record({ ...row('lead', 'k1'), child: { machineId: 'm', agentId: 'k1', name: 'cx', creationId: 'c1' } })+ ledger.record(row('lead', 'k2'))+ expect(ledger.all().map((r) => r.child.agentId)).toEqual(['x', 'k1', 'k2'])+ })++ it('checks every pending line it reads', () => {+ const line = { at: 1, depth: 1, by: { machineId: 'm', agentId: 'a' }, creation: { machineId: 'm', creationId: 'c' } }+ expect(parsePending(JSON.stringify(line))).toEqual({ at: 1, depth: 1, by: { machineId: 'm', agentId: 'a', name: '', engine: '' }, creation: { machineId: 'm', creationId: 'c', name: '', engine: '' } })+ for (const bad of ['', 'null', JSON.stringify({ ...line, depth: 0 }), JSON.stringify({ ...line, creation: { machineId: 'm' } }), JSON.stringify({ ...line, creation: undefined })]) {+ expect(parsePending(bad), bad).toBeNull()+ }+ })})diff --git a/cli/src/agentClient/ledger.ts b/cli/src/agentClient/ledger.tsindex 03d44f8e8..1876f7ee3 100644--- a/cli/src/agentClient/ledger.ts+++ b/cli/src/agentClient/ledger.ts@@ -6,6 +6,10 @@* Read by `harness ps` (who started each), and by `new` and `close` (limits, depth, and which harnesses an agent* may close). It never lets two harnesses message each other: only a tab with Agent Messages on does (owner,* 2026-10-11). It is a collaboration scope, not a sandbox: any process of this user can write the file.+ *+ * A harness asked for and not started yet (its engine still installing) has a line of its own, `Pending`, with the+ * machine's creation id: it starts by itself later, after `harness new` has answered, and is then recorded as started+ * by whichever verb of the agent's first sees it made (agentClient/commands.ts `opened`). Older readers skip the line.*/import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync } from 'node:fs'import { dirname, join } from 'node:path'@@ -15,12 +19,23 @@ export interface Started {at: number/** The harness that ran `harness new`. */by: LedgerMember & { name: string; engine: string }- /** The harness it started. */- child: LedgerMember & { name: string }+ /** The harness it started, and the creation it was asked for by when that was saved first (`Pending`). */+ child: LedgerMember & { name: string; creationId?: string }/** 1 for a harness a person's harness started, 2 for one that harness started. */depth: number}+/** A harness asked for that has not started yet: its creation on [creation.machineId], and the name it was given. */+export interface Pending {+ at: number+ by: LedgerMember & { name: string; engine: string }+ creation: { machineId: string; creationId: string; name: string; engine: string }+ depth: number+}++/** How long a pending line is asked after. An install ends within twenty minutes (engines/kit/nativeInstall.ts). */+export const PENDING_WITHIN_MS = 30 * 60_000+/** The file, in the daemon's data folder. */export const ledgerPath = (dataDir: string): string => join(dataDir, 'agent-client', 'started.jsonl')@@ -41,7 +56,23 @@ export function parseStarted(line: string): Started | null {return {at: v.at,by: { machineId: by.machineId as string, agentId: by.agentId as string, name: String(by.name ?? ''), engine: String(by.engine ?? '') },- child: { machineId: child.machineId as string, agentId: child.agentId as string, name: String(child.name ?? '') },+ child: { machineId: child.machineId as string, agentId: child.agentId as string, name: String(child.name ?? ''),+ ...(typeof child.creationId === 'string' && child.creationId ? { creationId: child.creationId } : {}) },+ depth: v.depth,+ }+}++export function parsePending(line: string): Pending | null {+ let v: Record<string, unknown>+ try { v = JSON.parse(line) } catch { return null }+ const creation = v?.creation as Record<string, unknown> | undefined+ if (!v || typeof v !== 'object' || typeof v.at !== 'number' || !member(v.by) || typeof v.depth !== 'number' || v.depth < 1+ || !creation || typeof creation.machineId !== 'string' || !creation.machineId || typeof creation.creationId !== 'string' || !creation.creationId) return null+ const by = v.by as unknown as Record<string, unknown>+ return {+ at: v.at,+ by: { machineId: by.machineId as string, agentId: by.agentId as string, name: String(by.name ?? ''), engine: String(by.engine ?? '') },+ creation: { machineId: creation.machineId, creationId: creation.creationId, name: String(creation.name ?? ''), engine: String(creation.engine ?? '') },depth: v.depth,}}@@ -49,7 +80,7 @@ export function parseStarted(line: string): Started | null {const same = (a: LedgerMember, b: LedgerMember): boolean => a.machineId === b.machineId && a.agentId === b.agentIdexport class Ledger {- private cache: { key: string; rows: Started[] } | null = null+ private cache: { key: string; rows: Started[]; pending: Pending[] } | null = nullconstructor(readonly path: string) {}/** Where the older lines went when the file passed its size. */@@ -57,22 +88,30 @@ export class Ledger {/** Every line, oldest first: the previous file's, then this one's. An unreadable file is an empty one. Read again* only when either changed. */- all(): Started[] {+ all(): Started[] { return this.read().rows }++ private read(): { rows: Started[]; pending: Pending[] } {const files = [this.previous, this.path].map((path) => { try { const st = statSync(path); return { path, key: `${st.mtimeMs}:${st.size}` } } catch { return null } })const key = files.map((f) => f?.key ?? '-').join('|')- if (this.cache?.key === key) return this.cache.rows- const rows: Started[] = []+ if (this.cache?.key === key) return this.cache+ const rows: Started[] = [], pending: Pending[] = []for (const file of files) {if (!file) continuelet text = ''try { text = readFileSync(file.path, 'utf8') } catch { continue }- for (const line of text.split('\n')) { const row = line ? parseStarted(line) : null; if (row) rows.push(row) }+ for (const line of text.split('\n')) {+ if (!line) continue+ const row = parseStarted(line)+ if (row) { rows.push(row); continue }+ const asked = parsePending(line)+ if (asked) pending.push(asked)+ }}- this.cache = { key, rows }- return rows+ this.cache = { key, rows, pending }+ return this.cache}- append(row: Started): void {+ append(row: Started | Pending): void {mkdirSync(dirname(this.path), { recursive: true })// One short line with O_APPEND: two agents starting harnesses at once never interleave.appendFileSync(this.path, `${JSON.stringify(row)}\n`, { mode: 0o600 })@@ -81,6 +120,12 @@ export class Ledger {try { if (statSync(this.path).size > ROTATE_BYTES) renameSync(this.path, this.previous) } catch { /* rotated by another */ }}+ /** Appends [row] unless [row.child] already has its line: a harness asked for and started later is recorded by+ * whichever of the agent's verbs sees it made first, and two at once would each count it toward the limits. */+ record(row: Started): void {+ if (!this.parentOf(row.child)) this.append(row)+ }+/** The line that says who started [m], or null when the person did. */parentOf(m: LedgerMember): Started | null {return this.all().findLast((row) => same(row.child, m)) ?? null@@ -88,11 +133,24 @@ export class Ledger {/** The harnesses [m] started, newest last. */childrenOf(m: LedgerMember): Started[] {- return this.all().filter((row) => same(row.by, m))+ // One a harness, its latest line: two verbs recording the same start at once (`record`) both write it, and a child+ // counted twice met the limits early and matched no name (two rows for one).+ const children = new Map(this.all().filter((row) => same(row.by, m)).map((row) => [`${row.child.machineId}/${row.child.agentId}`, row]))+ return [...children.values()].sort((a, b) => a.at - b.at)}/** 0 for a harness the person started. */depthOf(m: LedgerMember): number {return this.parentOf(m)?.depth ?? 0}++ /** What [m] asked for in the last half hour that has no started line yet, newest last; anyone's when [m] is null. */+ pendingOf(m: LedgerMember | null, now: number): Pending[] {+ const { rows, pending } = this.read()+ const started = new Set(rows.map((row) => row.child.creationId).filter(Boolean))+ // One per creation, its latest line: a line written twice is one harness asked for.+ const asked = new Map(pending.filter((row) => (!m || same(row.by, m)) && now - row.at < PENDING_WITHIN_MS && !started.has(row.creation.creationId))+ .map((row) => [row.creation.creationId, row]))+ return [...asked.values()]+ }}diff --git a/cli/src/agentClient/mcp.spec.ts b/cli/src/agentClient/mcp.spec.tsindex 118f19147..dade714ba 100644--- a/cli/src/agentClient/mcp.spec.ts+++ b/cli/src/agentClient/mcp.spec.ts@@ -60,7 +60,7 @@ describe('harness mcp', () => {['new', 'claude', '/work/here/app', '--name', 'reviewer', '--task', 'review it\nall of it'],['new', 'codex', '@mini', '/abs', '--name', 'gpu', '--task', 'train'],['new', 'claude', '~/p', '--name', 'n', '--task', 'x'],- ['wait', 'a,b', '--timeout', '120s'], ['wait', 'a', '--any', '--timeout', '600s'], ['wait', 'a', '--timeout', '2s'],+ ['wait', 'a,b', '--timeout', '45s'], ['wait', 'a', '--any', '--timeout', '600s'], ['wait', 'a', '--timeout', '2s'],['show', 'a'], ['show', 'a', '--chars', '99'],['send', 'a', 'also the footer'],['close', 'a'], ['close', 'a', '--now'],diff --git a/cli/src/agentClient/mcp.ts b/cli/src/agentClient/mcp.tsindex 7026dc3a9..b90662f26 100644--- a/cli/src/agentClient/mcp.ts+++ b/cli/src/agentClient/mcp.ts@@ -29,8 +29,10 @@ List first (harness_list). Put everything in the task: starting a harness does nName every harness. Then wait for it (harness_wait), read its answer (harness_read), and close it when you are done (harness_close). Never ask a harness to publish, deploy, delete or push.`-/** How long `harness_wait` waits when not told: within what MCP clients allow a call. */-const WAIT_DEFAULT_S = 120+/** How long `harness_wait` waits when not told: within what MCP clients allow a call. Codex ends one at 60 s unless its+ * config says otherwise (`tool_timeout_sec`, developers.openai.com/codex/mcp), so 120 s ended every long wait as an+ * error there; the agent calls again for more. */+const WAIT_DEFAULT_S = 45const WAIT_MAX_S = 600interface Tool {@@ -55,7 +57,7 @@ export const TOOLS: Tool[] = [},{name: 'harness_start',- description: 'Start a new harness: an agent in a session of its own, working on [task] in an existing [folder], or in a new [project] Harness makes for it. Returns at once; wait for it with harness_wait and read its answer with harness_read.',+ description: 'Start a new harness: an agent in a session of its own, working on [task] in an existing [folder], or in a new [project] Harness makes for it. Returns within a minute; wait for it with harness_wait and read its answer with harness_read. If its agent is still being installed then, it starts by itself: follow it by its name, and never start it again.',inputSchema: schema({task: { type: 'string', description: 'The whole task, as you would write it to a colleague: what to do, where, and what to answer with.' },folder: { type: 'string', description: 'An existing folder to work in: an absolute path, or one relative to where this server runs. Claude Code and Codex ask the person to trust a folder Harness did not make, and wait until they answer.' },diff --git a/cli/src/agentClient/model.ts b/cli/src/agentClient/model.tsindex 490e1d4c0..62b8204a4 100644--- a/cli/src/agentClient/model.ts+++ b/cli/src/agentClient/model.ts@@ -29,7 +29,8 @@ export interface Caller extends LedgerMember {outside?: boolean}-export type State = 'working' | 'idle' | 'needs-input' | 'stopped' | 'offline' | 'unknown'+/** `installing`, `starting`, `failed`: a harness asked for that has not started (commands.ts `Asked`). */+export type State = 'working' | 'idle' | 'needs-input' | 'stopped' | 'offline' | 'unknown' | 'installing' | 'starting' | 'failed'export interface Row {name: stringdiff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.tsindex 123bac29c..c02e275f5 100644--- a/cli/src/lib/newCommand.spec.ts+++ b/cli/src/lib/newCommand.spec.ts@@ -330,6 +330,88 @@ describe('harness new: the daemon', () => {expect(d.err).toEqual(['Codex is installed but cannot run: /usr/bin/env: ‘node’: No such file or directory'])})+ it('answers an agent within 40 seconds, leaving a harness still installing to start by itself, recorded by its name', async () => {+ // An MCP client ends a tool call at a minute (Codex's default tool_timeout_sec): a Codex install takes about that.+ const installing = { state: 'pending', held: { service: 'install', detail: 'Installing Codex. The harness starts once it is installed.' } }+ const pending: Array<[string, Record<string, unknown>]> = []+ const origin = { check: async () => {}, prompt: (text: string) => text, created: async () => null, next: () => '', existing: async () => null,+ pending: (machineId: string, creation: Record<string, unknown>) => { pending.push([machineId, creation]) } }+ const run = async (env: NodeJS.ProcessEnv, json = false) => {+ let clock = 0+ const socket = new FakeSocket((frame) => frame.type === 'agent_create' || frame.type === 'agent_create_status' ? installing : frame.type === 'agent_create_cancel' ? { state: 'cancelled' } : null)+ const d = deps(['codex', '--name', 'cx', ...(json ? ['--json'] : []), '--', 'Reply with pong'], socket,+ { origin: async () => origin, env, now: () => clock, sleep: async (ms) => { clock += ms } })+ expect(await newCommand(d)).toBe(0)+ expect(clock).toBe(40_000)+ expect(socket.sent.some((f) => f.type === 'agent_create_cancel')).toBe(false)+ return { d, socket }+ }+ const mcp = await run({ HARNESS_VIA_MCP: '1' })+ expect(mcp.d.out).toEqual(['Harness is installing Codex; the harness "cx" starts by itself once it is installed. '+ + 'Check on it with harness_list or harness_wait (names: "cx"); do not start it again.'])+ expect(mcp.d.err).toEqual([])+ const creationId = mcp.socket.sent.find((f) => f.type === 'agent_create')!.payload.creationId+ expect(pending).toEqual([['m2', { creationId, name: 'cx', engine: 'codex' }]])+ const shell = await run({})+ expect(shell.d.err).toEqual(['Installing Codex. The harness starts once it is installed.'])+ expect(shell.d.out).toEqual(['Harness is installing Codex; the harness "cx" starts by itself once it is installed. '+ + 'Check on it with harness ps or harness wait cx; do not start it again.'])+ const json = await run({ HARNESS_VIA_MCP: '1' }, true)+ expect(JSON.parse(json.d.out[0]!)).toMatchObject({ ok: true, pending: true, machineId: 'm2', name: 'cx' })+ expect(json.d.err).toEqual([])+ })++ it('names no harness it was given no name for, and asks for at least ten seconds however long the setup took', async () => {+ let clock = 0+ const installing = { state: 'pending', held: { service: 'install', detail: 'Installing Codex.' } }+ // Forty seconds gone before the machine answered: a slow line to another machine.+ const origin = { check: async () => { clock += 45_000 }, prompt: (text: string) => text, created: async () => null, next: () => '', pending: () => {} }+ let asks = 0+ const socket = new FakeSocket((frame) => frame.type === 'agent_create' ? installing : frame.type === 'agent_create_status' ? (asks++, installing) : null)+ const d = deps(['codex'], socket, { origin: async () => origin, now: () => clock, sleep: async (ms) => { clock += ms } })+ expect(await newCommand(d)).toBe(0)+ expect(asks).toBe(5)+ expect(d.out).toEqual(['Harness is installing Codex; the harness starts by itself once it is installed. Check on it with harness ps; do not start it again.'])+ })++ it('still cancels an agent\'s launch held for anything but an install, at 40 seconds', async () => {+ let clock = 0+ const origin = { check: async () => {}, prompt: (text: string) => text, created: async () => null, next: () => '', pending: () => {} }+ const socket = new FakeSocket((frame) => frame.type === 'agent_create_cancel' ? { state: 'cancelled' }+ : frame.type === 'agent_create' || frame.type === 'agent_create_status' ? { state: 'pending', held: { service: 'native', detail: 'Waiting.' } } : null)+ const d = deps(['codex', '--name', 'cx'], socket, { origin: async () => origin, now: () => clock, sleep: async (ms) => { clock += ms } })+ expect(await newCommand(d)).toBe(1)+ expect(d.err.at(-1)).toBe('Harness did not start the harness in time: Waiting. The request is cancelled, so it will not start later.')+ })++ it('answers an agent asking again for a harness it already has with that one, and asks the machine nothing', async () => {+ const socket = new FakeSocket(() => null)+ const note = '"cx" is already starting: Harness is installing Codex. It starts by itself; wait for it with harness wait cx. Do not start it again.'+ const asked: unknown[] = []+ const origin = { check: async () => { throw new Error('not reached') }, prompt: (text: string) => text, created: async () => null, next: () => '',+ existing: async (name: string | null, asking: { machineId: string; engine: string }) => {+ asked.push(asking)+ return name === 'cx' ? { name: 'cx', machineId: 'm2', state: 'starting' as const, note } : null+ } }+ const d = deps(['codex', '--name', 'cx', '--', 'again'], socket, { origin: async () => origin })+ expect(await newCommand(d)).toBe(0)+ expect(d.out).toEqual([note])+ expect(socket.sent).toEqual([])+ const json = deps(['codex', '--name', 'cx', '--json'], socket, { origin: async () => origin })+ expect(await newCommand(json)).toBe(0)+ expect(JSON.parse(json.out[0]!)).toEqual({ ok: true, existing: true, name: 'cx', machineId: 'm2', state: 'starting', note })+ expect(asked).toEqual([{ machineId: 'm2', engine: 'codex' }, { machineId: 'm2', engine: 'codex' }])+ })++ it('records the creation a harness was asked by when the machine made it', async () => {+ const created: unknown[][] = []+ const origin = { check: async () => {}, prompt: (text: string) => text, next: () => '', pending: () => {},+ created: async (...args: unknown[]) => { created.push(args); return null } }+ const socket = new FakeSocket((frame) => frame.type === 'agent_create' ? { state: 'created', agent: { id: 'k1', name: 'cx' } } : null)+ expect(await newCommand(deps(['codex', '--name', 'cx'], socket, { origin: async () => origin }))).toBe(0)+ expect(created).toEqual([['m2', { id: 'k1', name: 'cx' }, socket.sent.find((f) => f.type === 'agent_create')!.payload.creationId]])+ })+it('reads the folder off the harness the machine made', async () => {const socket = new FakeSocket((frame) => frame.type === 'agent_create'? { state: 'created', agent: { id: 'a1', name: 'fixer', project: { cwd: '/work/repo/.worktrees/x' } } } : null)diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.tsindex c72183f70..05ad29a20 100644--- a/cli/src/lib/newCommand.ts+++ b/cli/src/lib/newCommand.ts@@ -1,7 +1,7 @@import { randomUUID } from 'node:crypto'import { readdir, readFile, realpath } from 'node:fs/promises'import { dirname, isAbsolute, join, resolve } from 'node:path'-import { VIA_MCP_ENV } from '../agentClient/commands.js'+import { step, VIA_MCP_ENV } from '../agentClient/commands.js'import { folderTrust } from '../engines/launchPrep.js'import { ENGINES, type AgentEngine } from '../engines/types.js'import { engineName } from '../messages/model.js'@@ -239,11 +239,15 @@ export interface NewCommandDeps {/** Who is starting it, when an agent runs this from its pane (agentClient/commands.ts `agentOrigin`). */origin?: () => Promise<NewOrigin | null>sleep?: (ms: number) => Promise<void>+ now?: () => number/** The caller's environment: whether `harness mcp` runs this, and where its engines keep their folder trust.* This process's when left out. */env?: NodeJS.ProcessEnv}+/** A harness the caller already has by the name it asks for again (`NewOrigin.existing`). */+export interface ExistingHarness { name: string; machineId: string; state: 'starting' | 'running'; agentId?: string; note: string }+/** An agent starting a harness (docs/design/2026-10-11-agent-client.md): its limits, the header its task carries,* and the record of who started what. */export interface NewOrigin {@@ -252,7 +256,12 @@ export interface NewOrigin {/** The first message as the new harness reads it. */prompt(text: string, machineId: string): string/** Records it; a warning to print when the record could not be kept everywhere. */- created(machineId: string, agent: Record<string, unknown>): Promise<string | null>+ created(machineId: string, agent: Record<string, unknown>, creationId?: string): Promise<string | null>+ /** The caller's harness by [name] for the same agent on the same machine, already running or still on its way, said+ * instead of starting a second; else null. */+ existing?(name: string | null, asking: { machineId: string; engine: string }): Promise<ExistingHarness | null>+ /** Records a harness asked for that has not started yet, so the caller follows it by name once this has answered. */+ pending?(machineId: string, creation: { creationId: string; name: string; engine: string }): void/** How to read, wait for and message what was started. */next(agent: Record<string, unknown>): string/** The caller's own harness, by agent id, when it is one on this computer: a harness started here records it, and the@@ -260,6 +269,9 @@ export interface NewOrigin {parentAgentId?: string}+/** How long `harness new` takes at most to answer an agent: within Codex's one-minute MCP tool timeout, with room. */+export const AGENT_ANSWER_MS = 40_000+const ERRORS: Record<string, string> = {INVALID_CWD: 'That folder does not exist on the machine.',INVALID_ENGINE: 'That agent is not one this machine knows.',@@ -400,9 +412,10 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {return 1}const env = deps.env ?? process.env+ const clock = deps.now ?? Date.now+ const began = clock()try {const origin = (await deps.origin?.()) ?? null- await origin?.check()let machineId = deps.localMachineIdlet machineLabel = 'this computer'let local = true@@ -416,6 +429,15 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {deps.error('This computer is not signed in to Harness. Run `harness login`.')return 1}+ // An agent asking again for a harness it already has, by its name, for the same agent on the same machine: answered+ // with that one, never a second. The person at a terminal has no origin and is never stopped here.+ const already = await origin?.existing?.(args.name, { machineId, engine: args.agent })+ if (already) {+ const { note, ...harness } = already+ deps.output(args.json ? JSON.stringify({ ok: true, existing: true, ...harness, note }) : note)+ return 0+ }+ await origin?.check()const session = await daemonSession(deps, machineId)try {let cwd = args.cwd@@ -468,6 +490,12 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {...newAgentPayload(asked, cwd, baseEngine), ...(origin ? { startedBy: 'agent' } : {}), ...(parent ? { parentAgentId: parent } : {}),}let result = await session.request('agent_create', payload)+ const creationId = String(payload.creationId)+ // Recorded before any waiting: an agent's call that is cut off (a tool's timeout) leaves a harness that may still+ // start, and it is then the agent's, by name, for `ps`, `wait` and the check above.+ if (origin && (result.state === 'pending' || result.state === 'unconfirmed')) {+ origin.pending?.(machineId, { creationId, name: args.name ?? '', engine: String(payload.engine) })+ }// A launch the daemon holds (a native launch waiting its turn) is still on its way: asked after until it is not,// for a minute. Given up on at once, it could start later with an agent's task and no record of who started it// (the review of #1180). What it waits for is said as it changes: the daemon's own words, which used to stay in@@ -476,11 +504,17 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {// and the launch then gets its minute: a minute in all ended a Codex install as it finished (a fresh Ubuntu VM,// 2026-10-12, where it took about that).const installing = (status: Record<string, unknown>) => (status.held as { service?: unknown } | undefined)?.service === 'install'+ // An agent is answered within AGENT_ANSWER_MS, install or not: MCP clients end a tool call at a minute (Codex's+ // default `tool_timeout_sec`), and shell tools have limits of their own. A call cut off left the agent with nothing,+ // and one that asked again got a second harness.+ // At least ten seconds of asking, however long the setup took: a slow line to another machine left none.+ const answerBy = Math.max(began + AGENT_ANSWER_MS, clock() + 10_000)let said = '', polls = 30- for (let i = 0; i < polls && (result.state === 'pending' || result.state === 'unconfirmed'); i++) {+ for (let i = 0; i < polls && (result.state === 'pending' || result.state === 'unconfirmed') && (!origin || clock() < answerBy); i++) {if (installing(result)) polls = Math.min(180, Math.max(polls, i + 30))const reason = holdReason(result)- if (reason && reason !== said && !args.json) deps.error(reason)+ // Not under `harness mcp`: an MCP client sees only the whole answer, which says it, after the result.+ if (reason && reason !== said && !args.json && env[VIA_MCP_ENV] !== '1') deps.error(reason)said = reason || saidawait (deps.sleep ?? ((ms: number) => new Promise((done) => setTimeout(done, ms))))(2_000)result = await session.request('agent_create_status', { creationId: payload.creationId })@@ -488,11 +522,20 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {// Still held after a minute: cancelled, so it never starts later, task and all, with nobody waiting for it.// The daemon takes a cancel only before the launch is claimed (lib/agentCreationReceipt.ts `cancelIntent`) and// otherwise answers what became of it, which is then the answer here.+ // An agent's harness still installing its engine is left to start by itself, and the agent told how to follow it:+ // cancelled, the install would be wasted and the agent would only ask again.+ if (origin && result.state === 'pending' && installing(result)) {+ const name = args.name?.trim() ?? ''+ const note = `Harness is installing ${engineName(String(payload.engine))}; the harness ${name ? `"${name}" ` : ''}starts by itself once it is installed. `+ + `Check on it with ${name ? `${step(env, 'ps')} or ${step(env, 'wait', name)}` : step(env, 'ps')}; do not start it again.`+ deps.output(args.json ? JSON.stringify({ ok: true, pending: true, machineId, creationId, name, note }) : note)+ return 0+ }if (result.state === 'pending') {const reason = holdReason(result) || saidconst install = installing(result)const why = install ? `Harness is still installing ${engineName(String(payload.engine))}.`- : `Harness did not start the harness ${polls > 30 ? 'in time' : 'within a minute'}${reason ? `: ${reason}` : '.'}`+ : `Harness did not start the harness ${polls > 30 || origin ? 'in time' : 'within a minute'}${reason ? `: ${reason}` : '.'}`const cancelled = await session.request('agent_create_cancel', { creationId: payload.creationId }).catch(() => null)if (cancelled?.state === 'cancelled') {throw new Error(`${why} ${install ? 'Run the same command again in a minute; this request is cancelled' : 'The request is cancelled'}, `@@ -517,7 +560,7 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {: `Harness could not confirm the harness started (${String(result.state)}). Check with \`harness ps\` before starting another.`)}const agent = (result.agent ?? {}) as Record<string, unknown>- const warning = await origin?.created(machineId, agent)+ const warning = await origin?.created(machineId, agent, creationId)if (warning) deps.error(warning)if (args.json) deps.output(JSON.stringify({ ok: true, machineId, agent, ...(trustNote ? { note: trustNote } : {}) }))else {