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
Every agent command ends with Next; refusals exit 5; an agent's ps shows its own first (#1354)
lingrd07528a2666a4
diff --git a/cli/e2e/agentClient.e2e.ts b/cli/e2e/agentClient.e2e.tsindex 3bed42543..45a1f27ab 100644--- a/cli/e2e/agentClient.e2e.ts+++ b/cli/e2e/agentClient.e2e.ts@@ -131,8 +131,8 @@ describe('Harness for agents, end to end', () => {// It starts a harness with a task, which reads who sent it, in a project Harness makes for it.const started = await run('new', 'claude', 'kid', '--name', 'kid', '--', 'hello kid')expect(started.code, started.err).toBe(0)- 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).toContain(`kid on this computer: starting. Claude Code, in ${join(d.env.HOME!, 'harnesses', 'kid')}.`)+ expect(started.out).toContain('Next: harness wait kid (until it has answered; then read it: harness show kid)')expect(started.out).not.toContain('harness send')// 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)@@ -144,8 +144,7 @@ describe('Harness for agents, end to end', () => {expect(waited.out.trim()).toBe('kid: idle · read it: harness show kid')const shown = await run('show', 'kid')expect(shown.code, shown.err).toBe(0)- expect(shown.out).toContain('kid · Claude Code · ')- expect(shown.out).toContain('· idle · started by you')+ expect(shown.out).toMatch(/^kid on .+: idle · Claude Code · started by you\n/)expect(shown.out).toContain('asked: [from lead · Claude Code · ')expect(shown.out).toContain('the harness that started you. It reads your answer itself.]')expect(shown.out).not.toContain('harness send')@@ -175,15 +174,16 @@ describe('Harness for agents, end to end', () => {// It closes what it started, and only that; the harness it started may not close it.const own = await run('close', 'lead')- expect(own.code).toBe(1)+ // Refused, not failed: exit 5.+ expect(own.code).toBe(5)expect(own.err).toContain('That is your own harness.')const fromKid = await harness(d, String(kid.tmuxPane), ['close', 'lead'])- expect(fromKid.code, fromKid.out).toBe(1)+ expect(fromKid.code, fromKid.out).toBe(5)expect(fromKid.err).toContain('You did not start lead')await run('wait', 'kid', '--timeout', '2m')const closed = await run('close', 'kid')expect(closed.code, closed.err).toBe(0)- expect(closed.out.trim()).toBe('Closed kid. Its conversation is kept.')+ expect(closed.out.trim()).toMatch(/^kid on .+: closed\. Its conversation is kept; the person can resume it\.\nNext: nothing; you have 0 open of 4\.$/)const after = await run('ps', '--all', '--json')expect(JSON.parse(after.out).harnesses).toEqual(expect.arrayContaining([expect.objectContaining({ name: 'kid', state: 'stopped', startedBy: 'you' })]))@@ -234,7 +234,7 @@ describe('Harness for agents, end to end', () => {// One level down: the harness lead started may not start one itself, and nothing is started.const deeper = await harness(d, String(kid.tmuxPane), ['new', 'claude', 'deeper', '--name', 'deeper', '--', 'hello deeper'])- expect(deeper.code, deeper.out).toBe(1)+ expect(deeper.code, deeper.out).toBe(5)expect(deeper.err.trim()).toBe('A harness another agent started may not start harnesses itself. Do the work yourself, or say in your answer what else is needed.')expect((await list(true)).some((a) => a.name === 'deeper')).toBe(false)@@ -242,9 +242,9 @@ describe('Harness for agents, end to end', () => {const waited = await harness(d, String(first.tmuxPane), ['wait', 'kid', '--timeout', '2m'])expect(waited.code, waited.out + waited.err).toBe(0)const shown = await harness(d, String(first.tmuxPane), ['show', 'kid'])- expect(shown.out.trim().split('\n').at(-1)).toBe('Close it once you have what you need: harness close kid')+ expect(shown.out.trim().split('\n').at(-1)).toBe('Next: harness close kid (once you have what you need)')const ps = await harness(d, String(first.tmuxPane), ['ps'])- expect(ps.out.trim().split('\n').at(-1)).toBe('You have 1 harness of your own open, 1 idle. Close each once you have its answer: harness close <name>.')+ expect(ps.out.trim().split('\n').at(-1)).toBe('Next: harness show kid (read its answer, then close it: harness close kid)')// A second lead with two: the person types into one of them, from a window.const second = await lead('lead2')@@ -321,7 +321,9 @@ describe('Harness for agents, end to end', () => {const started = await run('new', 'claude', 'helper', '--name', 'helper', '--', 'check it')expect(started.code, started.out + started.err).toBe(0)// 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).toContain('Next: harness wait helper (until it has answered; then read it: harness show helper)')+ // No pane to open it beside.+ expect(started.out).toContain('The person sees it in Harness.\n')expect(started.out).not.toContain('harness send')// 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)@@ -338,11 +340,11 @@ describe('Harness for agents, end to end', () => {expect(shown.out).toContain('check it')const person = await run('close', 'theirs')- expect(person.code).toBe(1)+ expect(person.code).toBe(5)expect(person.err).toContain('You did not start theirs')// Another session of the same agent did not start it either.const other = await harness(d, '', ['close', 'helper'], { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 'another-session' })- expect(other.code).toBe(1)+ expect(other.code).toBe(5)const closed = await run('close', 'helper')expect(closed.code, closed.err).toBe(0)client.close()@@ -353,8 +355,8 @@ describe('Harness for agents, end to end', () => {// because for its first seconds every read of the Codex process was refused. The fake Codex holds such a descriptor// for as long, and its first hook is as late: until then nothing could bind its conversation, as there.it.each([- ['binds its conversation a few seconds in', 6_000, 'Closed pong. Its conversation is kept.'],- ['never binds while the close waits', 120_000, 'Closed pong. It was still starting, so no conversation was kept.'],+ ['binds its conversation a few seconds in', 6_000, /^pong on .+: closed\. Its conversation is kept; the person can resume it\.\nNext: nothing; you have 0 open of 4\.$/],+ ['never binds while the close waits', 120_000, /^pong on .+: closed\. It was still starting, so no conversation was kept\.\nNext: nothing; you have 0 open of 4\.$/],] as const)('an agent closes a Codex it started a second ago, which %s', async (_, unboundMs, said) => {const module = pathToFileURL(join(CLI_ROOT, 'e2e', 'harness', 'fakeEngine.mjs')).hrefconst { d } = await signedIn({ agents_start_agents: true }, { before: (d) => {@@ -375,7 +377,7 @@ describe('Harness for agents, end to end', () => {const closed = await run('close', 'pong', '--now')expect(closed.err).not.toMatch(/descriptor|identity is held/)expect(closed.code, closed.out + closed.err).toBe(0)- expect(closed.out.trim()).toBe(said)+ expect(closed.out.trim()).toMatch(said)const stopped = await until('pong stopped', async () => { const r = await row(); return !r || r.status === 'stopped' ? r ?? {} : null }, 30_000, 250)if (unboundMs < 10_000) expect(stopped.sessionId).toBeTruthy()expect(await enginesIn(d, String(live.tmuxPane))).toBe('')@@ -400,7 +402,7 @@ describe('Harness for agents, end to end', () => {expect(hello.result.instructions).toContain('Never give work to, or close, a harness you did not start')server.notify('notifications/initialized')const tools = (await server.request('tools/list')).result.tools.map((t: { name: string }) => t.name)- expect(tools).toEqual(['harness_list', 'harness_start', 'harness_wait', 'harness_read', 'harness_close'])+ expect(tools).toEqual(['harness_whoami', 'harness_list', 'harness_start', 'harness_wait', 'harness_read', 'harness_close'])// An empty folder of its own: refused, with the project it can ask for instead.const scratch = join(d.root, 'tmp', 'mcp-scratch')@@ -411,9 +413,9 @@ describe('Harness for agents, end to end', () => {+ 'which needs no approval). Nothing was started.' })const started = await server.call('harness_start', { task: 'hello from mcp', project: 'mcp-kid', name: 'mcpkid' })expect(started.isError, started.text).toBe(false)- expect(started.text).toContain(`Created mcpkid on this computer in ${join(d.env.HOME!, 'harnesses', 'mcp-kid')}.`)+ expect(started.text).toContain(`mcpkid on this computer: starting. Claude Code, 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")')+ expect(started.text).toContain('Next: harness_wait (names: "mcpkid") (until it has answered; then read it: harness_read (name: "mcpkid"))')// 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' }) })])@@ -426,9 +428,11 @@ describe('Harness for agents, end to end', () => {expect(listed.text.split('\n')[0]).toMatch(/^You: Cursor, outside Harness, on .+\. Nothing can message you here\.$/)expect(listed.text).toMatch(/\nmcpkid +Claude Code +\w+ +you /)const refused = await server.call('harness_close', { name: 'theirs' })- expect(refused).toEqual({ text: 'You did not start theirs, so you may not close it. Only the person can.', isError: true })+ // A refusal is an answer, not an error to retry.+ expect(refused).toEqual({ text: 'You did not start theirs, so you may not close it. Only the person can.', isError: false })const closed = await server.call('harness_close', { name: 'mcpkid' })- expect(closed).toEqual({ text: 'Closed mcpkid. Its conversation is kept.', isError: false })+ expect(closed.isError).toBe(false)+ expect(closed.text).toMatch(/^mcpkid on .+: closed\. Its conversation is kept; the person can resume it\.\nNext: nothing; you have 0 open of 4\.$/)server.close()client.close()})@@ -446,7 +450,7 @@ describe('Harness for agents, end to end', () => {await d.start()await until('Harness to allow its commands in Claude Code and Codex', () => existsSync(rules)&& readFileSync(settings, 'utf8').includes('mcp__plugin_harness_harness__harness_send'), 30_000)- const tools = { ps: 'harness_list', show: 'harness_read', wait: 'harness_wait', new: 'harness_start', close: 'harness_close', send: 'harness_send' }+ const tools = { whoami: 'harness_whoami', ps: 'harness_list', show: 'harness_read', wait: 'harness_wait', new: 'harness_start', close: 'harness_close', send: 'harness_send' }const verbs = Object.keys(tools) as Array<keyof typeof tools>, launcher = join(d.env.HOME!, '.local', 'bin', 'harness')// The person's deny of `harness close` is theirs: no allow for it in either spelling (Claude Code does not count the// launcher's path as the same command). Its MCP tool is another tool, and is allowed by name. `harness --help`,@@ -495,7 +499,7 @@ describe('Harness for agents, end to end', () => {// The project it names instead: Harness makes it, answers the question for it, and the work is done with nobody asked.const started = await run('new', 'claude', 'opinion', '--name', 'opinion', '--', 'a second opinion on the shell script')expect(started.code, started.out + started.err).toBe(0)- expect(started.out).toContain(`Created opinion on this computer in ${join(d.env.HOME!, 'harnesses', 'opinion')}.`)+ expect(started.out).toContain(`opinion on this computer: starting. Claude Code, in ${join(d.env.HOME!, 'harnesses', 'opinion')}.`)expect(started.out).not.toContain('trust')const waited = await run('wait', 'opinion', '--timeout', '2m')expect(waited.out.trim(), waited.err).toBe('opinion: idle · read it: harness show opinion')@@ -511,7 +515,7 @@ describe('Harness for agents, end to end', () => {+ '(harness wait exits 3). For new work, a project name avoids this: harness new codex checker --name checker -- …')const held = await run('wait', 'checker', '--timeout', '2m')expect(held.code, held.out + held.err).toBe(3)- expect(held.out.trim()).toMatch(/^checker: needs-input · /)+ expect(held.out.trim()).toMatch(/^checker: needs the person · /)expect((await run('close', 'opinion')).code).toBe(0)})@@ -522,7 +526,7 @@ describe('Harness for agents, end to end', () => {// Claude Code in a terminal app, refused with where the person turns it on.const asAgent = { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 'held-session' }const refused = await harness(d, '', ['new', 'claude', 'held', '--name', 'held', '--', 'hello'], asAgent)- expect(refused.code, refused.out).toBe(1)+ expect(refused.code, refused.out).toBe(5)expect(refused.err.trim()).toBe('Agents may not start harnesses: the person turns on "Agents can start other agents" in Harness Settings ▸ Experimental, or runs `harness settings agents-start-agents on`. Until then, do the work yourself.')expect(JSON.parse((await harness(d, '', ['ps', '--json'])).out).harnesses).toEqual([])// The person, at a terminal: written through this computer's daemon to the account, and kept here at once.@@ -545,7 +549,7 @@ describe('Harness for agents, end to end', () => {relay.setExperiment('agents_start_agents', false)await kept(d, (settings) => settings.agentsStartAgents === false)const again = await harness(d, '', ['new', 'claude', 'again', '--name', 'again', '--', 'hello'], asAgent)- expect(again.code, again.out).toBe(1)+ expect(again.code, again.out).toBe(5)expect(again.err).toContain('Settings ▸ Experimental')})diff --git a/cli/e2e/freshMachineEngines.e2e.ts b/cli/e2e/freshMachineEngines.e2e.tsindex b775007e0..0263bb39d 100644--- a/cli/e2e/freshMachineEngines.e2e.ts+++ b/cli/e2e/freshMachineEngines.e2e.ts@@ -275,8 +275,8 @@ it('answers an MCP agent within Codex\'s tool timeout while Codex installs, starconst 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.')+ expect(started.text).toBe('cx on this computer: installing Codex. It starts by itself once installed; do not start it again.\n'+ + 'Next: harness_wait (names: "cx") (until it has started and answered)')// 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 /)diff --git a/cli/src/agentClient/commands.spec.ts b/cli/src/agentClient/commands.spec.tsindex 7d39fa9d4..2ca4e1599 100644--- a/cli/src/agentClient/commands.spec.ts+++ b/cli/src/agentClient/commands.spec.ts@@ -2,7 +2,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vitest'-import { addressOf, agentOrigin, AGENTS_START_AGENTS_OFF, closeCommand, DEPTH_REFUSAL, EXIT, parseDuration, psCommand, showCommand, spawnCheck, spawnCount, spawnRefusal, SPAWN_LIMITS, waitCommand, whoamiCommand, type ClientDeps } from './commands.js'+import { addressOf, agentOrigin, AGENTS_START_AGENTS_OFF, closeCommand, DEPTH_REFUSAL, EXIT, parseDuration, psCommand, refusalNext, showCommand, spawnCheck, spawnCount, spawnRefusal, SPAWN_LIMITS, step, waitCommand, whoamiCommand, type ClientDeps } from './commands.js'import { AgentClientError, type Daemon, type Where } from './daemon.js'import { Ledger, ledgerPath } from './ledger.js'import { agentSettingsPath } from '../lib/agentSettings.js'@@ -103,26 +103,69 @@ describe('harness ps', () => {expect(d.closed).toBe(true)})- it('tells an agent how many of its own are open and idle, and to close them once answered', async () => {+ it('ends an agent\'s ps with Next: read its idle one, wait for its busy ones, or start one', async () => {const d = new FakeDaemon()d.frames = [frame('lead', { engine: 'claude' }), frame('a'), frame('b', { activity: { state: 'working' } }), frame('c', { status: 'stopped' }), frame('theirs')]const h = harness(d)for (const kid of ['a', 'b', 'c']) started(h.ledger, 'lead', kid)expect(await psCommand([], h.deps)).toBe(EXIT.ok)- expect(h.out.join('\n').split('\n').at(-1)).toBe('You have 2 harnesses of your own open, 1 idle. Close each once you have its answer: harness close <name>.')- // One, and none idle.+ expect(h.out.join('\n').split('\n').slice(-2)).toEqual([+ 'Next: harness show a (read its answer, then close it: harness close a)',+ ' or: harness wait b (until it stops working)',+ ])+ // Through MCP, as its tools.d.frames = [frame('lead', { engine: 'claude' }), frame('b', { activity: { state: 'working' } })]const one = harness(d, { env: { HARNESS_VIA_MCP: '1' } })expect(await psCommand([], one.deps)).toBe(EXIT.ok)- expect(one.out.join('\n').split('\n').at(-1)).toBe('You have 1 harness of your own open. Close each once you have its answer: harness_close (name: "<name>").')- // None of its own, and the person: nothing to say.+ expect(one.out.join('\n').split('\n').at(-1)).toBe('Next: harness_wait (names: "b") (until it stops working)')+ // None of its own, and it may start one.d.frames = [frame('lead', { engine: 'claude' }), frame('theirs')]const none = harness(d)expect(await psCommand([], none.deps)).toBe(EXIT.ok)- expect(none.out.join('\n')).not.toMatch(/of your own open/)+ expect(none.out.join('\n').split('\n').at(-1)).toBe('Next: harness new <agent> --name <name> <project> -- <task> (to hand work to another agent; do quick work yourself)')+ // It may not start one: the block above says why, and nothing comes next.+ setAgentSettingsForTest(dir, { agentsStartAgents: false })+ const off = harness(d)+ expect(await psCommand([], off.deps)).toBe(EXIT.ok)+ expect(off.out.join('\n')).not.toMatch(/^Next:/m)+ // The person: no Next.const person = harness(d, { pane: undefined })expect(await psCommand([], person.deps)).toBe(EXIT.ok)- expect(person.out.join('\n')).not.toMatch(/of your own open/)+ expect(person.out.join('\n')).not.toMatch(/^Next:/m)+ // Programs read it as a field.+ setAgentSettingsForTest(dir, { agentsStartAgents: true })+ const json = harness(d)+ expect(await psCommand(['--json'], json.deps)).toBe(EXIT.ok)+ expect(JSON.parse(json.out[0]).next).toEqual([{ run: 'harness new <agent> --name <name> <project> -- <task>', when: 'to hand work to another agent; do quick work yourself' }])+ })++ it('shows an agent at most 15 rows, its own first, and says how to see the rest; a person sees all', async () => {+ const d = new FakeDaemon()+ // Its own two are the oldest: still shown, and first.+ d.frames = [frame('lead', { engine: 'claude' }), ...Array.from({ length: 18 }, (_, i) => frame(`h${i}`)),+ frame('old1', { updatedAt: '2026-10-01T00:00:00Z' }), frame('old2', { updatedAt: '2026-10-01T00:00:00Z' })]+ const h = harness(d)+ started(h.ledger, 'lead', 'old1')+ started(h.ledger, 'lead', 'old2')+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)+ const lines = h.out.join('\n').split('\n')+ const rows = lines.filter((l) => /^(h\d+|old\d|lead) /.test(l))+ expect(rows).toHaveLength(15)+ expect(rows.slice(0, 2).map((l) => l.split(' ')[0])).toEqual(['old1', 'old2'])+ expect(lines).toContain('and 6 more: harness ps --all')+ // Programs get every row.+ const json = harness(d)+ expect(await psCommand(['--json'], json.deps)).toBe(EXIT.ok)+ expect(JSON.parse(json.out[0]).harnesses).toHaveLength(21)+ // --all: all of them.+ const all = harness(d)+ expect(await psCommand(['--all'], all.deps)).toBe(EXIT.ok)+ expect(all.out.join('\n')).not.toContain('more: harness ps --all')+ // The person: every row, as before.+ const person = harness(d, { pane: undefined })+ expect(await psCommand([], person.deps)).toBe(EXIT.ok)+ expect(person.out.join('\n')).not.toContain('more: harness ps --all')+ expect(person.out.join('\n').match(/^(h\d+|old\d|lead) /gm)).toHaveLength(21)})it('tells an agent outside Harness that it is one', async () => {@@ -224,13 +267,13 @@ describe('harness show', () => {started(h.ledger, 'lead', 'reviewer')expect(await showCommand(['rev'], h.deps)).toBe(EXIT.ok)expect(h.out).toEqual([- 'reviewer · Codex · studio · idle · started by you',+ 'reviewer on studio: idle · Codex · started by you','folder: /work/reviewer (main)','asked: review 3f2a','answer (after 1 tool calls):','Two bugs.',// Idle and the caller's: a harness left open after its answer is read sits there for nobody.- 'Close it once you have what you need: harness close reviewer',+ 'Next: harness close reviewer (once you have what you need)',])expect(d.requests.filter((r) => r.type === 'session_get').map((r) => r.payload)).toEqual([{ sessionId: 's-reviewer', limit: 80 }, { sessionId: 's-reviewer', limit: 80, before: '1' },@@ -247,18 +290,19 @@ describe('harness show', () => {started(h.ledger, 'lead', 'busy')expect(await showCommand(['kid'], h.deps)).toBe(EXIT.ok)// An unnamed harness is called by its session title, a sentence `close` would not take: the start of its id.- expect(h.out.at(-1)).toBe('Close it once you have what you need: harness close kid')+ expect(h.out.at(-1)).toBe('Next: harness close kid (once you have what you need)')expect(await showCommand(['busy'], h.deps)).toBe(EXIT.ok)- expect(h.out.at(-1)).not.toMatch(/Close it/)+ expect(h.out.at(-1)).not.toMatch(/harness close/)expect(await showCommand(['theirs'], h.deps)).toBe(EXIT.ok)- expect(h.out.at(-1)).not.toMatch(/Close it/)+ expect(h.out.at(-1)).not.toMatch(/harness close/)const mcp = harness(d, { env: { HARNESS_VIA_MCP: '1' } })expect(await showCommand(['kid'], mcp.deps)).toBe(EXIT.ok)- expect(mcp.out.at(-1)).toBe('Close it once you have what you need: harness_close (name: "kid")')- // Programs read the state themselves.+ expect(mcp.out.at(-1)).toBe('Next: harness_close (name: "kid") (once you have what you need)')+ // Programs read the next step as a field, not a line.const json = harness(d)expect(await showCommand(['kid', '--json'], json.deps)).toBe(EXIT.ok)- expect(json.out.join('\n')).not.toMatch(/Close it/)+ expect(json.out.join('\n')).not.toMatch(/Next:/)+ expect(JSON.parse(json.out.join('\n')).next).toEqual([{ run: 'harness close kid', when: 'once you have what you need' }])})it('clips a long answer and says how to read the rest; says when it waits for the person', async () => {@@ -268,15 +312,55 @@ describe('harness show', () => {d.pages.set('s-long', [{ events: [ev('user_message', { content: 'go' }), ev('text_delta', { content: 'x'.repeat(50) })], hasMore: false }])const h = harness(d)expect(await showCommand(['long', '--chars', '10'], h.deps)).toBe(EXIT.ok)- expect(h.out[0]).toBe('long · Codex · studio · needs-input · started by person')+ expect(h.out[0]).toBe('long on studio: needs the person · Codex · started by person')expect(h.out).toContain('xxxxxxxxx…')expect(h.out).toContain('… 40 more characters: harness show long --chars 50')- expect(h.out.at(-1)).toMatch(/waiting for the person/)+ expect(h.out.at(-1)).toMatch(/^Next: tell the person/)const json = harness(d)expect(await showCommand(['long', '--json', '--chars=5'], json.deps)).toBe(EXIT.ok)expect(JSON.parse(json.out.join('\n'))).toMatchObject({ name: 'long', state: 'needs-input', answer: 'xxxx…', truncated: true, ask: 'go' })})+ it('starts with the result and ends with Next: close for its own idle harness', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('kid')]+ d.pages.set('s-kid', [{ events: [ev('user_message', { content: 'review it' }), ev('text_delta', { content: 'One bug.' })], hasMore: false }])+ const h = harness(d)+ started(h.ledger, 'lead', 'kid')+ expect(await showCommand(['kid'], h.deps)).toBe(EXIT.ok)+ const lines = h.out.join('\n').split('\n')+ expect(lines[0]).toBe('kid on studio: idle · Codex · started by you')+ expect(lines.at(-1)).toBe('Next: harness close kid (once you have what you need)')+ })++ it('names wait for a working harness, and never close for one the caller did not start', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('busy', { activity: { state: 'working' } }), frame('theirs')]+ d.screens.set('busy', ['working'])+ const h = harness(d)+ started(h.ledger, 'lead', 'busy')+ expect(await showCommand(['busy'], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n').split('\n').at(-1)).toBe('Next: harness wait busy (until it stops working)')+ const theirs = harness(d)+ expect(await showCommand(['theirs'], theirs.deps)).toBe(EXIT.ok)+ expect(theirs.out.join('\n')).not.toMatch(/harness close/)+ })++ it('says to tell the person when only they can answer, and gives next in JSON', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('asker')]+ d.screens.set('asker', ['needs_input'])+ const h = harness(d)+ started(h.ledger, 'lead', 'asker')+ expect(await showCommand(['asker'], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n').split('\n').at(-1)).toBe('Next: tell the person; only they answer it (a question or a permission).')+ const json = harness(d)+ expect(await showCommand(['asker', '--json'], json.deps)).toBe(EXIT.ok)+ const parsed = JSON.parse(json.out[0])+ expect(parsed.state).toBe('needs-input')+ expect(parsed.next).toEqual([{ tell: 'tell the person; only they answer it (a question or a permission).' }])+ })+it('says when there is no turn yet, or no transcript to read', async () => {const d = new FakeDaemon()d.frames = [frame('fresh', { sessionId: '' }), frame('broken'), frame('stopped', { status: 'stopped' })]@@ -286,12 +370,12 @@ describe('harness show', () => {expect(await showCommand(['broken'], h.deps)).toBe(EXIT.ok)expect(await showCommand(['stopped'], h.deps)).toBe(EXIT.ok)expect(h.out.filter((l) => l === 'No turn yet.')).toHaveLength(3)- expect(h.out).toContain('stopped · Codex · studio · stopped · started by person')+ expect(h.out).toContain('stopped on studio: stopped · Codex · started by person')// The screen could not be read: the listed state stands.d.extra.agent_close = () => { throw new Error('gone') }const again = harness(d, { pane: undefined })expect(await showCommand(['fresh'], again.deps)).toBe(EXIT.ok)- expect(again.out[0]).toContain('· idle ·')+ expect(again.out[0]).toContain(': idle ·')})it('stops reading back after four pages', async () => {@@ -391,7 +475,7 @@ describe('harness wait', () => {answered(d, 'done')const h = harness(d)expect(await waitCommand(['done', '--json'], h.deps)).toBe(EXIT.ok)- expect(JSON.parse(h.out.join('\n'))).toEqual({ harnesses: [{ name: 'done', id: 'done', state: 'idle' }] })+ expect(JSON.parse(h.out.join('\n'))).toEqual({ harnesses: [{ name: 'done', id: 'done', state: 'idle', next: [{ run: 'harness show done', when: 'to read its answer' }] }] })expect(inspects(d)).toBe(2)})@@ -442,7 +526,7 @@ describe('harness wait', () => {d.screens.set('busy', ['working'])const h = harness(d)expect(await waitCommand(['asks'], h.deps)).toBe(EXIT.needsInput)- expect(h.out[0]).toMatch(/asks: needs-input · it waits for the person/)+ expect(h.out[0]).toMatch(/asks: needs the person · it waits for the person/)const t = harness(d)expect(await waitCommand(['busy', '--timeout', '10s'], t.deps)).toBe(EXIT.timeout)expect(t.out[0]).toBe('busy: timeout · still working; wait again or read it: harness show busy')@@ -461,6 +545,23 @@ describe('harness wait', () => {expect(g.out[0]).toBe('x: gone · it is gone')})+ it('tells where to look for a harness that is gone, and gives each one\'s next in JSON', async () => {+ const s = new FakeDaemon()+ s.frames = [frame('x')]+ s.screens.set('x', ['working'])+ let m = 0+ s.extra.agents_list = () => ({ agents: m++ < 2 ? s.frames : [] })+ const g = harness(s)+ expect(await waitCommand(['x'], g.deps)).toBe(EXIT.stopped)+ expect(g.out.join('\n')).toBe('x: gone · it is gone\nNext: harness ps --all (to see whether it was closed)')+ const d = new FakeDaemon()+ d.frames = [frame('done')]+ answered(d, 'done')+ const json = harness(d)+ expect(await waitCommand(['done', '--json'], json.deps)).toBe(EXIT.ok)+ expect(JSON.parse(json.out.join('\n')).harnesses[0].next).toEqual([{ run: 'harness show done', when: 'to read its answer' }])+ })+// A Codex lead closed its harness, then waited on it as it had queued: "Failed (exit 4) … stopped · it was stopped".it('says a harness the caller closed was closed by it, and is no failure; another\'s close still is', async () => {const d = new FakeDaemon()@@ -472,7 +573,7 @@ describe('harness wait', () => {expect(await waitCommand(['kid'], h.deps)).toBe(EXIT.ok)expect(h.out).toEqual(['kid: closed (you closed it)'])expect(await waitCommand(['kid', '--json'], h.deps)).toBe(EXIT.ok)- expect(JSON.parse(h.out[1])).toEqual({ harnesses: [{ name: 'kid', id: 'kid', state: 'closed' }] })+ expect(JSON.parse(h.out[1])).toEqual({ harnesses: [{ name: 'kid', id: 'kid', state: 'closed', next: [] }] })// Gone from the list after it closed it: still its close.h.ledger.append({ at: NOW, by: { machineId: 'm', agentId: 'lead' }, closed: { machineId: 'm', agentId: 'gone' } })let n = 0@@ -573,6 +674,81 @@ describe('harness wait', () => {})})+describe('Next names a harness as its verbs take it', () => {+ it('quotes a two-word name once, as a shell command or a tool call', async () => {+ expect(step({}, 'wait', '"code review"')).toBe('harness wait "code review"')+ expect(step({ HARNESS_VIA_MCP: '1' }, 'wait', '"code review"')).toBe('harness_wait (names: "code review")')+ expect(step({ HARNESS_VIA_MCP: '1' }, 'show', '"code review"')).toBe('harness_read (name: "code review")')+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' })]+ const viaMcp = (await agentOrigin(harness(d, { env: { HARNESS_VIA_MCP: '1' } }).deps))!+ expect(viaMcp.answer({ id: 'k1', name: 'code review' }, { local: true, machine: null }).next[0])+ .toEqual({ run: 'harness_wait (names: "code review")', when: 'until it has answered; then read it: harness_read (name: "code review")' })+ })++ it('gives wait\'s next by a name the verbs take: quoted, or the id\'s start for a sentence', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('abcdef123456', { name: 'so we have built harness web,' }), frame('cr123456', { name: 'code review' })]+ d.pages.set('s-abcdef123456', [{ events: [ev('user_message', { content: 'x' }), ev('text_delta', { content: 'Done.' }), ev('done')], hasMore: false }])+ d.pages.set('s-cr123456', [{ events: [ev('user_message', { content: 'x' }), ev('text_delta', { content: 'Done.' }), ev('done')], hasMore: false }])+ const h = harness(d, { pane: undefined })+ expect(await waitCommand(['abcdef12', '--json'], h.deps)).toBe(EXIT.ok)+ expect(JSON.parse(h.out[0]).harnesses[0].next).toEqual([{ run: 'harness show abcdef12', when: 'to read its answer' }])+ const two = harness(d, { pane: undefined })+ expect(await waitCommand(['cr123456', '--json'], two.deps)).toBe(EXIT.ok)+ expect(JSON.parse(two.out[0]).harnesses[0].next).toEqual([{ run: 'harness show "code review"', when: 'to read its answer' }])+ })+})++describe('refusals and the person', () => {+ it('closing a harness the caller did not start exits 5, with its code in JSON beside the old fields', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('theirs')]+ const h = harness(d)+ expect(EXIT.refused).toBe(5)+ expect(await closeCommand(['theirs'], h.deps)).toBe(EXIT.refused)+ const json = harness(d)+ expect(await closeCommand(['theirs', '--json'], json.deps)).toBe(EXIT.refused)+ expect(JSON.parse(json.out[0])).toEqual({ error: 'NOT_YOURS', detail: 'You did not start theirs, so you may not close it. Only the person can.', code: 'NOT_YOURS', next: [] })+ })++ it('refuses a start over the open limit with its reason, the switch off and an orphan with theirs', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), ...['a', 'b', 'c', 'd'].map((id) => frame(id))]+ const h = harness(d)+ for (const kid of ['a', 'b', 'c', 'd']) started(h.ledger, 'lead', kid)+ const full = await (await agentOrigin(h.deps))!.check().catch((e) => e)+ expect(full).toBeInstanceOf(AgentClientError)+ expect([full.code, full.reason]).toEqual(['SPAWN_LIMIT', 'OPEN_LIMIT'])+ expect(refusalNext({}, full)).toEqual([{ run: 'harness close <name>', when: 'one you are done with, to free a place' }])+ setAgentSettingsForTest(dir, { agentsStartAgents: false })+ const off = await (await agentOrigin(harness(d).deps))!.check().catch((e) => e)+ expect([off.code, off.reason]).toEqual(['TURNED_OFF', 'SWITCH_OFF'])+ expect(refusalNext({}, off)).toEqual([])+ const orphan = await (await agentOrigin(harness(new FakeDaemon(), { pane: '%gone', where: () => ({ ...where, harnessPane: true }) }).deps))!.check().catch((e) => e)+ expect([orphan.code, orphan.reason]).toEqual(['NOT_YOURS', 'ORPHAN'])+ })++ it('says needs the person in text and keeps needs-input in JSON, with needsPerson', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('asker')]+ d.screens.set('asker', ['needs_input'])+ const h = harness(d)+ started(h.ledger, 'lead', 'asker')+ expect(await waitCommand(['asker'], h.deps)).toBe(EXIT.needsInput)+ expect(h.out[0]).toMatch(/^asker: needs the person · /)+ const json = harness(d)+ expect(await waitCommand(['asker', '--json'], json.deps)).toBe(EXIT.needsInput)+ expect(JSON.parse(json.out[0]).harnesses[0]).toMatchObject({ state: 'needs-input', needsPerson: true })+ const shown = harness(d)+ expect(await showCommand(['asker'], shown.deps)).toBe(EXIT.ok)+ expect(shown.out[0]).toBe('asker on studio: needs the person · Codex · started by you')+ const shownJson = harness(d)+ expect(await showCommand(['asker', '--json'], shownJson.deps)).toBe(EXIT.ok)+ expect(JSON.parse(shownJson.out[0])).toMatchObject({ state: 'needs-input', needsPerson: true })+ })+})+describe('harness close', () => {it('closes a harness the agent started, once it is idle', async () => {const d = new FakeDaemon()@@ -580,33 +756,50 @@ describe('harness close', () => {const h = harness(d)started(h.ledger, 'lead', 'kid')expect(await closeCommand(['kid'], h.deps)).toBe(EXIT.ok)- expect(h.out).toEqual(['Closed kid. Its conversation is kept.'])+ expect(h.out).toEqual(['kid on studio: closed. Its conversation is kept; the person can resume it.\nNext: nothing; you have 0 open of 4.'])expect(d.requests.at(-1)).toMatchObject({ type: 'agent_close', payload: { agentId: 'kid', sessionId: 's-kid', mode: 'idle' } })const now = harness(d)expect(await closeCommand(['kid', '--now', '--json'], now.deps)).toBe(EXIT.ok)- expect(JSON.parse(now.out[0])).toEqual({ name: 'kid', id: 'kid', closed: true })+ expect(JSON.parse(now.out[0])).toEqual({ name: 'kid', id: 'kid', closed: true, effect: 'Its conversation is kept; the person can resume it.', next: [], open: 0 })expect(d.requests.at(-1)?.payload.mode).toBe('now')})+ it('says the result and the effect, and how many of its own are still open', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('kid'), frame('other')]+ const h = harness(d)+ started(h.ledger, 'lead', 'kid')+ started(h.ledger, 'lead', 'other')+ expect(await closeCommand(['kid'], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n')).toBe('kid on studio: closed. Its conversation is kept; the person can resume it.\nNext: nothing; you have 1 open of 4.')+ const json = harness(d)+ expect(await closeCommand(['other', '--json'], json.deps)).toBe(EXIT.ok)+ expect(JSON.parse(json.out[0])).toEqual({ name: 'other', id: 'other', closed: true, effect: 'Its conversation is kept; the person can resume it.', next: [], open: 1 })+ // The person: the result alone.+ const person = harness(d, { pane: undefined })+ expect(await closeCommand(['kid'], person.deps)).toBe(EXIT.ok)+ expect(person.out).toEqual(['kid on studio: closed. Its conversation is kept; the person can resume it.'])+ })+it('refuses an agent a harness it did not start, and its own; the person closes anything', async () => {const d = new FakeDaemon()d.frames = [frame('lead'), frame('theirs')]const h = harness(d)- expect(await closeCommand(['theirs'], h.deps)).toBe(EXIT.failed)+ expect(await closeCommand(['theirs'], h.deps)).toBe(EXIT.refused)expect(h.err[0]).toBe('You did not start theirs, so you may not close it. Only the person can.')- expect(await closeCommand(['lead'], h.deps)).toBe(EXIT.failed)+ expect(await closeCommand(['lead'], h.deps)).toBe(EXIT.refused)expect(h.err[1]).toBe('That is your own harness. The person closes it.')const person = harness(d, { pane: undefined })expect(await closeCommand(['theirs'], person.deps)).toBe(EXIT.ok)// An agent the daemon lists offline for a moment is still that agent: never the person.d.frames = [frame('lead', { status: 'offline' }), frame('theirs')]const stopped = harness(d)- expect(await closeCommand(['theirs'], stopped.deps)).toBe(EXIT.failed)+ expect(await closeCommand(['theirs'], stopped.deps)).toBe(EXIT.refused)expect(stopped.err[0]).toMatch(/^You did not start theirs/)// A pane Harness made whose harness it has forgotten: what is left of an agent, never the person.d.frames = [frame('theirs')]const left = harness(d, { pane: '%gone', where: () => ({ ...where, harnessPane: true }) })- expect(await closeCommand(['theirs'], left.deps)).toBe(EXIT.failed)+ expect(await closeCommand(['theirs'], left.deps)).toBe(EXIT.refused)expect(left.err[0]).toBe('This pane\'s harness is no longer running, so nothing here may close or start harnesses. Only the person can.')// A person's terminal in Harness, or a pane of their own tmux, is the person.d.frames = [frame('theirs'), frame('sh', { engine: 'terminal', tmuxPane: '%sh' })]@@ -619,15 +812,15 @@ describe('harness close', () => {d.frames = [frame('mine'), frame('theirs'), frame('sh', { engine: 'terminal', tmuxPane: '%sh' })]const h = harness(d, { pane: undefined, env: { CODEX_THREAD_ID: 'T1' } })h.ledger.append({ at: NOW, depth: 1, by: { machineId: 'm', agentId: 'codex:T1', name: 'Codex', engine: 'codex' }, child: { machineId: 'm', agentId: 'mine', name: 'mine' } })- expect(await closeCommand(['theirs'], h.deps)).toBe(EXIT.failed)+ expect(await closeCommand(['theirs'], h.deps)).toBe(EXIT.refused)expect(h.err[0]).toBe('You did not start theirs, so you may not close it. Only the person can.')expect(await closeCommand(['mine'], h.deps)).toBe(EXIT.ok)// Another session of the same agent did not start it.const other = harness(d, { pane: undefined, env: { CODEX_THREAD_ID: 'T2' } })- expect(await closeCommand(['mine'], other.deps)).toBe(EXIT.failed)+ expect(await closeCommand(['mine'], other.deps)).toBe(EXIT.refused)// From a person's terminal in Harness: still the agent its shell names.const inTile = harness(d, { pane: '%sh', env: { AI_AGENT: 'cursor_1-2_agent' }, where: () => ({ ...where, harnessPane: true }) })- expect(await closeCommand(['theirs'], inTile.deps)).toBe(EXIT.failed)+ expect(await closeCommand(['theirs'], inTile.deps)).toBe(EXIT.refused)})it('says what to do when it is working or changed, and passes on any other refusal', async () => {@@ -662,9 +855,9 @@ describe('harness close', () => {const h = harness(d)started(h.ledger, 'lead', 'kid')expect(await closeCommand(['kid', '--now'], h.deps)).toBe(EXIT.ok)- expect(h.out).toEqual(['Closed kid. It was still starting, so no conversation was kept.'])+ expect(h.out).toEqual(['kid on studio: closed. It was still starting, so no conversation was kept.\nNext: nothing; you have 0 open of 4.'])expect(await closeCommand(['kid', '--now', '--json'], h.deps)).toBe(EXIT.ok)- expect(JSON.parse(h.out[1])).toEqual({ name: 'kid', id: 'kid', closed: true, conversationKept: false })+ expect(JSON.parse(h.out[1])).toEqual({ name: 'kid', id: 'kid', closed: true, conversationKept: false, effect: 'It was still starting, so no conversation was kept.', next: [], open: 0 })expect(await closeCommand(['kid', '--now'], h.deps)).toBe(EXIT.failed)expect(h.err).toEqual(['kid was not closed: Harness cannot tell which conversation it is in right now, and closing it would lose that conversation. Try again in a moment.'])})@@ -683,7 +876,7 @@ describe('harness close', () => {expect(readFileSync(ledgerPath(dir), 'utf8').trim().split('\n')).toHaveLength(2)const unwritable = harness(d, { ledger: (data) => Object.assign(new Ledger(ledgerPath(data)), { append: () => { throw new Error('read-only') } }) })expect(await closeCommand(['kid'], unwritable.deps)).toBe(EXIT.ok)- expect(unwritable.out).toEqual(['Closed kid. Its conversation is kept.'])+ expect(unwritable.out).toEqual(['kid on studio: closed. Its conversation is kept; the person can resume it.\nNext: nothing; you have 0 open of 4.'])})it('closes one harness at a time, by name', async () => {@@ -752,7 +945,7 @@ describe('harness new, run by an agent', () => {await expect(origin.check()).rejects.toThrow(/no longer running/)expect(origin.prompt('x', 'm')).toBe('x')expect(await origin.created('m', {})).toBeNull()- expect(origin.next({})).toBe('')+ expect(origin.answer({}, { local: true, machine: null })).toEqual({ effect: '', next: [] })})it('heads the task with who sent it, records what it started, and says how to follow it, never to message it', async () => {@@ -780,10 +973,24 @@ describe('harness new, run by an agent', () => {expect(h.ledger.all()).toEqual([{ at: NOW, depth: 1, by: { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }, child: { machineId: 'm', agentId: 'kid', name: 'reviewer' } }])await origin.created('m', { id: 'kid2', name: 7 })expect(h.ledger.all()[1].child.name).toBe('')- expect(origin.next({ id: 'kid', name: 'reviewer' })).toBe('Read it: harness show reviewer · wait for it: harness wait reviewer')+ const here = { local: true, machine: null }+ expect(origin.answer({ id: 'kid', name: 'reviewer' }, here)).toEqual({+ effect: 'The person sees it in Harness, beside you.',+ next: [{ run: 'harness wait reviewer', when: 'until it has answered; then read it: harness show reviewer' }],+ })// A name that is a sentence, or Harness's own stand-in: the id's start instead.- expect(origin.next({ id: 'abcdef123456', name: 'Claude harness 10-11 8:38' })).toContain('harness show abcdef12 ·')- expect(origin.next({ id: 'abcdef123456', name: 'code review' })).toContain('harness show "code review" ·')+ const runOf = (agent: Record<string, unknown>, at: { local: boolean; machine: string | null } = here) => { const [step] = origin.answer(agent, at).next; return 'run' in step ? step.run : '' }+ expect(runOf({ id: 'abcdef123456', name: 'Claude harness 10-11 8:38' })).toBe('harness wait abcdef12')+ expect(runOf({ id: 'abcdef123456', name: 'code review' })).toBe('harness wait "code review"')+ // On another machine: named with it, and the person sees it there, not beside the caller.+ expect(origin.answer({ id: 'kid', name: 'reviewer' }, { local: false, machine: 'Mac mini' })).toEqual({+ effect: 'The person sees it in Harness.',+ next: [{ run: 'harness wait --machine "Mac mini" reviewer', when: 'until it has answered; then read it: harness show --machine "Mac mini" reviewer' }],+ })+ // Under MCP the tools take no machine: harness_wait finds the caller's own by its record.+ const viaMcp = (await agentOrigin(harness(d, { env: { HARNESS_VIA_MCP: '1' } }).deps))!+ const [mcpStep] = viaMcp.answer({ id: 'kid', name: 'reviewer' }, { local: false, machine: 'mini' }).next+ expect(mcpStep).toEqual({ run: 'harness_wait (names: "reviewer")', when: 'until it has answered; then read it: harness_read (name: "reviewer")' })expect(addressOf({ machineId: 'm', agentId: 'abcdef123456', name: 'so we have built harness web,', engine: 'claude' })).toBe('abcdef12')expect(addressOf({ machineId: 'm', agentId: 'abcdef123456', name: 'x'.repeat(41), engine: 'claude' })).toBe('abcdef12')})@@ -798,8 +1005,11 @@ describe('harness new, run by an agent', () => {expect(origin.prompt('review it', 'm')).toBe('[from Claude Code outside Harness · studio, the agent that started you. It reads your answer itself.]\n\nreview it')expect(await origin.created('m', { id: 'kid', name: 'reviewer' })).toBeNull()expect(h.ledger.all()).toEqual([{ at: NOW, depth: 1, by: { machineId: 'm', agentId: 'claude-code:S1', name: 'Claude Code', engine: 'claude' }, child: { machineId: 'm', agentId: 'kid', name: 'reviewer' } }])- // Nothing can message it: it has no pane.- expect(origin.next({ id: 'kid', name: 'reviewer' })).toBe('Read it: harness show reviewer · wait for it: harness wait reviewer')+ // Nothing can message it: it has no pane. It has no place beside it either.+ expect(origin.answer({ id: 'kid', name: 'reviewer' }, { local: true, machine: null })).toEqual({+ effect: 'The person sees it in Harness.',+ next: [{ run: 'harness wait reviewer', when: 'until it has answered; then read it: harness show reviewer' }],+ })// In a person's terminal in Harness, it is still that agent.expect(await agentOrigin(harness(d, { pane: '%9', env: claude, where: () => ({ ...where, harnessPane: true }) }).deps)).not.toBeNull()// The daemon did not answer: refused, never the person.@@ -979,7 +1189,8 @@ describe('a harness asked for that has not started (its engine still installing)asked(h.ledger, 'slow', 'c3')h.out.length = 0expect(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.' }] })+ expect(JSON.parse(h.out[0])).toEqual({ harnesses: [{ name: 'slow', id: 'c3', state: 'installing', detail: 'Installing Codex. The harness starts once it is installed.',+ next: [{ run: 'harness wait slow', when: 'to keep waiting' }] }] })h.out.length = 0expect(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.'])@@ -1193,7 +1404,7 @@ describe('a harness on another machine, named with --machine', () => {// name.h.out.length = 0expect(await showCommand(['lamp', '--machine=office-id'], h.deps)).toBe(EXIT.ok)- expect(h.out[0]).toBe('lamp-first-task · Claude Code · office · idle · started by person')+ expect(h.out[0]).toBe('lamp-first-task on office: idle · Claude Code · started by person')expect(h.out).toContain('Four.')// More of the answer is asked for on that machine too, as it was named.h.out.length = 0@@ -1298,7 +1509,7 @@ describe('a harness on another machine, named with --machine', () => {it('closes one there as here: the person anything, an agent only what it started', async () => {const { d, office, h } = lamp()expect(await closeCommand(['--machine', 'office', 'lamp-first-task'], h.deps)).toBe(EXIT.ok)- expect(h.out).toEqual(['Closed lamp-first-task. Its conversation is kept.'])+ expect(h.out).toEqual(['lamp-first-task on office: closed. Its conversation is kept; the person can resume it.'])expect(office.requests.at(-1)).toMatchObject({ type: 'agent_close', payload: { agentId: 'lamp-first-task', mode: 'idle' } })// One still working is waited for on its machine.office.extra.agent_close = (p) => (p.mode === 'inspect' ? { activity: 'working' } : { error: 'SESSION_NOT_IDLE', activity: 'working' })@@ -1309,7 +1520,7 @@ describe('a harness on another machine, named with --machine', () => {d.frames = [frame('lead', { engine: 'claude' })]office.frames.push(frame('kid'))const agent = harness(d, { machines, others: { 'office-id': office } })- expect(await closeCommand(['--machine', 'office', 'lamp-first-task'], agent.deps)).toBe(EXIT.failed)+ expect(await closeCommand(['--machine', 'office', 'lamp-first-task'], agent.deps)).toBe(EXIT.refused)expect(agent.err[0]).toBe('You did not start lamp-first-task, so you may not close it. Only the person can.')started(agent.ledger, 'lead', 'kid', 'office-id')expect(await closeCommand(['--machine', 'office', 'kid'], agent.deps)).toBe(EXIT.ok)diff --git a/cli/src/agentClient/commands.ts b/cli/src/agentClient/commands.tsindex bb03bbf59..9b8df9dba 100644--- a/cli/src/agentClient/commands.ts+++ b/cli/src/agentClient/commands.ts@@ -25,10 +25,11 @@ import { engineName } from '../messages/model.js'import { machineListCachePath } from '../device/machineList.js'import { readAuthSession } from '../lib/authSession.js'import { buildContext, formatContext, type Context, type SpawnCount, type SpawnReason } from './context.js'+import { formatNext, type NextStep } from './next.js'import { AgentClientError, openDaemon, whereFor, type Daemon, type Where } from './daemon.js'import { Ledger, ledgerPath, type Pending, type Started } from './ledger.js'import { messagesRpc, type Rpc } from '../messages/rpc.js'-import { asSaid, callerOf, clip, isAgent, lastTurn, matching, outsideCaller, rowsOf, stateOf, STOPPED_WITHIN_MS, type Caller, type Frame, type HistoryEvent, type Row, type State } from './model.js'+import { asSaid, callerOf, clip, forAgent, isAgent, lastTurn, matching, outsideCaller, rowsOf, stateOf, STOPPED_WITHIN_MS, type Caller, type Frame, type HistoryEvent, type Row, type State } from './model.js'export interface ClientDeps {pane?: string | undefined@@ -70,14 +71,26 @@ ${ON_MACHINE}`export const CLOSE_USAGE = `Usage: harness close [--machine <name>] <name> [--now] [--json]Saves the harness's screen and stops it. Its conversation is kept: the person can resume it.-It is refused while the harness is working, unless --now. An agent may close only harnesses it started.+It is refused while the harness is working, unless --now. An agent may close only harnesses it started:+closing another's exits 5.${ON_MACHINE}`export const WHOAMI_USAGE = `Usage: harness whoami [--json]Who you are to Harness: which agent, on which machine, inside Harness or not; whether you may start harnesses nowand, if not, who can change that; how many of yours are open, and how many starts are left.`-export const EXIT = { ok: 0, failed: 1, usage: 2, needsInput: 3, stopped: 4, timeout: 124 } as const+export const EXIT = { ok: 0, failed: 1, usage: 2, needsInput: 3, stopped: 4, refused: 5, timeout: 124 } as const++/** Not a failure: the caller may not do this. It should not retry; it tells the person or does the work itself. */+export const REFUSED_CODES: ReadonlySet<string> = new Set(['SPAWN_LIMIT', 'TURNED_OFF', 'NOT_YOURS'])++/** What a refused caller may do instead: close one of its own when it is at its limit; otherwise the message says. */+export function refusalNext(env: NodeJS.ProcessEnv, error: AgentClientError): NextStep[] {+ return error.reason === 'OPEN_LIMIT' ? [{ run: step(env, 'close', '<name>'), when: 'one you are done with, to free a place' }] : []+}++/** A state as an agent reads it: one that waits on a question or a permission says who answers it. JSON keeps the word. */+const stateSaid = (state: string): string => (state === 'needs-input' ? 'needs the person' : state)/** Set by `harness mcp` (mcp.ts) for the verbs it runs: their next steps are then named as its tools. */export const VIA_MCP_ENV = 'HARNESS_VIA_MCP'@@ -90,7 +103,9 @@ const TOOL_OF = { ps: 'harness_list', show: 'harness_read', wait: 'harness_wait'*/export function step(env: NodeJS.ProcessEnv, verb: keyof typeof TOOL_OF, name = '', option?: { flag: string; arg: string }): string {if (env[VIA_MCP_ENV] !== '1') return ['harness', verb, name, option?.flag].filter(Boolean).join(' ')- const args = [name && `${verb === 'wait' ? 'names' : 'name'}: "${name}"`, option?.arg].filter(Boolean)+ // A name quoted for the shell (`"code review"`, addressOf) is quoted once, as the tool's argument.+ const bare = name.replace(/^"(.*)"$/, '$1')+ const args = [bare && `${verb === 'wait' ? 'names' : 'name'}: "${bare}"`, option?.arg].filter(Boolean)return `${TOOL_OF[verb]}${args.length ? ` (${args.join(', ')})` : ''}`}@@ -466,9 +481,12 @@ async function run(usage: string, deps: ClientDeps, json: (argv: readonly string}const code = error instanceof AgentClientError ? error.code : 'FAILED'const message = error instanceof Error ? error.message : String(error)- if (json(argv)) s.out(JSON.stringify({ error: code, detail: message }))- else s.err(message)- return EXIT.failed+ const refused = error instanceof AgentClientError && REFUSED_CODES.has(code)+ if (json(argv)) {+ s.out(JSON.stringify({ error: code, detail: message,+ ...(refused ? { code, ...(error.reason ? { reason: error.reason } : {}), next: refusalNext(s.env, error) } : {}) }))+ } else s.err(message)+ return refused ? EXIT.refused : EXIT.failed}}const wantsJson = (argv: readonly string[]): boolean => argv.includes('--json')@@ -520,27 +538,46 @@ export function psCommand(argv: readonly string[], deps: ClientDeps = {}): Promimachine: away ? away.label : 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, away),})))- const note = o.caller ? openNote(s.env, rows) : null- // An agent is told where it is and what it may do before the list; a person's ps is as it was.+ // An agent is told where it is and what it may do before the list, and what to do next after it; a person's ps is+ // as it was.const agent = !!o.caller || o.orphan- s.out(flags.has('--json') ? JSON.stringify({ you: o.caller ? o.caller.name : null, machine: on.machine, context: contextFor(s, o), harnesses: rows }, null, 1)- : [agent ? formatContext(contextFor(s, o)) : null, formatRows(rows, s.now(), away ? away.label : undefined), note].filter(Boolean).join('\n'))+ const context = contextFor(s, o)+ const next = o.caller ? psNext(s.env, rows, !!context.canStart?.ok) : []+ // An agent reads its own first and at most AGENT_ROWS, unless it asked for all; programs and the person get every row.+ const { shown, more } = agent && !all ? forAgent(rows) : { shown: rows, more: 0 }+ const rest = more ? `and ${more} more: ${step(s.env, 'ps', away ? machineOption(away.word) : '', { flag: '--all', arg: 'all: true' })}` : null+ s.out(flags.has('--json') ? JSON.stringify({ you: o.caller ? o.caller.name : null, machine: on.machine, context, harnesses: rows, next }, null, 1)+ : [agent ? formatContext(context) : null, formatRows(shown, s.now(), away ? away.label : undefined), rest, formatNext(next)].filter(Boolean).join('\n'))return EXIT.ok} finally { line?.close(); o.daemon.close() }})}-/** What `show` ends with for an idle harness of the caller's. */-export const closeHint = (env: NodeJS.ProcessEnv, frame: Frame, away: Away | null = null): string =>- `Close it once you have what you need: ${step(env, 'close', onAway(addressOf({ machineId: '', agentId: frame.id, name: frame.name ?? '', engine: '' }), away))}`+/** What `show` says to do next, from its state and whose it is: never `close` for a harness the caller did not start.+ * Idle and the caller's: a harness left open after its answer is read sits there for nobody (owner, October 12). */+function showNext(env: NodeJS.ProcessEnv, state: State, yours: boolean, at: string): NextStep[] {+ if (state === 'needs-input') return [{ tell: 'tell the person; only they answer it (a question or a permission).' }]+ if (state === 'working' || state === 'unknown' || state === 'starting' || state === 'installing') return [{ run: step(env, 'wait', at), when: 'until it stops working' }]+ if (state === 'idle' && yours) return [{ run: step(env, 'close', at), when: 'once you have what you need' }]+ return []+}-/** What `ps` ends with for an agent with harnesses of its own open: how many, and how many sit idle. */-export function openNote(env: NodeJS.ProcessEnv, rows: readonly Row[]): string | null {+/**+ * What an agent's `ps` ends with: its idle harness to read and then close (one left open after its answer is read sits+ * there for nobody), its busy ones to wait for, or, with none of its own and leave to start one, a start.+ */+export function psNext(env: NodeJS.ProcessEnv, rows: readonly Row[], canStart: boolean): NextStep[] {+ const at = (r: Row) => addressOf({ machineId: '', agentId: r.id, name: r.name, engine: '' })const open = rows.filter((r) => r.yours && r.state !== 'stopped' && r.state !== 'failed')- if (!open.length) return null- const idle = open.filter((r) => r.state === 'idle').length- return `You have ${open.length} harness${open.length === 1 ? '' : 'es'} of your own open${idle ? `, ${idle} idle` : ''}. `- + `Close each once you have its answer: ${step(env, 'close', '<name>')}.`+ const idle = open.filter((r) => r.state === 'idle'), busy = open.filter((r) => r.state !== 'idle')+ const steps: NextStep[] = []+ if (idle.length) steps.push({ run: step(env, 'show', at(idle[0])), when: `read its answer, then close it: ${step(env, 'close', at(idle[0]))}` })+ if (busy.length) steps.push({ run: step(env, 'wait', busy.map(at).join(',')), when: 'until it stops working' })+ if (!open.length && canStart) {+ steps.push({ run: env[VIA_MCP_ENV] === '1' ? 'harness_start (name: "<name>", task: "<task>")' : 'harness new <agent> --name <name> <project> -- <task>',+ when: 'to hand work to another agent; do quick work yourself' })+ }+ return steps}/**@@ -613,14 +650,18 @@ export function showCommand(argv: readonly string[], deps: ClientDeps = {}): Proconst parent = o.ledger.parentOf({ machineId: t.machineId, agentId: t.frame.id })const startedBy = t.yours ? 'you' : parent ? parent.by.name : 'person'const answer = turn?.answer ?? ''+ // A name the verbs take: an unnamed harness is called by its session title, a sentence, so by its id's start.+ const at = onAway(addressOf({ machineId: '', agentId: t.frame.id, name: t.frame.name ?? '', engine: '' }), away)+ const next = showNext(s.env, state, t.yours, at)const result = {name: t.frame.name, id: t.frame.id, agent: engineName(t.frame.engine ?? ''), machine: t.machine, state, startedBy,folder: t.frame.project?.cwd ?? null, branch: t.frame.project?.branch ?? null,- ask: turn?.ask ?? null, answer: clip(answer, chars), truncated: answer.length > chars, tools: turn?.tools ?? 0,+ ask: turn?.ask ?? null, answer: clip(answer, chars), truncated: answer.length > chars, tools: turn?.tools ?? 0, next,+ ...(state === 'needs-input' ? { needsPerson: true } : {}),}if (flags.has('--json')) s.out(JSON.stringify(result, null, 1))else {- s.out(`${result.name} · ${result.agent} · ${result.machine} · ${state} · started by ${startedBy}`)+ s.out(`${result.name} on ${result.machine}: ${stateSaid(state)} · ${result.agent} · started by ${startedBy}`)s.out(`folder: ${tilde(result.folder)}${result.branch ? ` (${result.branch})` : ''}`)if (!turn) s.out('No turn yet.')else {@@ -629,9 +670,8 @@ export function showCommand(argv: readonly string[], deps: ClientDeps = {}): Pros.out(result.answer || '(no text)')if (result.truncated) s.out(`… ${answer.length - chars} more characters: ${step(s.env, 'show', onAway(result.name ?? t.frame.id, away), { flag: `--chars ${answer.length}`, arg: `chars: ${answer.length}` })}`)}- if (state === 'needs-input') s.out(`It is waiting for the person (a question or a permission). Only the person answers it.`)- // Idle and the caller's: a harness left open after its answer is read sits there for nobody (owner, October 12).- if (state === 'idle' && t.yours) s.out(closeHint(s.env, t.frame, away))+ const said = formatNext(next)+ if (said) s.out(said)}return EXIT.ok} finally { if (t?.remote) t.daemon.close(); o.daemon.close() }@@ -646,6 +686,18 @@ const CLOCK_SLACK_MS = 60_000/** `closed`: stopped or gone because the caller closed it (`harness close`, the ledger's `Closed` line). */type Settled = 'idle' | 'needs-input' | 'stopped' | 'gone' | 'closed' | 'timeout' | 'failed'+/** What to do once a wait has ended on [state], with the commands that read it, wait again, and list the stopped ones. */+function waitNext(state: string, run: { read: string; again: string; list: string }): NextStep[] {+ switch (state) {+ case 'idle': return [{ run: run.read, when: 'to read its answer' }]+ case 'needs-input': return [{ tell: 'tell the person; only they answer it (a question or a permission).' }]+ case 'timeout': case 'installing': case 'starting': return [{ run: run.again, when: 'to keep waiting' }]+ case 'stopped': return [{ run: run.read, when: 'its answer is kept' }]+ case 'gone': return [{ run: run.list, when: 'to see whether it was closed' }]+ default: return []+ }+}+export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Promise<number> {return run(WAIT_USAGE, deps, wantsJson, argv, async (s) => {const { names, flags, machine } = words(argv, { '--any': 'flag', '--timeout': 'value', '--json': 'flag' })@@ -775,10 +827,18 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Proreturn { 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))+ // A name the verbs take: quoted when it is two words, the id's start when it is a sentence (a session's title).+ const nextOf = (r: (typeof results)[number]): NextStep[] => {+ const at = onAway(addressOf({ machineId: '', agentId: r.id, name: r.name, engine: '' }), away)+ return waitNext(r.state, { read: step(s.env, 'show', at), again: step(s.env, 'wait', at),+ list: step(s.env, 'ps', away ? machineOption(away.word) : '', { flag: '--all', arg: 'all: true' }) })+ }+ if (flags.has('--json')) {+ s.out(JSON.stringify({ harnesses: results.map((r) => ({ ...r, ...(r.state === 'needs-input' ? { needsPerson: true } : {}), next: nextOf(r) })) }, null, 1))+ }else for (const r of results) {if (r.state === 'closed') { s.out(`${r.name}: closed (you closed it)`); continue }- const read = step(s.env, 'show', onAway(r.name, away))+ const read = step(s.env, 'show', onAway(addressOf({ machineId: '', agentId: r.id, name: r.name, engine: '' }), away))const next = r.state === 'idle' ? `read it: ${read}`: 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: ${read}`@@ -787,7 +847,9 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Pro// Harness closes one another agent started once it has sat idle half an hour (services/agentCleanup.ts): its// answer is still there to read.: r.state === 'stopped' ? `it was stopped; its answer is kept: ${read}` : 'it is gone'- s.out(`${r.name}: ${r.state} · ${next}`)+ s.out(`${r.name}: ${stateSaid(r.state)} · ${next}`)+ // Gone says nothing of why: whether it was closed is in the list of the stopped ones.+ if (r.state === 'gone') s.out(formatNext(nextOf(r))!)}const states = results.map((r) => r.state)return states.some((x) => x === 'timeout' || x === 'installing' || x === 'starting') ? EXIT.timeout : states.includes('needs-input') ? EXIT.needsInput@@ -831,7 +893,7 @@ export function closeCommand(argv: readonly string[], deps: ClientDeps = {}): Prreturn EXIT.ok}const name = t.frame.name ?? t.frame.id.slice(0, 8)- if (o.orphan) throw new AgentClientError('NOT_YOURS', ORPHAN)+ if (o.orphan) throw new AgentClientError('NOT_YOURS', ORPHAN, 'ORPHAN')if (o.caller && o.caller.agentId === t.frame.id && t.machineId === o.where.machineId) {throw new AgentClientError('NOT_YOURS', 'That is your own harness. The person closes it.')}@@ -857,8 +919,14 @@ export function closeCommand(argv: readonly string[], deps: ClientDeps = {}): Pr}// Closed while still starting, before its machine could read its conversation: there is none to keep.const kept = reply.withoutConversation !== true- s.out(flags.has('--json') ? JSON.stringify({ name, id: t.frame.id, closed: true, ...(kept ? {} : { conversationKept: false }) })- : kept ? `Closed ${name}. Its conversation is kept.` : `Closed ${name}. It was still starting, so no conversation was kept.`)+ const effect = kept ? 'Its conversation is kept; the person can resume it.' : 'It was still starting, so no conversation was kept.'+ // How many of its own are left, counted as `whoami` counts them, without the one just closed.+ const closedHere = t.machineId === o.where.machineId, closedId = t.frame.id+ o.frames = o.frames.filter((f) => !(closedHere && f.id === closedId))+ const open = o.caller ? contextFor(s, o).quota?.open ?? null : null+ s.out(flags.has('--json')+ ? JSON.stringify({ name, id: t.frame.id, closed: true, ...(kept ? {} : { conversationKept: false }), effect, next: [], ...(open === null ? {} : { open }) })+ : [`${name} on ${t.machine}: closed. ${effect}`, open === null ? null : `Next: nothing; you have ${open} open of ${SPAWN_LIMITS.livePerHarness}.`].filter(Boolean).join('\n'))return EXIT.ok} finally { if (t?.remote) t.daemon.close(); o.daemon.close() }})@@ -963,8 +1031,8 @@ export function addressOf(caller: Caller): string {}/** A start refused before anything is asked of the machine. */-const refusing = (code: string, message: string): NewOrigin => ({- check: async () => { throw new AgentClientError(code, message) }, prompt: (text) => text, created: async () => null, next: () => '',+const refusing = (code: string, message: string, reason?: string): NewOrigin => ({+ check: async () => { throw new AgentClientError(code, message, reason) }, prompt: (text) => text, created: async () => null, answer: () => ({ effect: '', next: [] }),})/**@@ -984,19 +1052,19 @@ export async function agentOrigin(deps: ClientDeps = {}, record: Rpc = messagesRreturn s.where().harnessPane || agentOutside ? refusing('UNKNOWN_CALLER', 'Harness could not tell who is starting this. Try again in a moment.') : null}o.daemon.close()- if (o.orphan) return refusing('NOT_YOURS', ORPHAN)+ if (o.orphan) return refusing('NOT_YOURS', ORPHAN, 'ORPHAN')const caller = o.callerif (!caller) return null// The person's say: the account's experiment, as the machine the agent runs on keeps it (Settings ▸ Experimental,// `harness settings`).- if (!readAgentSettings(o.where.dataDir).agentsStartAgents) return refusing('TURNED_OFF', AGENTS_START_AGENTS_OFF)+ if (!readAgentSettings(o.where.dataDir).agentsStartAgents) return refusing('TURNED_OFF', AGENTS_START_AGENTS_OFF, 'SWITCH_OFF')return {// 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 = spawnCheck(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)+ if (refusal) throw new AgentClientError('SPAWN_LIMIT', refusal.message, refusal.reason)},existing: async (name, asking) => {if (!name?.trim()) return null@@ -1077,9 +1145,15 @@ export async function agentOrigin(deps: ClientDeps = {}, record: Rpc = messagesRreturn `${name || 'The harness'} runs on a machine whose Harness did not record who started it: there, its limits start from zero.`}},- next: (agent) => {- const at = addressOf({ machineId: '', agentId: String(agent.id ?? ''), name: String(agent.name ?? ''), engine: '' })- return `Read it: ${step(s.env, 'show', at)} · wait for it: ${step(s.env, 'wait', at)}`+ answer: (agent, at) => {+ const name = addressOf({ machineId: '', agentId: String(agent.id ?? ''), name: String(agent.name ?? ''), engine: '' })+ // Under MCP the tools take no machine: harness_wait finds the caller's own by its record, on any machine.+ const target = at.local || at.machine === null || s.env[VIA_MCP_ENV] === '1' ? name : `${machineOption(at.machine)} ${name}`+ return {+ // The windows open it beside the caller's pane only for a harness in a pane on this computer.+ effect: caller.outside || !at.local ? 'The person sees it in Harness.' : 'The person sees it in Harness, beside you.',+ next: [{ run: step(s.env, 'wait', target), when: `until it has answered; then read it: ${step(s.env, 'show', target)}` }],+ }},}}diff --git a/cli/src/agentClient/daemon.ts b/cli/src/agentClient/daemon.tsindex 46b7ef814..5cc7e275f 100644--- a/cli/src/agentClient/daemon.ts+++ b/cli/src/agentClient/daemon.ts@@ -15,7 +15,8 @@ import { localSocketPath } from '../lib/localSocket.js'import { paneOwner } from '../messages/command.js'export class AgentClientError extends Error {- constructor(readonly code: string, message: string) { super(message) }+ /** [reason]: which limit or rule refused, for a refusal (`SPAWN_LIMIT`'s `OPEN_LIMIT`, `TURNED_OFF`'s `SWITCH_OFF`). */+ constructor(readonly code: string, message: string, readonly reason?: string) { super(message) }}/** Which daemon: its port and data folder, and this machine's id as the daemon knows it. */diff --git a/cli/src/agentClient/help.spec.ts b/cli/src/agentClient/help.spec.tsnew file mode 100644index 000000000..ed95e97c5--- /dev/null+++ b/cli/src/agentClient/help.spec.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest'+import { CLOSE_USAGE, EXIT, PS_USAGE, SHOW_USAGE, WAIT_USAGE, WHOAMI_USAGE } from './commands.js'+import { NEW_USAGE } from '../lib/newCommand.js'+import { agentsHelp, helpFor } from './help.js'++const synopsis = (usage: string) => usage.split('\n')[0].replace(/^Usage: /, '')++describe('harness help agents', () => {+ it('fits in 40 lines and names each verb as its usage does', () => {+ const text = agentsHelp()+ expect(text.split('\n').length).toBeLessThanOrEqual(40)+ for (const usage of [WHOAMI_USAGE, PS_USAGE, NEW_USAGE, WAIT_USAGE, SHOW_USAGE, CLOSE_USAGE]) expect(text).toContain(synopsis(usage))+ expect(text).toContain('harness send <name>[,<name>] "text"')+ })+ it('lists every exit code', () => {+ for (const code of Object.values(EXIT)) expect(agentsHelp()).toMatch(new RegExp(`\\b${code} `))+ })+ it('uses placeholders, never a real name', () => {+ expect(agentsHelp()).not.toMatch(/--(machine|name) (?![<\[])/)+ })+})++describe('harness --help', () => {+ const full = 'harness vX — connect this computer to your machine\n…'+ it('points an agent to its help on the first line, and leaves the rest as it was', () => {+ expect(helpFor({}, full)).toBe(`An agent? Run: harness help agents\n${full}`)+ })+ it('puts the agents\' help first when an agent asks', () => {+ expect(helpFor({ CODEX_THREAD_ID: 't' }, full).startsWith(agentsHelp())).toBe(true)+ expect(helpFor({ AI_AGENT: 'cursor' }, full).startsWith(agentsHelp())).toBe(true)+ expect(helpFor({ CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's' }, full).endsWith(full)).toBe(true)+ })+})diff --git a/cli/src/agentClient/help.ts b/cli/src/agentClient/help.tsnew file mode 100644index 000000000..a53832d6c--- /dev/null+++ b/cli/src/agentClient/help.ts@@ -0,0 +1,53 @@+/**+ * `harness help agents`: all an agent needs on one screen (docs/design/2026-10-15-agent-experience.md, part 4). Each+ * verb's line is its own usage's first line, so this cannot name an option the verb does not take.+ */+import { CLOSE_USAGE, EXIT, PS_USAGE, SHOW_USAGE, SPAWN_LIMITS, WAIT_USAGE, WHOAMI_USAGE } from './commands.js'+import { NEW_USAGE } from '../lib/newCommand.js'+import { SEND_USAGE } from '../messages/command.js'+import { outsideCaller } from './model.js'++const synopsis = (usage: string): string => usage.split('\n')[0].replace(/^Usage: /, '')+const sendLine = (): string => (SEND_USAGE.split('\n').find((l) => l.includes('harness send <name>[,<name>]')) ?? '').trim().split(/\s{2,}/)[0]++export function agentsHelp(): string {+ return [+ 'Harness for agents: start other agents, wait for them, read their answers, close them,',+ 'on this computer or another of the person\'s machines (--machine <machine>).',+ 'Every harness spends the person\'s tokens: start one only for work that runs beside yours,',+ 'needs another model\'s view, or takes long. Do quick work yourself.',+ '',+ `First: ${synopsis(WHOAMI_USAGE)} who you are here, and whether you may start harnesses`,+ `Then: ${synopsis(PS_USAGE)}`,+ ` ${synopsis(NEW_USAGE)}`,+ ` ${synopsis(WAIT_USAGE)}`,+ ` ${synopsis(SHOW_USAGE)}`,+ ` ${synopsis(CLOSE_USAGE)}`,+ ` ${sendLine()}`,+ '',+ 'A whole job:',+ ' harness new <agent> --name <name> <project> -- <task>',+ ' harness wait <name>',+ ' harness show <name>',+ ' harness close <name>',+ 'Every command ends with Next: the command to run next. --json gives it as "next".',+ '',+ 'States: working, idle, needs the person, installing, starting, stopped, gone, closed, failed.',+ `Exit codes: ${EXIT.ok} done · ${EXIT.failed} failed · ${EXIT.usage} wrong command · ${EXIT.needsInput} needs the person · `+ + `${EXIT.stopped} stopped or gone · ${EXIT.refused} refused (do not retry) · ${EXIT.timeout} still working when the wait ended.`,+ `Limits: ${SPAWN_LIMITS.livePerHarness} of yours open at once, ${SPAWN_LIMITS.perWindow} starts in ${SPAWN_LIMITS.windowMs / 60_000} minutes;`,+ 'a harness another agent started may not start harnesses.',+ 'Rules: name every harness. Put the whole task in it: you cannot message it after.',+ 'Close what you started once you have its answer. Never close one you did not start.',+ 'When a harness needs the person, tell the person: only they answer it.',+ 'Never ask a harness to publish, deploy, delete or push.',+ '',+ 'More: https://harness.autonomous.ai/agents',+ ].join('\n')+}++/** `harness --help`: a line for agents first; an agent asking (by what its shell sets) gets its own help before the rest. */+export function helpFor(env: NodeJS.ProcessEnv, full: string): string {+ const text = `An agent? Run: harness help agents\n${full}`+ return outsideCaller(env, '') ? `${agentsHelp()}\n\n${text}` : text+}diff --git a/cli/src/agentClient/mcp.spec.ts b/cli/src/agentClient/mcp.spec.tsindex f484cb6c3..d5d1e052f 100644--- a/cli/src/agentClient/mcp.spec.ts+++ b/cli/src/agentClient/mcp.spec.ts@@ -170,7 +170,10 @@ describe('harness mcp', () => {expect(result('harness_close', { code: 1, out: '', err: 'You did not start x, so you may not close it.\n' })).toEqual({ content: [{ type: 'text', text: 'You did not start x, so you may not close it.' }], isError: true })expect(result('harness_read', { code: 2, out: '', err: '' })).toEqual({ content: [{ type: 'text', text: 'harness exited 2' }], isError: true })- expect(result('harness_wait', { code: 3, out: 'a: needs-input\n', err: '' })).toEqual({ content: [{ type: 'text', text: 'a: needs-input' }] })+ expect(result('harness_wait', { code: 3, out: 'a: needs the person\n', err: '' })).toEqual({ content: [{ type: 'text', text: 'a: needs the person' }] })+ // A refusal is an answer: the agent should not retry it as it would a failure.+ expect(result('harness_close', { code: 5, out: '', err: 'You did not start x, so you may not close it. Only the person can.\n' }))+ .toEqual({ content: [{ type: 'text', text: 'You did not start x, so you may not close it. Only the person can.' }] })expect(result('harness_wait', { code: 4, out: 'a: stopped\n', err: '' }).isError).toBeUndefined()expect(result('harness_wait', { code: 124, out: 'a: working\n', err: '' })).toEqual({ content: [{ type: 'text', text: 'a: working\nStill working. Call harness_wait again to keep waiting.' }] })expect(result('harness_wait', { code: 124, out: '', err: '' }).content[0].text).toBe('Still working. Call harness_wait again to keep waiting.')diff --git a/cli/src/agentClient/mcp.ts b/cli/src/agentClient/mcp.tsindex 2b7043788..7d1c113b1 100644--- a/cli/src/agentClient/mcp.ts+++ b/cli/src/agentClient/mcp.ts@@ -27,7 +27,9 @@ Every harness spends the person's tokens. Start one (harness_start) only for worCall harness_whoami first: it says whether you may start harnesses now. Then list (harness_list). Put everything in the task: starting a harness does not let you message it. A follow-up goes by harness_send only to a teammate in your tab, while Agent Messages are on; otherwise start a new harness with the fuller task. Never give work to, or close, a harness you did not start: those are the person's.-Name every harness. Then wait for it (harness_wait), read its answer (harness_read), and close it once you have its answer (harness_close). At most 4 of yours at once, and a harness another agent started may not start harnesses itself. Never ask a harness to publish, deploy, delete or push.`+Name every harness. Then wait for it (harness_wait), read its answer (harness_read), and close it once you have its answer (harness_close). At most 4 of yours at once, and a harness another agent started may not start harnesses itself. Never ask a harness to publish, deploy, delete or push.++Each answer ends with Next: the call to make next. A refusal is final: do not retry it; tell the person, or do the work yourself.`/** 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@@ -57,7 +59,7 @@ export const TOOLS: Tool[] = [},{name: 'harness_list',- description: 'The harnesses on this machine: name, agent, state (working, idle, needs-input), who started each ("you" for yours), when it was last active, its folder, and what it is about.',+ description: 'The harnesses on this machine: name, agent, state (working, idle, needs the person), who started each ("you" for yours), when it was last active, its folder, and what it is about.',inputSchema: schema({ all: { type: 'boolean', description: 'Also the ones stopped in the last week.' } }),annotations: { readOnlyHint: true },argv: (a) => ['ps', ...(a.all === true ? ['--all'] : [])],@@ -234,7 +236,8 @@ export function result(tool: string, ran: Ran): { content: Array<{ type: 'text';if (tool === 'harness_wait' && ran.code === EXIT.timeout) {return { content: [{ type: 'text', text: `${text ? `${text}\n` : ''}Still working. Call harness_wait again to keep waiting.` }] }}- const answered = ran.code === EXIT.ok || (tool === 'harness_wait' && (ran.code === EXIT.needsInput || ran.code === EXIT.stopped))+ // A refusal is an answer too: an error invites a retry, and a refusal is not retried.+ const answered = ran.code === EXIT.ok || ran.code === EXIT.refused || (tool === 'harness_wait' && (ran.code === EXIT.needsInput || ran.code === EXIT.stopped))return answered ? { content: [{ type: 'text', text: text || 'Done.' }] } : { content: [{ type: 'text', text: text || `harness exited ${ran.code}` }], isError: true }}diff --git a/cli/src/agentClient/model.spec.ts b/cli/src/agentClient/model.spec.tsindex 5e9b56a5e..806181a63 100644--- a/cli/src/agentClient/model.spec.ts+++ b/cli/src/agentClient/model.spec.ts@@ -3,7 +3,22 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'import { Ledger, ledgerPath } from './ledger.js'-import { asSaid, callerOf, clip, lastTurn, matching, outsideCaller, rowsOf, stateOf, STOPPED_WITHIN_MS, type Frame } from './model.js'+import { asSaid, callerOf, clip, forAgent, lastTurn, matching, outsideCaller, rowsOf, stateOf, STOPPED_WITHIN_MS, type Frame, type Row } from './model.js'++describe('forAgent', () => {+ const row = (name: string, over: Partial<Row> = {}): Row => ({ name, id: name, agent: 'Codex', machine: 'm', state: 'idle', folder: null, branch: null,+ startedBy: 'person', yours: false, self: false, lastActive: null, ...over })+ it('puts its own first, then the working and the ones needing the person, then the rest, and counts the rest past 15', () => {+ const rows = [...Array.from({ length: 30 }, (_, i) => row(`idle${i}`)), row('busy', { state: 'working' }), row('mine1', { yours: true }), row('mine2', { yours: true })]+ const { shown, more } = forAgent(rows)+ expect(shown.map((r) => r.name).slice(0, 3)).toEqual(['mine1', 'mine2', 'busy'])+ expect(shown).toHaveLength(15)+ expect(more).toBe(18)+ })+ it('shows every row when there are 15 or fewer', () => {+ expect(forAgent([row('a'), row('b')])).toEqual({ shown: [row('a'), row('b')], more: 0 })+ })+})const dirs: string[] = []const ledger = (): Ledger => {diff --git a/cli/src/agentClient/model.ts b/cli/src/agentClient/model.tsindex 0f6c304e2..59f61d6c6 100644--- a/cli/src/agentClient/model.ts+++ b/cli/src/agentClient/model.ts@@ -151,6 +151,16 @@ export function rowsOf(frames: Frame[], ctx: RowContext): Row[] {return rows.sort((a, b) => rank(a) - rank(b) || (b.lastActive ?? '').localeCompare(a.lastActive ?? ''))}+/** How many rows an agent's `ps` shows unless asked for all: on the owner's Mac, 40 rows became about 8 to read. */+export const AGENT_ROWS = 15++/** An agent's `ps`: its own first, then those working or waiting on the person, then the rest; [max] at most. */+export function forAgent(rows: readonly Row[], max = AGENT_ROWS): { shown: Row[]; more: number } {+ const busy = (r: Row) => r.state === 'working' || r.state === 'needs-input'+ const ordered = [...rows.filter((r) => r.yours), ...rows.filter((r) => !r.yours && busy(r)), ...rows.filter((r) => !r.yours && !busy(r))]+ return { shown: ordered.slice(0, max), more: Math.max(0, ordered.length - max) }+}+/** The rows [name] means: a whole name, else a name's start, else an id's start (six characters or more). */export function matching<T extends { name: string; id: string }>(name: string, rows: T[]): T[] {const wanted = name.trim().toLowerCase()diff --git a/cli/src/agentClient/next.spec.ts b/cli/src/agentClient/next.spec.tsnew file mode 100644index 000000000..88e0aab54--- /dev/null+++ b/cli/src/agentClient/next.spec.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from 'vitest'+import { formatNext } from './next.js'++describe('Next', () => {+ it('says one step on one line, with when to take it', () => {+ expect(formatNext([{ run: 'harness wait <name>', when: 'until it has answered' }])).toBe('Next: harness wait <name> (until it has answered)')+ })+ it('gives the other steps as "or"', () => {+ expect(formatNext([{ run: 'harness show <name>', when: 'to read its answer' }, { run: 'harness wait <name>', when: 'until it stops working' }]))+ .toBe('Next: harness show <name> (to read its answer)\n or: harness wait <name> (until it stops working)')+ })+ it('says a step that is not a command as it is', () => {+ expect(formatNext([{ tell: 'tell the person; only they answer it (a question or a permission).' }]))+ .toBe('Next: tell the person; only they answer it (a question or a permission).')+ })+ it('says nothing when there is nothing next', () => {+ expect(formatNext([])).toBeNull()+ })+})diff --git a/cli/src/agentClient/next.ts b/cli/src/agentClient/next.tsnew file mode 100644index 000000000..f37e5266d--- /dev/null+++ b/cli/src/agentClient/next.ts@@ -0,0 +1,13 @@+/**+ * What every agent verb ends with (docs/design/2026-10-15-agent-experience.md, part 2): the step to take next, and+ * when to take it, so an agent is never left to guess. `--json` carries the same steps as `next`.+ */++/** A command to run and when to pick it, or something only words can say ("tell the person …"). */+export type NextStep = { run: string; when: string } | { tell: string }++/** `Next: <command> (<when>)`, then ` or: …` for the other choices; null when there is nothing next. */+export function formatNext(steps: readonly NextStep[]): string | null {+ if (!steps.length) return null+ return steps.map((step, i) => `${i ? ' or:' : 'Next:'} ${'run' in step ? `${step.run} (${step.when})` : step.tell}`).join('\n')+}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 14181a069..fd4351829 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -98,7 +98,8 @@ const LOG_FILE = DAEMON_LOG_FILEfunction usage(exitCode = 0): never {- console.log(`harness v${VERSION} — connect this computer to your machine+ // An agent is pointed to its own help first (agentClient/help.ts); one that asks gets it before the rest.+ console.log(helpFor(process.env, `harness v${VERSION} — connect this computer to your machineAgents — after "harness start", run the vendor CLI directly inside tmux. Harness discovers supportedtop-level processes automatically; it does not launch them or change their permission flags:@@ -153,6 +154,7 @@ Machine:new, ps, show, wait and close take --machine <name> for another of yourmachines: \`harness show --machine office x\`harness mcp the agent verbs as an MCP server on stdin/stdout, for agents that use MCP+ harness help agents the agent commands, states, exit codes and rules on one screenharness settings [<name> on|off] what agents may do (agents-start-agents, pull-request-line, agent-messages): your account's experiments in Settings ▸ Experimental, each off by defaultharness machines delete <id> remove ANOTHER machine (refuses this one; use \`harness logout\`)harness remote from a Harness terminal tile: open a terminal on another of your machines and move this tile to it@@ -224,7 +226,7 @@ making a new one. Deleting it (or ~/.harness) makes this look like a brand-new cno durable home, a container or CI job, pin ADAPTER_COMPUTER_ID instead.Env: BACKEND_WS_URL (${env.BACKEND_WS_URL}), WEB_URL (${env.WEB_URL}), ADAPTER_DATA_DIR,- ADAPTER_COMPUTER_ID, CLAUDE_PROJECTS_DIR, PORT`)+ ADAPTER_COMPUTER_ID, CLAUDE_PROJECTS_DIR, PORT`))process.exit(exitCode)}@@ -2499,6 +2501,7 @@ async function logsExportCommand(json: boolean): Promise<void> {import { orchestratorCommand } from './orchestrator/command.js'import { paneOwner, sendCommand } from './messages/command.js'import { agentOrigin, closeCommand, psCommand, showCommand, waitCommand, whoamiCommand } from './agentClient/commands.js'+import { agentsHelp, helpFor } from './agentClient/help.js'import { openUrlCommand } from './agentClient/openUrl.js'import { harnessRunner, mcpCommand } from './agentClient/mcp.js'import { settingsCommand } from './agentClient/settings.js'@@ -2525,6 +2528,7 @@ function withoutFirst(argv: string[], token: string): string[] {return at < 0 ? argv : [...argv.slice(0, at), ...argv.slice(at + 1)]}+if (cmd === 'help' && args[0] === 'agents') { console.log(agentsHelp()); process.exit(0) }if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') usage()if (cmd === 'version' || cmd === '--version' || cmd === '-v') { console.log(VERSION); process.exit(0) }diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.tsindex f37242533..7392e4140 100644--- a/cli/src/lib/newCommand.spec.ts+++ b/cli/src/lib/newCommand.spec.ts@@ -5,6 +5,7 @@ import { tmpdir } from 'node:os'import { join } from 'node:path'import { newAgentPayload, newCommand, NewUsageError, parseNewArgs, resolveNewMachine, trustAsked, type NewCommandDeps, type NewSocket } from './newCommand.js'import { SANDBOXED } from './unreachable.js'+import { AgentClientError } from '../agentClient/daemon.js'const env = { cwd: '/work/repo', home: '/home/me' }@@ -398,12 +399,12 @@ describe('harness new: the daemon', () => {// 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,+ const origin = { check: async () => {}, prompt: (text: string) => text, created: async () => null, answer: () => ({ effect: '', next: [] }), existing: async () => null,pending: (machineId: string, creation: Record<string, unknown>) => { pending.push([machineId, creation]) } }- const run = async (env: NodeJS.ProcessEnv, json = false) => {+ const run = async (env: NodeJS.ProcessEnv, json = false, name = 'cx') => {let clock = 0const 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,+ const d = deps(['codex', '--name', name, ...(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)@@ -411,36 +412,43 @@ describe('harness new: the daemon', () => {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.out).toEqual(['cx on this computer: installing Codex. It starts by itself once installed; do not start it again.\n'+ + 'Next: harness_wait (names: "cx") (until it has started and answered)'])expect(mcp.d.err).toEqual([])const creationId = mcp.socket.sent.find((f) => f.type === 'agent_create')!.payload.creationIdexpect(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.'])+ expect(shell.d.out).toEqual(['cx on this computer: installing Codex. It starts by itself once installed; do not start it again.\n'+ + 'Next: harness wait cx (until it has started and answered)'])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.parse(json.d.out[0]!)).toMatchObject({ ok: true, pending: true, machineId: 'm2', name: 'cx',+ next: [{ run: 'harness_wait (names: "cx")', when: 'until it has started and answered' }] })expect(json.d.err).toEqual([])+ // A name of two words: one name to wait on, as the shell takes it and as the tool does.+ const spaced = await run({}, false, 'code review')+ expect(spaced.d.out[0]!.split('\n').at(-1)).toBe('Next: harness wait "code review" (until it has started and answered)')+ const spacedMcp = await run({ HARNESS_VIA_MCP: '1' }, false, 'code review')+ expect(spacedMcp.d.out[0]!.split('\n').at(-1)).toBe('Next: harness_wait (names: "code review") (until it has started and answered)')})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 = 0const 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: () => {} }+ const origin = { check: async () => { clock += 45_000 }, prompt: (text: string) => text, created: async () => null, answer: () => ({ effect: '', next: [] }), pending: () => {} }let asks = 0const 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.'])+ expect(d.out).toEqual(['The harness on this computer: installing Codex. It starts by itself once installed; do not start it again.\n'+ + 'Next: harness ps (to follow it)'])})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 origin = { check: async () => {}, prompt: (text: string) => text, created: async () => null, answer: () => ({ effect: '', 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 } })@@ -452,7 +460,7 @@ describe('harness new: the daemon', () => {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: () => '',+ const origin = { check: async () => { throw new Error('not reached') }, prompt: (text: string) => text, created: async () => null, answer: () => ({ effect: '', 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@@ -469,7 +477,7 @@ describe('harness new: the daemon', () => {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: () => {},+ const origin = { check: async () => {}, prompt: (text: string) => text, answer: () => ({ effect: '', 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)@@ -484,6 +492,23 @@ describe('harness new: the daemon', () => {expect(d.out[0]).toBe('Created fixer on this computer in /work/repo/.worktrees/x.')})+ it('exits 5 when the agent is refused, and says why in JSON beside the old error', async () => {+ const message = 'You have 4 harnesses running. Close one you are done with first (harness close <name>).'+ const origin = { check: async () => { throw new AgentClientError('SPAWN_LIMIT', message, 'OPEN_LIMIT') },+ prompt: (text: string) => text, created: async () => null, answer: () => ({ effect: '', next: [] }) }+ const text = deps(['codex', '--name', 'x'], new FakeSocket(() => null), { origin: async () => origin })+ expect(await newCommand(text)).toBe(5)+ expect(text.err).toEqual([message])+ const json = deps(['codex', '--name', 'x', '--json'], new FakeSocket(() => null), { origin: async () => origin })+ expect(await newCommand(json)).toBe(5)+ expect(JSON.parse(json.out[0]!)).toEqual({ ok: false, error: message, code: 'SPAWN_LIMIT', reason: 'OPEN_LIMIT',+ next: [{ run: 'harness close <name>', when: 'one you are done with, to free a place' }] })+ // Not a refusal: a failure, as before.+ const failing = deps(['codex', '--json'], new FakeSocket(() => null), { origin: async () => ({ ...origin, check: async () => { throw new Error('broke') } }) })+ expect(await newCommand(failing)).toBe(1)+ expect(JSON.parse(failing.out[0]!)).toEqual({ ok: false, error: 'broke' })+ })+it('run by an agent: checks its limits, heads its task with who sent it, records it, and says how to follow it', async () => {const created: Array<[string, Record<string, unknown>]> = []let warning: string | null = null@@ -491,7 +516,8 @@ describe('harness new: the daemon', () => {check: async () => {},prompt: (text: string, machineId: string) => `[from lead on ${machineId}]\n\n${text}`,created: async (machineId: string, agent: Record<string, unknown>) => { created.push([machineId, agent]); return warning },- next: (agent: Record<string, unknown>) => `Read it: harness show ${String(agent.name)}`,+ answer: (agent: Record<string, unknown>) => ({ effect: 'The person sees it in Harness, beside you.',+ next: [{ run: `harness wait ${String(agent.name)}`, when: `until it has answered; then read it: harness show ${String(agent.name)}` }] }),}const socket = new FakeSocket((frame) => frame.type === 'agent_create' ? { state: 'created', agent: { id: 'a9', name: 'reviewer' } } : null)const d = deps(['codex', '--name', 'reviewer', '--', 'review', 'it'], socket, { origin: async () => origin })@@ -500,7 +526,14 @@ describe('harness new: the daemon', () => {// The machine records that an agent started it: the pull requests it opens say so (lib/agentAttribution.ts).expect(socket.sent[1]!.payload.startedBy).toBe('agent')expect(created).toEqual([['m2', { id: 'a9', name: 'reviewer' }]])- expect(d.out[1]).toBe('Read it: harness show reviewer')+ // Starting, never started the task; what changed; and what to run next.+ expect(d.out).toEqual(['reviewer on this computer: starting. Codex, in /work/repo.', 'The person sees it in Harness, beside you.',+ 'Next: harness wait reviewer (until it has answered; then read it: harness show reviewer)'])+ const json = deps(['codex', '--name', 'reviewer', '--json', '--', 'review', 'it'], new FakeSocket((frame) => frame.type === 'agent_create'+ ? { state: 'created', agent: { id: 'a9', name: 'reviewer' } } : null), { origin: async () => origin })+ expect(await newCommand(json)).toBe(0)+ expect(JSON.parse(json.out[0]!)).toMatchObject({ ok: true, agent: { id: 'a9' }, effect: 'The person sees it in Harness, beside you.',+ next: [{ run: 'harness wait reviewer', when: 'until it has answered; then read it: harness show reviewer' }] })// No task: nothing to head.const quiet = new FakeSocket((frame) => frame.type === 'agent_create' ? { state: 'created', agent: { id: 'b1', name: 'idle' } } : null)expect(await newCommand(deps(['codex'], quiet, { origin: async () => origin }))).toBe(0)@@ -551,7 +584,7 @@ describe('harness new: the daemon', () => {it('run by a harness here: names it as the one that started the new harness, so the windows open it beside it', async () => {const origin = {- check: async () => {}, prompt: (text: string) => text, created: async () => null, next: () => '', parentAgentId: 'lead-agent',+ check: async () => {}, prompt: (text: string) => text, created: async () => null, answer: () => ({ effect: '', next: [] }), parentAgentId: 'lead-agent',}const created = (id: string) => new FakeSocket((frame) => frame.type === 'fs_list_dir' ? { path: '/Users/mini', entries: [] }: frame.type === 'agent_create' ? { state: 'created', agent: { id, name: id } } : null)@@ -628,7 +661,7 @@ const agentStarting = () => {check: async () => {},prompt: (text: string) => text,created: async (_machineId: string, agent: Record<string, unknown>) => { created.push(String(agent.id)); return null },- next: () => 'Read it: harness show it',+ answer: () => ({ effect: '', next: [{ run: 'harness show it', when: 'to read it' }] }),},}}@@ -711,7 +744,7 @@ describe('harness new: a folder the engine would ask about', () => {c.claudeTrusts(realpathSync(scratch))const trusted = deps(['claude', scratch, '--', 'go'], creating({ id: 'a1', name: 'opinion' }), { origin: async () => origin, env: c.env, home: c.home })expect(await newCommand(trusted)).toBe(0)- expect(trusted.out).toEqual([`Created opinion on this computer in ${scratch}.`, 'Read it: harness show it'])+ expect(trusted.out).toEqual([`opinion on this computer: starting. Claude Code, in ${scratch}.`, 'Next: harness show it (to read it)'])})it('starts an agent\'s harness in a folder with content, and says it will wait for the person to trust it', async () => {@@ -721,17 +754,17 @@ describe('harness new: a folder the engine would ask about', () => {const shell = deps(['codex', work, '--name', 'reviewer', '--', 'review it'], creating({ id: 'a1', name: 'reviewer' }), { origin: async () => origin, env: c.env, home: c.home })expect(await newCommand(shell)).toBe(0)expect(shell.out).toEqual([- `Created reviewer on this computer in ${work}.`,+ `reviewer on this computer: starting. Codex, in ${work}.`,`Codex will ask the person to trust ${work} before it starts, so it waits for them until they answer (harness wait exits 3). `+ 'For new work, a project name avoids this: harness new codex reviewer --name reviewer -- …',- 'Read it: harness show it',+ 'Next: harness show it (to read it)',])expect(created).toEqual(['a1'])const viaMcp = deps(['claude', work, '--name', 'reviewer', '--', 'review it'], creating({ id: 'a2', name: 'reviewer' }),{ origin: async () => origin, env: { ...c.env, HARNESS_VIA_MCP: '1' }, home: c.home })expect(await newCommand(viaMcp)).toBe(0)expect(viaMcp.out[1]).toBe(`Claude Code will ask the person to trust ${work} before it starts, so it waits for them until they answer `- + '(harness_wait says needs-input). For new work, a project name avoids this: harness_start (project: "reviewer", …)')+ + '(harness_wait says it needs the person). For new work, a project name avoids this: harness_start (project: "reviewer", …)')const json = deps(['codex', work, '--json', '--', 'go'], creating({ id: 'a3', name: 'x' }), { origin: async () => origin, env: c.env, home: c.home })expect(await newCommand(json)).toBe(0)expect(JSON.parse(json.out[0]!)).toMatchObject({ ok: true, agent: { id: 'a3' }, note: expect.stringContaining('Codex will ask the person to trust') })@@ -739,7 +772,7 @@ describe('harness new: a folder the engine would ask about', () => {c.codexTrusts(realpathSync(work))const trusted = deps(['codex', work, '--', 'go'], creating({ id: 'a4', name: 'x' }), { origin: async () => origin, env: c.env, home: c.home })expect(await newCommand(trusted)).toBe(0)- expect(trusted.out).toEqual([`Created x on this computer in ${work}.`, 'Read it: harness show it'])+ expect(trusted.out).toEqual([`x on this computer: starting. Codex, in ${work}.`, 'Next: harness show it (to read it)'])})it('leaves the person at a terminal, another machine, and a store harness\'s empty folder as they were', async () => {@@ -754,13 +787,13 @@ describe('harness new: a folder the engine would ask about', () => {// Another machine's folders and settings are not here to read.const far = deps(['claude', '--machine', 'mini', scratch], creating({ id: 'f1', name: 'far' }), { origin: async () => origin, env: c.env, home: c.home })expect(await newCommand(far)).toBe(0)- expect(far.out).toEqual([`Created far on Mac mini in ${scratch}.`, 'Read it: harness show it'])+ expect(far.out).toEqual([`far on Mac mini: starting. Claude Code, in ${scratch}.`, 'Next: harness show it (to read it)'])// A store harness lays its template into an empty folder, which is then trusted; one with content is still asked about.const store = (folder: string) => new FakeSocket((frame) => frame.type === 'dsh_list' ? { dsh: [{ id: 'owner/kit', engine: 'claude', installed: true }] }: frame.type === 'agent_create' ? { state: 'created', agent: { id: 's1', name: 'kit' } } : null)const empty = deps(['owner/kit', scratch], store(scratch), { origin: async () => origin, env: c.env, home: c.home })expect(await newCommand(empty)).toBe(0)- expect(empty.out).toEqual([`Created kit on this computer in ${scratch}.`, 'Read it: harness show it'])+ expect(empty.out).toEqual([`kit on this computer: starting. Claude Code, in ${scratch}.`, 'Next: harness show it (to read it)'])const full = deps(['owner/kit', work], store(work), { origin: async () => origin, env: c.env, home: c.home })expect(await newCommand(full)).toBe(0)expect(full.out[1]).toBe(`Claude Code will ask the person to trust ${work} before it starts, so it waits for them until they answer `diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.tsindex 4027d9ff1..e5d7ff551 100644--- a/cli/src/lib/newCommand.ts+++ b/cli/src/lib/newCommand.ts@@ -1,7 +1,9 @@import { randomUUID } from 'node:crypto'import { readdir, readFile, realpath } from 'node:fs/promises'import { dirname, isAbsolute, join, resolve } from 'node:path'-import { addressOf, atMachineRefusal, machineOption, step, VIA_MCP_ENV } from '../agentClient/commands.js'+import { addressOf, atMachineRefusal, EXIT, machineOption, refusalNext, REFUSED_CODES, step, VIA_MCP_ENV } from '../agentClient/commands.js'+import { AgentClientError } from '../agentClient/daemon.js'+import { formatNext, type NextStep } from '../agentClient/next.js'import { folderTrust } from '../engines/launchPrep.js'import { ENGINES, type AgentEngine } from '../engines/types.js'import { engineName } from '../messages/model.js'@@ -69,6 +71,8 @@ export const NEW_USAGE = [' harness new codex -- fix the flaky login test',' --name <n> the harness\'s name until the agent titles its session',' --json print the result as one JSON line',+ '',+ 'An agent refused (its limits, or the person has not let agents start agents) exits 5: do not retry.',].join('\n')const MODES = new Set(['auto', 'ask', 'plan', 'full'])@@ -273,8 +277,8 @@ export interface NewOrigin {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+ /** What the start changed, and what to run next: wait for it, then read it. */+ answer(agent: Record<string, unknown>, at: { local: boolean; machine: string | null }): { effect: string; next: NextStep[] }/** The caller's own harness, by agent id, when it is one on this computer: a harness started here records it, and the* windows open it beside the caller's pane. Absent for an agent outside Harness. */parentAgentId?: string@@ -509,7 +513,7 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {// With content it may be just what the work needs, so it starts; the agent is told it will wait for the person.if (asks === 'content') {trustNote = `${engineName(engine)} will ask the person to trust ${cwd} before it starts, so it waits for them until `- + `they answer (${env[VIA_MCP_ENV] === '1' ? 'harness_wait says needs-input' : 'harness wait exits 3'}). `+ + `they answer (${env[VIA_MCP_ENV] === '1' ? 'harness_wait says it needs the person' : 'harness wait exits 3'}). `+ `For new work, a project name avoids this: ${instead}`}}@@ -557,9 +561,13 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {// 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)+ // Under MCP the tools take no machine: harness_wait finds the caller's own by its record.+ // One name as the shell takes it: quoted when it has a space (the MCP tool call quotes it once, `step`).+ const word = /^[\w.:-]+$/.test(name) ? name : `"${name.replace(/(["\\$`])/g, '\\$1')}"`+ const at = local || args.machine === null || env[VIA_MCP_ENV] === '1' ? word : `${machineOption(args.machine)} ${word}`+ const next: NextStep[] = name ? [{ run: step(env, 'wait', at), when: 'until it has started and answered' }] : [{ run: step(env, 'ps'), when: 'to follow it' }]+ const note = `${name || 'The harness'} on ${machineLabel}: installing ${engineName(String(payload.engine))}. It starts by itself once installed; do not start it again.`+ deps.output(args.json ? JSON.stringify({ ok: true, pending: true, machineId, creationId, name, note, next }) : `${note}\n${formatNext(next)}`)return 0}if (result.state === 'pending') {@@ -593,14 +601,25 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {const agent = (result.agent ?? {}) as Record<string, unknown>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 {+ // An agent is told it is starting (never that its task is done), what changed, and what to run next.+ const told = origin?.answer(agent, { local, machine: args.machine })+ if (args.json) deps.output(JSON.stringify({ ok: true, machineId, agent, ...(trustNote ? { note: trustNote } : {}), ...(told ? { effect: told.effect, next: told.next } : {}) }))+ else if (origin && told) {+ const project = (agent.project ?? {}) as Record<string, unknown>+ const folder = typeof project.cwd === 'string' ? project.cwd : cwd+ const name = String(agent.name ?? agent.id ?? 'The harness')+ deps.output(`${name} on ${machineLabel}: starting. ${engineName(String(agent.engine ?? payload.engine ?? ''))}${folder ? `, in ${folder}` : ''}.`)+ if (told.effect) deps.output(told.effect)+ if (trustNote) deps.output(trustNote)+ const next = formatNext(told.next)+ if (next) deps.output(next)+ } else {const project = (agent.project ?? {}) as Record<string, unknown>const where = typeof project.cwd === 'string' ? ` in ${project.cwd}` : cwd ? ` in ${cwd}` : ''const name = String(agent.name ?? agent.id ?? 'a harness')deps.output(`Created ${name} on ${machineLabel}${where}.`)if (trustNote) deps.output(trustNote)- deps.output(origin ? origin.next(agent) : 'Open it in Harness with ⌘O.')+ deps.output('Open it in Harness with ⌘O.')// Started on another machine by a person or a program, it is read and waited for through that machine, named as// it was here. The lamp (lamp-4ace, 2026-10-14 21:36), a program outside Harness, started `lamp-first-task` on// office this way and was told only ⌘O, which it has not got.@@ -613,8 +632,12 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {} finally { session.close() }} catch (error) {const message = error instanceof Error ? error.message : String(error)- if (args.json) deps.output(JSON.stringify({ ok: false, error: message }))- else deps.error(message)- return error instanceof NewUsageError ? 2 : 1+ // Refused (a limit, the person's setting, a pane whose harness is gone): not a failure to retry.+ const refused = error instanceof AgentClientError && REFUSED_CODES.has(error.code) ? error : null+ if (args.json) {+ deps.output(JSON.stringify({ ok: false, error: message,+ ...(refused ? { code: refused.code, ...(refused.reason ? { reason: refused.reason } : {}), next: refusalNext(env, refused) } : {}) }))+ } else deps.error(message)+ return refused ? EXIT.refused : error instanceof NewUsageError ? 2 : 1}}diff --git a/cli/src/messages/command.spec.ts b/cli/src/messages/command.spec.tsindex c5b4e266d..2f9fa1888 100644--- a/cli/src/messages/command.spec.ts+++ b/cli/src/messages/command.spec.ts@@ -6,6 +6,8 @@ import { formatSent, paneOwner, parseSendArgs, readMessageFile, SEND_USAGE, sendimport { MessageError } from './model.js'import type { Rpc } from './rpc.js'+const SEND_NEXT = 'Next: harness send (alone: who is here, and any reply to you)'+let dir: stringbeforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'send-')) })afterEach(() => rmSync(dir, { recursive: true, force: true }))@@ -66,12 +68,19 @@ describe('what harness send prints', () => {'m1234567 → web: queued · working: arrives at its next tool call','m1234567 → phone: delivered (at its tool call)','m1234567 → lead: delivered (it read it)',+ SEND_NEXT,].join('\n'))expect(formatSent({ id: 'm7', recipients: [{ name: 'api', state: 'queued' }], advice: 'This message is 2000 characters…' }))- .toBe('m7 → api: queued\nThis message is 2000 characters…')+ .toBe(`m7 → api: queued\nThis message is 2000 characters…\n${SEND_NEXT}`)expect(formatSent({})).toBe('')})+ it('says where a reply comes after a message is sent, and nothing more for the roster', () => {+ const text = formatSent({ id: 'm1', recipients: [{ name: 'mate', state: 'delivered', via: 'hook' }] })+ expect(text.split('\n').at(-1)).toBe('Next: harness send (alone: who is here, and any reply to you)')+ expect(formatSent({ roster: 'Teammates: api' })).not.toMatch(/Next:/)+ })+it('asks the pane\'s daemon, and prints its answer or its error', async () => {const out: string[] = [], err: string[] = []const asked: Array<Record<string, unknown>> = []@@ -83,7 +92,7 @@ describe('what harness send prints', () => {const io = { rpc, out: (l: string) => out.push(l), err: (l: string) => err.push(l), pane: '%4', owner: () => ({ port: 19000, dataDir: '/d' }) }expect(await sendCommand(['api', 'hello'], io)).toBe(0)expect(asked[0]).toEqual({ action: 'send', pane: '%4', to: ['api'], text: 'hello', port: 19000 })- expect(out.at(-1)).toBe('m1234567 → api: queued')+ expect(out.at(-1)).toBe(`m1234567 → api: queued\n${SEND_NEXT}`)expect(await sendCommand(['api', 'hello', '--json'], io)).toBe(0)expect(JSON.parse(out.at(-1)!)).toMatchObject({ id: 'm1234567' })expect(await sendCommand(['api', 'fail'], io)).toBe(1)diff --git a/cli/src/messages/command.ts b/cli/src/messages/command.tsindex 07f1cae87..8e8ae9b7e 100644--- a/cli/src/messages/command.ts+++ b/cli/src/messages/command.ts@@ -105,7 +105,9 @@ export function formatSent(reply: Record<string, unknown>): string {const via = r.via === 'hook' ? ' (at its tool call)' : r.via === 'prompt' ? ' (as a prompt)' : r.via === 'read' ? ' (it read it)' : ''return `${id} → ${String(r.name)}: ${String(r.state)}${via}${r.reason ? ` · ${String(r.reason)}` : ''}`})- return [...lines, ...(typeof reply.advice === 'string' ? [reply.advice] : [])].join('\n')+ // A reply comes as a message to the sender; `harness send` alone shows any that came (agentClient/next.ts's format).+ const next = lines.length ? ['Next: harness send (alone: who is here, and any reply to you)'] : []+ return [...lines, ...(typeof reply.advice === 'string' ? [reply.advice] : []), ...next].join('\n')}export async function sendCommand(argv: readonly string[], deps: {diff --git a/docs/cli.md b/docs/cli.mdindex 78c5f1157..c9b9b4088 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -120,6 +120,23 @@ Yours: <open> open of <max> · <starts> of <max starts> starts in the last <minuRun by the person, it prints the first line only: `You: the person, on <machine>.`+Every agent verb ends with what to run next, in one shape (`--json` gives the same as `next`, and `new` and `close`+add `effect`, what changed):++```+<name> on <machine>: starting. <agent>, in <folder>.+The person sees it in Harness, beside you.+Next: harness wait <name> (until it has answered; then read it: harness show <name>)+```++`show` names `close` for an idle harness of the agent's own, `wait` for a working one, and the person for one that+needs the person; `close` says how many of the agent's own are still open; an agent's `ps` ends with its idle one to+read, its busy ones to wait for, or a start, and shows its own first and at most 15 rows (`--all` shows every one).+A harness waiting on a question or a permission is shown as `needs the person` (JSON keeps `needs-input` and adds+`needsPerson: true`). A refusal (`SPAWN_LIMIT`, `TURNED_OFF`, `NOT_YOURS`) exits 5, with `code`, `reason` and+`next` in its JSON. `harness help agents` prints the commands, states, exit codes and rules on one screen, and+`harness --help` starts with it when an agent runs it.+## Your devicesSigning in is what makes a device trusted: every computer and app signed in to the account adds itsdiff --git a/docs/design/2026-10-11-agent-client.md b/docs/design/2026-10-11-agent-client.mdindex fbe8c0442..b89bc5c7f 100644--- a/docs/design/2026-10-11-agent-client.md+++ b/docs/design/2026-10-11-agent-client.md@@ -54,7 +54,8 @@ harness close <name> [--now] # save its screen and stop iText by default, for agents as much as people: they read it as well, and it is a third of JSON's size (`ps` onthe owner's Mac, 21 harnesses: 5.8 KB of text, 16.2 KB of JSON). `--json` for programs. Every error says what to run next.-`wait` exits 0 idle, 3 needs the person, 4 stopped or gone, 124 timed out. A harness the caller closed itself is+`wait` exits 0 idle, 3 needs the person, 4 stopped or gone, 124 timed out. A refusal (limits, the person's+setting, a harness the caller did not start) exits 5, and every verb ends with `Next:` (2026-10-15-agent-experience.md). A harness the caller closed itself is`closed (you closed it)` and exits 0 (`close` notes it in the ledger): a Codex lead that closed its harness and thenwaited on it, as it had queued, was told it had failed (October 12).@@ -360,9 +361,9 @@ A close of a harness already closed, the same conversation, is answered closed (a window closing a tab closes its panes one at a time, and the starter's close had already taken the next pane'sharness with it; that pane's close was answered `AGENT_CHANGED` and shown as "Could not confirm that it stopped".-Agents are told too: `harness show` on an idle harness of theirs ends with `Close it once you have what you need:-harness close kid`, and `harness ps` ends with `You have 2 harnesses of your own open, 1 idle. Close each once you have-its answer: harness close <name>.` (the MCP tools name `harness_close` instead). `wait` on one Harness closed says where+Agents are told too: `harness show` on an idle harness of theirs ends with `Next: harness close <name> (once you+have what you need)`, and an agent's `harness ps` ends with `Next: harness show <name> (read its answer, then close+it: harness close <name>)`; the MCP tools name `harness_close` instead (2026-10-15-agent-experience.md). `wait` on one Harness closed says whereits answer still is: `kid: stopped · it was stopped; its answer is kept: harness show kid`.Not covered: harnesses an agent started on another machine when its starter closes (each machine's cleanup sees onlydiff --git a/docs/plans/2026-10-15-002-agent-next-steps-plan.md b/docs/plans/2026-10-15-002-agent-next-steps-plan.mdnew file mode 100644index 000000000..37fc9b772--- /dev/null+++ b/docs/plans/2026-10-15-002-agent-next-steps-plan.md@@ -0,0 +1,1155 @@+# Harness for agents: phases 4, 5, 7 and 8, implementation plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Every agent verb ends with what changed and what to run next, refusals are told apart by their exit code,+an agent reads less (`ps` capped, `harness help agents`), and MCP clients get the same facts as structured data.++**Architecture:** A pure module `cli/src/agentClient/next.ts` holds the one shape every verb answers with+(`NextStep`, `formatNext`) and the agents' help text. Each verb builds its `Next` from what it already knows and+prints it last; `--json` carries the same as `effect` and `next` fields. Refusals keep their messages and exit 5.+Under `harness mcp` each verb also prints its JSON on one marked line, which `mcp.ts` moves into `structuredContent`.++**Tech Stack:** TypeScript (Node, ESM), vitest, the existing agent client (`cli/src/agentClient/`), `harness new`+(`cli/src/lib/newCommand.ts`), `harness send` (`cli/src/messages/command.ts`).++**Spec:** `docs/design/2026-10-15-agent-experience.md`: parts 2, 3, 4 and 6; phases 4, 5, 7 and 8. Builds on the+phases 1 to 3 plan (`docs/plans/2026-10-15-001-agent-experience-plan.md`), already on `feat/agent-first-glance`.++## Scope++| Phase | In this plan | Left out, and why |+|---|---|---|+| 4 Result, effect, Next | all verbs: `new`, `ps`, `show`, `wait`, `close`, `send` | `new`'s "already running/starting" answer keeps its text: it already names the command and says not to start again |+| 5 States and exit codes | `needs the person` in text, `needsPerson` in JSON, refusals exit 5 with `code`/`reason`/`next` | `signed-out` is phase 6 (its own plan: detection needs research) |+| 7 Less to read | agent `ps` order and 15-row cap, `harness help agents`, `--help` first lines | `harness machines` columns: the reachability column needs each machine's Harness version, which no list has (phase 9's older-Harness check) |+| 8 MCP | none in this run | the person narrowed the run to agents using the CLI; Tasks 9 and 10 stay written for later |+| 10 Publishing | none | the `.mcpb` runs `npx @autonomous-ai/harness-mcp`, which is unpublished: attaching it to releases now ships a broken bundle. Needs the owner's npm step first |++## Global Constraints++- Branch `feat/agent-next-steps`, stacked on `feat/agent-first-glance`, in the worktree `../ah-agent-first-glance`.+ Base on that branch until phases 1 to 3 are merged, then rebase on `main`.+- Ask the person before the first commit on this branch, and before any push or pull request.+- Plain words (`docs/naming-system.md`). Examples in docs and help use placeholders: `<agent>`, `<name>`,+ `<machine>`, `<task>`, `<project>`, never real names.+- `--json` only gains fields: nothing renamed, removed or retyped. `needs-input` stays in JSON. Where the spec writes+ `{"error": {"code": …}}`, the existing `error` field keeps its type and `code`, `reason`, `next` are added beside it.+- A person's text is unchanged, except `close`'s and `show`'s first line (shared by both) and `needs the person`.+ Only agents get `Next` from `new` and `ps`.+- `Next` names only what the caller may run: never `close` for a harness it did not start.+- Done is said only by `wait` and `show`: `new` says `starting`, `send` says `sent`.+- One format everywhere: `Next: <command> (<when>)`, further options as ` or: <command> (<when>)`; a step with no+ command is `Next: <what to do>`. Under MCP the command is the tool call (`step()`).+- Exit codes: 0 ok, 1 failed, 2 usage, 3 needs the person, 4 stopped or gone, 5 refused, 124 timed out. Refused codes:+ `SPAWN_LIMIT`, `TURNED_OFF`, `NOT_YOURS`.+- No core or daemon change. No new limits or permissions.+- Test commands: `cd cli && npx vitest run <files>`; `cd cli && npm run typecheck`; `cd website && npx vitest run scripts/agents-site.spec.ts`.+- The CLI end to end (`cli/e2e/agentClient.e2e.ts`) runs once, in the last task.++## Review Focus++1. **A harness name with spaces or a sentence as its name** (an unnamed harness titled by its session). Expected:+ every `Next` command still runs as printed: the name quoted, or the id's start (`addressOf`). Test in Task 1.+2. **Under MCP with `machine` given to `harness_start`.** Expected: `Next` names `harness_wait (names: "<name>")`+ with no `--machine` inside the tool's argument. Test in Task 4.+3. **A JSON reader of today's output** (an eval script, a person's script). Expected: every field it read is still+ there with the same type. Test in Tasks 2, 3, 6 (each `--json` test checks an old field beside the new ones).+4. **An agent with 40 harnesses on the machine and 2 of its own idle among the oldest.** Expected: its own two are in+ the 15 rows `ps` shows, and the last line says how many more. Test in Task 7.+5. **An agent's `--help` when it is a person in a plain terminal with no agent variables.** Expected: only the one+ added first line, the rest of the help unchanged. Test in Task 8.++---++## Phase 4: every verb answers with result, effect and Next++### Task 1: The Next shape, and `show`++**Files:**+- Create: `cli/src/agentClient/next.ts`, `cli/src/agentClient/next.spec.ts`+- Modify: `cli/src/agentClient/commands.ts` (`showCommand`, `closeHint`)+- Test: `cli/src/agentClient/commands.spec.ts` (the `harness show` group)++**Interfaces:**+- Produces: `type NextStep = { run: string; when: string } | { tell: string }`; `formatNext(steps: readonly NextStep[]): string | null`+ (null for none). Every later task prints with it.++- [ ] **Step 1: Write the failing tests for the format**++`cli/src/agentClient/next.spec.ts`:++```ts+import { describe, expect, it } from 'vitest'+import { formatNext } from './next.js'++describe('Next', () => {+ it('says one step on one line, with when to take it', () => {+ expect(formatNext([{ run: 'harness wait <name>', when: 'until it has answered' }])).toBe('Next: harness wait <name> (until it has answered)')+ })+ it('gives the other steps as "or"', () => {+ expect(formatNext([{ run: 'harness show <name>', when: 'to read its answer' }, { run: 'harness wait <name>', when: 'until it stops working' }]))+ .toBe('Next: harness show <name> (to read its answer)\n or: harness wait <name> (until it stops working)')+ })+ it('says a step that is not a command as it is', () => {+ expect(formatNext([{ tell: 'tell the person; only they answer it (a question or a permission).' }]))+ .toBe('Next: tell the person; only they answer it (a question or a permission).')+ })+ it('says nothing when there is nothing next', () => {+ expect(formatNext([])).toBeNull()+ })+})+```++- [ ] **Step 2: Run them to see them fail**++Run: `cd cli && npx vitest run src/agentClient/next.spec.ts`+Expected: FAIL, `Failed to resolve import "./next.js"`.++- [ ] **Step 3: Write `next.ts`**++```ts+/**+ * What every agent verb ends with (docs/design/2026-10-15-agent-experience.md, part 2): the step to take next, and+ * when to take it, so an agent is never left to guess. `--json` carries the same steps as `next`.+ */++/** A command to run and when to pick it, or something only words can say ("tell the person …"). */+export type NextStep = { run: string; when: string } | { tell: string }++/** `Next: <command> (<when>)`, then ` or: …` for the other choices; null when there is nothing next. */+export function formatNext(steps: readonly NextStep[]): string | null {+ if (!steps.length) return null+ return steps.map((step, i) => `${i ? ' or:' : 'Next:'} ${'run' in step ? `${step.run} (${step.when})` : step.tell}`).join('\n')+}+```++- [ ] **Step 4: Run them to see them pass**++Run: `cd cli && npx vitest run src/agentClient/next.spec.ts`+Expected: 4 passed.++- [ ] **Step 5: Write the failing `show` tests**++In `commands.spec.ts`, in `describe('harness show', …)`, add:++```ts+ it('starts with the result and ends with Next: close for its own idle harness', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('kid')]+ d.pages.set('s-kid', [{ events: [ev('user_message', { text: 'review it' }), ev('assistant_message', { text: 'One bug.' })], hasMore: false }])+ const h = harness(d)+ started(h.ledger, 'lead', 'kid')+ expect(await showCommand(['kid'], h.deps)).toBe(EXIT.ok)+ const lines = h.out.join('\n').split('\n')+ expect(lines[0]).toBe('kid on studio: idle · Codex · started by you')+ expect(lines.at(-1)).toBe('Next: harness close kid (once you have what you need)')+ })++ it('names wait for a working harness, and never close for one the caller did not start', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('busy', { activity: { state: 'working' } }), frame('theirs')]+ d.screens.set('busy', ['working'])+ const h = harness(d)+ started(h.ledger, 'lead', 'busy')+ expect(await showCommand(['busy'], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n').split('\n').at(-1)).toBe('Next: harness wait busy (until it stops working)')+ const theirs = harness(d)+ expect(await showCommand(['theirs'], theirs.deps)).toBe(EXIT.ok)+ expect(theirs.out.join('\n')).not.toMatch(/harness close/)+ })++ it('says to tell the person when only they can answer, and gives next in JSON', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('asker')]+ d.screens.set('asker', ['needs_input'])+ const h = harness(d)+ started(h.ledger, 'lead', 'asker')+ expect(await showCommand(['asker'], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n').split('\n').at(-1)).toBe('Next: tell the person; only they answer it (a question or a permission).')+ const json = harness(d)+ expect(await showCommand(['asker', '--json'], json.deps)).toBe(EXIT.ok)+ const parsed = JSON.parse(json.out[0])+ expect(parsed.state).toBe('needs-input')+ expect(parsed.next).toEqual([{ tell: 'tell the person; only they answer it (a question or a permission).' }])+ })+```++(`d.screens` values are the daemon's words: `needs_input` reaches `inspect` as `activity`; `FakeDaemon` returns them+as given.)++- [ ] **Step 6: Run them to see them fail**++Run: `cd cli && npx vitest run src/agentClient/commands.spec.ts -t "harness show"`+Expected: the three new tests FAIL: line 0 is `kid · Codex · studio · idle · started by you`, the last line is+`Close it once you have what you need: harness close kid`, and JSON has no `next`.++- [ ] **Step 7: Change `showCommand`**++In `commands.ts`, import `formatNext, type NextStep` from `./next.js`. Replace `closeHint` with:++```ts+/** What `show` says to do next, from its state and whose it is: never `close` for a harness the caller did not start. */+function showNext(env: NodeJS.ProcessEnv, state: State, yours: boolean, at: string): NextStep[] {+ if (state === 'needs-input') return [{ tell: 'tell the person; only they answer it (a question or a permission).' }]+ if (state === 'working' || state === 'unknown' || state === 'starting' || state === 'installing') return [{ run: step(env, 'wait', at), when: 'until it stops working' }]+ if (state === 'idle' && yours) return [{ run: step(env, 'close', at), when: 'once you have what you need' }]+ return []+}+```++In `showCommand`, compute `const at = onAway(addressOf({ machineId: '', agentId: t.frame.id, name: t.frame.name ?? '', engine: '' }), away)`+and `const next = showNext(s.env, state, t.yours, at)`; add `next` to `result` (after `tools`). Change the text so:+- the first line is `` `${result.name} on ${t.machine}: ${state} · ${result.agent} · started by ${startedBy}` ``;+- the `It is waiting for the person …` line and the `closeHint` line are removed;+- the last line is `formatNext(next)` when it is not null.++- [ ] **Step 8: Run the show group, fix what the change was meant to change**++Run: `cd cli && npx vitest run src/agentClient/commands.spec.ts -t "harness show"`+Expected: the new tests pass. Older assertions on `· studio ·` first lines, on `It is waiting for the person`, or on+`Close it once you have what you need` fail; change each to the new line, and nothing else.++- [ ] **Step 9: Commit**++```bash+git add cli/src/agentClient/next.ts cli/src/agentClient/next.spec.ts cli/src/agentClient/commands.ts cli/src/agentClient/commands.spec.ts+git commit -m "harness show starts with its result and ends with Next"+```++### Task 2: `wait` gives each harness's Next in JSON, and `gone` gets one++**Files:**+- Modify: `cli/src/agentClient/commands.ts` (`waitCommand`)+- Test: `cli/src/agentClient/commands.spec.ts` (the `harness wait` group)++**Interfaces:**+- Consumes: `NextStep`, `formatNext` (Task 1).++- [ ] **Step 1: Write the failing tests**++```ts+ it('tells where to look for a harness that is gone, and gives each one\'s next in JSON', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('kid')]+ const h = harness(d)+ started(h.ledger, 'lead', 'kid')+ const waiting = waitCommand(['kid'], h.deps)+ d.frames = [frame('lead', { engine: 'claude' })]+ expect(await waiting).toBe(EXIT.stopped)+ expect(h.out.join('\n')).toBe('kid: gone · it is gone\nNext: harness ps --all (to see whether it was closed)')+ d.frames = [frame('lead', { engine: 'claude' }), frame('kid')]+ d.pages.set('s-kid', [{ events: [ev('user_message', { text: 'go' }), ev('assistant_message', { text: 'done' })], hasMore: false }])+ const json = harness(d)+ expect(await waitCommand(['kid', '--json'], json.deps)).toBe(EXIT.ok)+ const [kid] = JSON.parse(json.out[0]).harnesses+ expect(kid.state).toBe('idle')+ expect(kid.next).toEqual([{ run: 'harness show kid', when: 'to read its answer' }])+ })+```++- [ ] **Step 2: Run to see it fail**++Run: `cd cli && npx vitest run src/agentClient/commands.spec.ts -t "is gone"`+Expected: FAIL: no `Next:` line, and `kid.next` is undefined.++- [ ] **Step 3: Implement**++In `waitCommand`, after `results` is built, add a pure function above `waitCommand`:++```ts+/** What to do once a wait has ended on [state], with the commands that read it, wait again, and list the stopped ones. */+function waitNext(state: string, run: { read: string; again: string; list: string }): NextStep[] {+ switch (state) {+ case 'idle': return [{ run: run.read, when: 'to read its answer' }]+ case 'needs-input': return [{ tell: 'tell the person; only they answer it (a question or a permission).' }]+ case 'timeout': case 'installing': case 'starting': return [{ run: run.again, when: 'to keep waiting' }]+ case 'stopped': return [{ run: run.read, when: 'its answer is kept' }]+ case 'gone': return [{ run: run.list, when: 'to see whether it was closed' }]+ default: return []+ }+}+```++Called once per result with `at = onAway(r.name, away)`:+`waitNext(r.state, { read: step(s.env, 'show', at), again: step(s.env, 'wait', at), list: step(s.env, 'ps', away ? machineOption(away.word) : '', { flag: '--all', arg: 'all: true' }) })`.++Each JSON result gains `next: waitNext(…)`. In text, keep each `name: state · …` line as it is, and after a `gone`+line print `formatNext(next)`.++- [ ] **Step 4: Run the wait group**++Run: `cd cli && npx vitest run src/agentClient/commands.spec.ts -t "harness wait"`+Expected: all pass; any older test asserting the whole JSON `harnesses` array with `toEqual` gets `next` added.++- [ ] **Step 5: Commit**++```bash+git add cli/src/agentClient/commands.ts cli/src/agentClient/commands.spec.ts+git commit -m "harness wait gives each harness's next step in JSON, and says where to look for one that is gone"+```++### Task 3: `close` says the result, the effect, and how many are left++**Files:**+- Modify: `cli/src/agentClient/commands.ts` (`closeCommand`)+- Modify: `cli/src/agentClient/mcp.spec.ts` only if it asserts `Closed …`+- Test: `cli/src/agentClient/commands.spec.ts` (the `harness close` group)++**Interfaces:**+- Consumes: `formatNext` (Task 1), `contextFor` (phase 3).++- [ ] **Step 1: Write the failing test**++```ts+ it('says the result and the effect, and how many of its own are still open', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('kid'), frame('other')]+ const h = harness(d)+ started(h.ledger, 'lead', 'kid')+ started(h.ledger, 'lead', 'other')+ expect(await closeCommand(['kid'], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n')).toBe('kid on studio: closed. Its conversation is kept; the person can resume it.\nNext: nothing; you have 1 open of 4.')+ const json = harness(d)+ expect(await closeCommand(['other', '--json'], json.deps)).toBe(EXIT.ok)+ expect(JSON.parse(json.out[0])).toEqual({ name: 'other', id: 'other', closed: true, effect: 'Its conversation is kept; the person can resume it.', next: [], open: 1 })+ })+```++(The second close still counts `kid`: the fake daemon keeps listing it. `open` is what the caller's own count says+after this close.)++- [ ] **Step 2: Run to see it fail**++Run: `cd cli && npx vitest run src/agentClient/commands.spec.ts -t "how many of its own are still open"`+Expected: FAIL: text is `Closed kid. Its conversation is kept.`++- [ ] **Step 3: Implement**++At the end of `closeCommand`'s success path:++```ts+ const effect = kept ? 'Its conversation is kept; the person can resume it.' : 'It was still starting, so no conversation was kept.'+ // How many of its own are left, counted as `whoami` counts them, without the one just closed.+ o.frames = o.frames.filter((f) => !(t!.machineId === o.where.machineId && f.id === t!.frame.id))+ const open = o.caller ? contextFor(s, o).quota?.open ?? null : null+ const max = SPAWN_LIMITS.livePerHarness+ s.out(flags.has('--json')+ ? JSON.stringify({ name, id: t.frame.id, closed: true, ...(kept ? {} : { conversationKept: false }), effect, next: [], ...(open === null ? {} : { open }) })+ : [`${name} on ${t.machine}: closed. ${effect}`, open === null ? null : `Next: nothing; you have ${open} open of ${max}.`].filter(Boolean).join('\n'))+```++- [ ] **Step 4: Run the close group and the MCP spec**++Run: `cd cli && npx vitest run src/agentClient/commands.spec.ts src/agentClient/mcp.spec.ts`+Expected: the new test passes; change older `Closed <name>. …` assertions to the new first line.++- [ ] **Step 5: Commit**++```bash+git add cli/src/agentClient/commands.ts cli/src/agentClient/commands.spec.ts cli/src/agentClient/mcp.spec.ts+git commit -m "harness close says what it did, what it kept, and how many of yours are still open"+```++### Task 4: An agent's `harness new` says starting, the effect, and Next++**Files:**+- Modify: `cli/src/lib/newCommand.ts` (`NewOrigin`, the success and installing paths)+- Modify: `cli/src/agentClient/commands.ts` (`agentOrigin`: `next` becomes `answer`)+- Test: `cli/src/lib/newCommand.spec.ts`, `cli/src/agentClient/commands.spec.ts` (the `agentOrigin` tests)++**Interfaces:**+- Consumes: `NextStep`, `formatNext` (Task 1).+- Produces: `NewOrigin.answer(agent: Record<string, unknown>, at: { local: boolean; machine: string | null }): { effect: string; next: NextStep[] }`,+ replacing `next(agent): string`.++- [ ] **Step 1: Write the failing tests**++In `newCommand.spec.ts`, where an origin fake has `next: () => 'Read it: harness show it'`, the fakes become+`answer: () => ({ effect: 'The person sees it in Harness, beside you.', next: [{ run: 'harness wait it', when: 'until it has answered; then read it: harness show it' }] })`,+and `next: () => ''` becomes `answer: () => ({ effect: '', next: [] })`. Change one assertion first to the new text:++```ts+ expect(trusted.out).toEqual([+ `opinion on this computer: starting. Codex, in ${scratch}.`,+ 'The person sees it in Harness, beside you.',+ 'Next: harness wait it (until it has answered; then read it: harness show it)',+ ])+```++and add a JSON check beside it:++```ts+ const json = deps(['codex', scratch, '--name', 'opinion', '--json'], socket, { origin: async () => origin })+ expect(await newCommand(json)).toBe(0)+ const said = JSON.parse(json.out[0])+ expect(said.agent).toBeTruthy()+ expect(said.effect).toBe('The person sees it in Harness, beside you.')+ expect(said.next).toEqual([{ run: 'harness wait it', when: 'until it has answered; then read it: harness show it' }])+```++In `commands.spec.ts`, add to the `agentOrigin` group:++```ts+ it('answers an agent\'s start with the effect and Next, the machine named, and under MCP the tool', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' })]+ const origin = (await agentOrigin(harness(d).deps))!+ expect(origin.answer({ id: 'k1', name: 'kid' }, { local: true, machine: null })).toEqual({+ effect: 'The person sees it in Harness, beside you.',+ next: [{ run: 'harness wait kid', when: 'until it has answered; then read it: harness show kid' }],+ })+ expect(origin.answer({ id: 'k1', name: 'kid' }, { local: false, machine: 'Mac mini' }).next[0]).toEqual(+ { run: 'harness wait --machine "Mac mini" kid', when: 'until it has answered; then read it: harness show --machine "Mac mini" kid' })+ const viaMcp = (await agentOrigin(harness(d, { env: { HARNESS_VIA_MCP: '1' } }).deps))!+ expect(viaMcp.answer({ id: 'k1', name: 'kid' }, { local: false, machine: 'mini' }).next[0].run).toBe('harness_wait (names: "kid")')+ })+```++- [ ] **Step 2: Run to see them fail**++Run: `cd cli && npx vitest run src/lib/newCommand.spec.ts src/agentClient/commands.spec.ts -t "start|Created|origin"`+Expected: typecheck-level failures in vitest (`answer` is not a function) and the old `Created …` text.++- [ ] **Step 3: Implement in `newCommand.ts`**++In `NewOrigin`, replace `next` with:++```ts+ /** What the start changed, and what to run next: wait for it, then read it. */+ answer(agent: Record<string, unknown>, at: { local: boolean; machine: string | null }): { effect: string; next: NextStep[] }+```++In the success path, for an agent (`origin`):++```ts+ const engine = engineName(String(agent.engine ?? payload.engine ?? ''))+ const said = origin?.answer(agent, { local, machine: args.machine })+ if (args.json) deps.output(JSON.stringify({ ok: true, machineId, agent, ...(trustNote ? { note: trustNote } : {}), ...(said ? { effect: said.effect, next: said.next } : {}) }))+ else if (origin && said) {+ deps.output(`${name} on ${machineLabel}: starting. ${engine}${where ? `,${where}` : ''}.`)+ if (said.effect) deps.output(said.effect)+ if (trustNote) deps.output(trustNote)+ const next = formatNext(said.next)+ if (next) deps.output(next)+ } else { /* the person: as today, "Created …", ⌘O, and Read it for another machine */ }+```++In the installing path (agent, held for an install), replace the note with:++```ts+ const at = name ? (local || env[VIA_MCP_ENV] === '1' ? name : `${machineOption(args.machine!)} ${name}`) : ''+ const next: NextStep[] = name ? [{ run: step(env, 'wait', at), when: 'until it has started and answered' }] : [{ run: step(env, 'ps'), when: 'to follow it' }]+ const note = `${name || 'The harness'} on ${machineLabel}: installing ${engineName(String(payload.engine))}. It starts by itself once installed; do not start it again.`+ deps.output(args.json ? JSON.stringify({ ok: true, pending: true, machineId, creationId, name, note, next }) : `${note}\n${formatNext(next)}`)+```++- [ ] **Step 4: Implement in `agentOrigin`**++Replace `next: (agent) => …` with:++```ts+ answer: (agent, at) => {+ const name = addressOf({ machineId: '', agentId: String(agent.id ?? ''), name: String(agent.name ?? ''), engine: '' })+ // Under MCP the tools take no machine: harness_wait finds the caller's own by its record, on any machine.+ const target = at.local || at.machine === null || s.env[VIA_MCP_ENV] === '1' ? name : `${machineOption(at.machine)} ${name}`+ return {+ effect: caller.outside || !at.local ? 'The person sees it in Harness.' : 'The person sees it in Harness, beside you.',+ next: [{ run: step(s.env, 'wait', target), when: `until it has answered; then read it: ${step(s.env, 'show', target)}` }],+ }+ },+```++- [ ] **Step 5: Run, and update every changed assertion**++Run: `cd cli && npx vitest run src/lib/newCommand.spec.ts src/agentClient && npm run typecheck`+Expected: new tests pass. Change each origin fake (`next:` → `answer:`) and each agent-path `Created … `/`Read it:`+assertion to the new lines. The person's lines (`Created mine …`, `Open it in Harness with ⌘O.`) stay as they are.+The three `starts by itself once it is installed` assertions change to the installing text above.++- [ ] **Step 6: Commit**++```bash+git add cli/src/lib/newCommand.ts cli/src/lib/newCommand.spec.ts cli/src/agentClient/commands.ts cli/src/agentClient/commands.spec.ts+git commit -m "An agent's harness new says it is starting, that the person sees it, and to wait for it next"+```++### Task 5: An agent's `ps` ends with Next; `send` says how a reply comes++**Files:**+- Modify: `cli/src/agentClient/commands.ts` (`openNote` becomes `psNext`), `cli/src/messages/command.ts` (`formatSent`)+- Test: `cli/src/agentClient/commands.spec.ts` (the `harness ps` group), `cli/src/messages/command.spec.ts`++**Interfaces:**+- Consumes: `NextStep`, `formatNext` (Task 1); `Context.canStart` (phase 3).+- Produces: `psNext(env, rows: readonly Row[], canStart: boolean): NextStep[]`.++- [ ] **Step 1: Write the failing tests**++Replace the test `tells an agent how many of its own are open and idle, …` with:++```ts+ it('ends an agent\'s ps with Next: read its idle one, wait for its busy ones, or start one', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('a'), frame('b', { activity: { state: 'working' } }), frame('theirs')]+ const h = harness(d)+ for (const kid of ['a', 'b']) started(h.ledger, 'lead', kid)+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)+ expect(h.out.join('\n').split('\n').slice(-2)).toEqual([+ 'Next: harness show a (read its answer, then close it: harness close a)',+ ' or: harness wait b (until it stops working)',+ ])+ // None of its own, and it may start one.+ d.frames = [frame('lead', { engine: 'claude' }), frame('theirs')]+ const none = harness(d)+ expect(await psCommand([], none.deps)).toBe(EXIT.ok)+ expect(none.out.join('\n').split('\n').at(-1)).toBe('Next: harness new <agent> --name <name> <project> -- <task> (to hand work to another agent; do quick work yourself)')+ // The person: no Next.+ const person = harness(d, { pane: undefined })+ expect(await psCommand([], person.deps)).toBe(EXIT.ok)+ expect(person.out.join('\n')).not.toMatch(/^Next:/m)+ })+```++In `cli/src/messages/command.spec.ts`, add:++```ts+ it('says where a reply comes after a message is sent', () => {+ const text = formatSent({ id: 'm1', recipients: [{ name: 'mate', state: 'delivered', via: 'hook' }] })+ expect(text.split('\n').at(-1)).toBe('Next: harness send (alone: who is here, and any reply to you)')+ })+```++- [ ] **Step 2: Run to see them fail**++Run: `cd cli && npx vitest run src/agentClient/commands.spec.ts src/messages/command.spec.ts -t "Next|reply"`+Expected: FAIL: `You have 2 harnesses of your own open, …` is the last line; `formatSent` has no Next.++- [ ] **Step 3: Implement `psNext`**++Replace `openNote` with:++```ts+/** What an agent's `ps` ends with: its idle harness to read and close, its busy ones to wait for, or a start. */+export function psNext(env: NodeJS.ProcessEnv, rows: readonly Row[], canStart: boolean): NextStep[] {+ const at = (r: Row) => addressOf({ machineId: '', agentId: r.id, name: r.name, engine: '' })+ const open = rows.filter((r) => r.yours && r.state !== 'stopped' && r.state !== 'failed')+ const idle = open.filter((r) => r.state === 'idle'), busy = open.filter((r) => r.state !== 'idle')+ const steps: NextStep[] = []+ if (idle.length) steps.push({ run: step(env, 'show', at(idle[0])), when: `read its answer, then close it: ${step(env, 'close', at(idle[0]))}` })+ if (busy.length) steps.push({ run: step(env, 'wait', busy.map(at).join(',')), when: 'until it stops working' })+ if (!open.length && canStart) {+ steps.push({ run: env[VIA_MCP_ENV] === '1' ? 'harness_start (name: "<name>", task: "<task>")' : 'harness new <agent> --name <name> <project> -- <task>',+ when: 'to hand work to another agent; do quick work yourself' })+ }+ return steps+}+```++In `psCommand`, `const context = contextFor(s, o)` once; `const next = o.caller ? psNext(s.env, rows, !!context.canStart?.ok) : []`.+JSON gains `next`; text ends with `formatNext(next)` instead of `note`.++- [ ] **Step 4: Implement `send`'s Next**++In `formatSent`, for a send (not the roster), append `Next: harness send (alone: who is here, and any reply to you)`+after the recipients' lines and the advice.++- [ ] **Step 5: Run**++Run: `cd cli && npx vitest run src/agentClient src/messages`+Expected: pass; older `formatSent` assertions with `toBe` get the Next line.++- [ ] **Step 6: Commit**++```bash+git add cli/src/agentClient/commands.ts cli/src/agentClient/commands.spec.ts cli/src/messages/command.ts cli/src/messages/command.spec.ts+git commit -m "An agent's harness ps ends with what to do next; harness send says where a reply comes"+```++## Phase 5: states and exit codes++### Task 6: `needs the person` in text, refusals exit 5 with code, reason and next++**Files:**+- Modify: `cli/src/agentClient/daemon.ts` (`AgentClientError` gains `reason`), `cli/src/agentClient/commands.ts`+ (`EXIT`, `run`, `waitCommand`, `showCommand`, `agentOrigin`), `cli/src/lib/newCommand.ts` (its catch),+ `cli/src/agentClient/mcp.ts` (`result`, descriptions)+- Test: `cli/src/agentClient/commands.spec.ts`, `cli/src/lib/newCommand.spec.ts`, `cli/src/agentClient/mcp.spec.ts`++**Interfaces:**+- Produces: `EXIT.refused = 5`; `REFUSED_CODES: ReadonlySet<string>` = `SPAWN_LIMIT`, `TURNED_OFF`, `NOT_YOURS`;+ `new AgentClientError(code, message, reason?)`; `refusalNext(env, error): NextStep[]`.++- [ ] **Step 1: Write the failing tests**++In `commands.spec.ts`:++```ts+describe('refusals and the person', () => {+ it('closing a harness the caller did not start exits 5, with its code and reason in JSON', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('theirs')]+ const h = harness(d)+ expect(await closeCommand(['theirs'], h.deps)).toBe(EXIT.refused)+ expect(EXIT.refused).toBe(5)+ const json = harness(d)+ expect(await closeCommand(['theirs', '--json'], json.deps)).toBe(5)+ const said = JSON.parse(json.out[0])+ expect(said.error).toBe('NOT_YOURS')+ expect(said.code).toBe('NOT_YOURS')+ expect(typeof said.detail).toBe('string')+ expect(said.next).toEqual([])+ })++ it('a start over the open limit is refused with its reason, and Next names close', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), ...['a', 'b', 'c', 'd'].map((id) => frame(id))]+ const h = harness(d)+ for (const kid of ['a', 'b', 'c', 'd']) started(h.ledger, 'lead', kid)+ const origin = (await agentOrigin(h.deps))!+ const error = await origin.check().catch((e) => e)+ expect(error).toBeInstanceOf(AgentClientError)+ expect([error.code, error.reason]).toEqual(['SPAWN_LIMIT', 'OPEN_LIMIT'])+ })++ it('says needs the person in text and keeps needs-input in JSON, with needsPerson', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), frame('asker')]+ d.screens.set('asker', ['needs_input'])+ const h = harness(d)+ started(h.ledger, 'lead', 'asker')+ expect(await waitCommand(['asker'], h.deps)).toBe(EXIT.needsInput)+ expect(h.out[0]).toMatch(/^asker: needs the person · /)+ const json = harness(d)+ expect(await waitCommand(['asker', '--json'], json.deps)).toBe(EXIT.needsInput)+ expect(JSON.parse(json.out[0]).harnesses[0]).toMatchObject({ state: 'needs-input', needsPerson: true })+ })+})+```++In `newCommand.spec.ts`, beside the existing refusal test for an origin whose `check` throws:++```ts+ it('exits 5 when the agent is refused, and says why in JSON beside the old error', async () => {+ const socket = new FakeSocket(() => null) // refused before anything is asked of the daemon+ const origin = { check: async () => { throw new AgentClientError('SPAWN_LIMIT', 'You have 4 harnesses running. Close one you are done with first (harness close <name>).', 'OPEN_LIMIT') },+ prompt: (text: string) => text, created: async () => null, answer: () => ({ effect: '', next: [] }) }+ const d = deps(['codex', '--name', 'x', '--json'], socket, { origin: async () => origin })+ expect(await newCommand(d)).toBe(5)+ expect(JSON.parse(d.out[0])).toEqual({ ok: false, error: 'You have 4 harnesses running. Close one you are done with first (harness close <name>).',+ code: 'SPAWN_LIMIT', reason: 'OPEN_LIMIT', next: [{ run: 'harness close <name>', when: 'one you are done with, to free a place' }] })+ })+```+++In `mcp.spec.ts`:++```ts+ it('gives a refusal as an answer, not a failure', () => {+ expect(result('harness_close', { code: 5, out: '', err: 'You did not start theirs, so you may not close it. Only the person can.' }))+ .toEqual({ content: [{ type: 'text', text: 'You did not start theirs, so you may not close it. Only the person can.' }] })+ })+```++and change line 173's `'a: needs-input'` input and expectation to `'a: needs the person'`.++- [ ] **Step 2: Run to see them fail**++Run: `cd cli && npx vitest run src/agentClient src/lib/newCommand.spec.ts -t "refus|needs the person|exits 5"`+Expected: FAIL: exit 1, no `code`/`reason`, `needs-input` in text.++- [ ] **Step 3: Implement**++`daemon.ts`:++```ts+export class AgentClientError extends Error {+ /** [reason]: which limit or rule refused, for a refusal (`SPAWN_LIMIT`'s `OPEN_LIMIT`, `TURNED_OFF`'s `SWITCH_OFF`). */+ constructor(readonly code: string, message: string, readonly reason?: string) { super(message) }+}+```++`commands.ts`:++```ts+export const EXIT = { ok: 0, failed: 1, usage: 2, needsInput: 3, stopped: 4, refused: 5, timeout: 124 } as const+/** Not a failure: the caller may not do this. It should not retry; it tells the person or does the work itself. */+export const REFUSED_CODES: ReadonlySet<string> = new Set(['SPAWN_LIMIT', 'TURNED_OFF', 'NOT_YOURS'])+/** What a refused caller may do instead: close one of its own when it is at its limit; otherwise the message says. */+export function refusalNext(env: NodeJS.ProcessEnv, error: AgentClientError): NextStep[] {+ return error.reason === 'OPEN_LIMIT' ? [{ run: step(env, 'close', '<name>'), when: 'one you are done with, to free a place' }] : []+}+```++- `run()`: an `AgentClientError` whose code is in `REFUSED_CODES` returns `EXIT.refused`; its JSON is+ `{ error: code, detail: message, code, ...(reason ? { reason } : {}), next: refusalNext(env, error) }`.+- `agentOrigin`: `check` throws `new AgentClientError('SPAWN_LIMIT', c.message, c.reason)` from `spawnCheck`'s+ result (with `liveFor` as today); `refusing('TURNED_OFF', …)` passes `'SWITCH_OFF'`; the orphan `NOT_YOURS`+ passes `'ORPHAN'`. `refusing` takes the reason as a third argument.+- `newCommand.ts` catch: an `AgentClientError` with a code in `REFUSED_CODES` returns 5, and its JSON adds+ `code`, `reason` (when there is one) and `next: refusalNext(env, error)`.+- Text says `needs the person` where it printed `needs-input`: `waitCommand`'s line (`${r.name}: ${label} · …`),+ `showCommand`'s first line. One helper: `const said = (state: string) => (state === 'needs-input' ? 'needs the person' : state)`.+ JSON results with `needs-input` add `needsPerson: true`.+- `mcp.ts` `result()`: `EXIT.refused` is answered (no `isError`), for every tool. `harness_list`'s description says+ `needs the person` instead of `needs-input`. `newCommand.ts`'s trust note says+ `harness_wait says needs the person` under MCP. `WAIT_USAGE`'s exit line becomes+ `Exit status: 0 idle or closed by you, 3 one needs the person (a question or a permission), 4 one stopped or is gone, 5 refused, 124 timed out.`+- `CLOSE_USAGE` adds: `An agent refused (not its harness) exits 5.`++- [ ] **Step 4: Run, and update every changed assertion**++Run: `cd cli && npx vitest run src/agentClient src/lib/newCommand.spec.ts && npm run typecheck`+Expected: pass after `toBe(EXIT.failed)` on refusals becomes `toBe(EXIT.refused)` and `needs-input` in text+assertions becomes `needs the person`. Run `cd cli && npx tsx --test scripts/agent-eval/score.test.mts`: the+scorer reads refusals by message, so it passes unchanged.++- [ ] **Step 5: Commit**++```bash+git add cli/src/agentClient cli/src/lib/newCommand.ts cli/src/lib/newCommand.spec.ts+git commit -m "Refusals exit 5 with their code and reason; text says needs the person"+```++## Phase 7: less to read++### Task 7: An agent's `ps`: its own first, then the busy ones, at most 15 rows++**Files:**+- Modify: `cli/src/agentClient/model.ts` (add `forAgent`), `cli/src/agentClient/commands.ts` (`psCommand`)+- Test: `cli/src/agentClient/model.spec.ts`, `cli/src/agentClient/commands.spec.ts`++**Interfaces:**+- Produces: `forAgent(rows: readonly Row[], max?: number): { shown: Row[]; more: number }` (max 15).++- [ ] **Step 1: Write the failing tests**++`model.spec.ts`:++```ts+describe('forAgent', () => {+ const row = (name: string, over: Partial<Row> = {}): Row => ({ name, id: name, agent: 'Codex', machine: 'm', state: 'idle', folder: null, branch: null,+ startedBy: 'person', yours: false, self: false, lastActive: null, ...over })+ it('puts its own first, then the working and the ones needing the person, then the rest, and counts the rest past 15', () => {+ const rows = [...Array.from({ length: 30 }, (_, i) => row(`idle${i}`)), row('busy', { state: 'working' }), row('mine1', { yours: true }), row('mine2', { yours: true })]+ const { shown, more } = forAgent(rows)+ expect(shown.map((r) => r.name).slice(0, 3)).toEqual(['mine1', 'mine2', 'busy'])+ expect(shown).toHaveLength(15)+ expect(more).toBe(18)+ })+ it('shows every row when there are 15 or fewer', () => {+ expect(forAgent([row('a'), row('b')])).toEqual({ shown: [row('a'), row('b')], more: 0 })+ })+})+```++`commands.spec.ts`, in the `harness ps` group:++```ts+ it('shows an agent at most 15 rows and says how to see the rest; a person sees all', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' }), ...Array.from({ length: 20 }, (_, i) => frame(`h${i}`))]+ const h = harness(d)+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)+ const text = h.out.join('\n')+ expect(text).toContain('and 6 more: harness ps --all')+ const person = harness(d, { pane: undefined })+ expect(await psCommand([], person.deps)).toBe(EXIT.ok)+ expect(person.out.join('\n')).not.toContain('more: harness ps --all')+ expect(person.out.join('\n').match(/^h\d+ /gm)).toHaveLength(20)+ })+```++(21 harnesses: 15 shown, 6 more.)++- [ ] **Step 2: Run to see them fail**++Run: `cd cli && npx vitest run src/agentClient/model.spec.ts src/agentClient/commands.spec.ts -t "forAgent|15 rows"`+Expected: FAIL: `forAgent` is not exported; no `and 6 more` line.++- [ ] **Step 3: Implement**++`model.ts`:++```ts+/** How many rows an agent's `ps` shows unless asked for all: on the owner's Mac, 40 rows became about 8 to read. */+export const AGENT_ROWS = 15++/** An agent's `ps`: its own first, then those working or waiting on the person, then the rest; [max] at most. */+export function forAgent(rows: readonly Row[], max = AGENT_ROWS): { shown: Row[]; more: number } {+ const busy = (r: Row) => r.state === 'working' || r.state === 'needs-input'+ const ordered = [...rows.filter((r) => r.yours), ...rows.filter((r) => !r.yours && busy(r)), ...rows.filter((r) => !r.yours && !busy(r))]+ return { shown: ordered.slice(0, max), more: Math.max(0, ordered.length - max) }+}+```++`psCommand` text for an agent without `--all`: `const { shown, more } = forAgent(rows)`; print `formatRows(shown, …)`+then, when `more`, `` `and ${more} more: ${step(s.env, 'ps', away ? machineOption(away.word) : '', { flag: '--all', arg: 'all: true' })}` ``,+then the Next. JSON keeps every row. A person's text keeps every row.++- [ ] **Step 4: Run**++Run: `cd cli && npx vitest run src/agentClient`+Expected: pass.++- [ ] **Step 5: Commit**++```bash+git add cli/src/agentClient/model.ts cli/src/agentClient/model.spec.ts cli/src/agentClient/commands.ts cli/src/agentClient/commands.spec.ts+git commit -m "An agent's harness ps shows its own first and at most 15 rows"+```++### Task 8: `harness help agents`, and `--help` points agents to it++**Files:**+- Create: `cli/src/agentClient/help.ts`, `cli/src/agentClient/help.spec.ts`+- Modify: `cli/src/cli.ts` (`usage`, the `help` word)++**Interfaces:**+- Consumes: `PS_USAGE`, `SHOW_USAGE`, `WAIT_USAGE`, `CLOSE_USAGE`, `WHOAMI_USAGE`, `EXIT`, `SPAWN_LIMITS`+ (commands.ts); `NEW_USAGE` (lib/newCommand.ts); `SEND_USAGE` (messages/command.ts); `outsideCaller` (model.ts).+- Produces: `agentsHelp(): string`; `helpFor(env: NodeJS.ProcessEnv, full: string): string`.++`next.ts` must not import `commands.ts` at module load if `commands.ts` imports `next.ts` (a cycle ESM handles for+functions, not for top-level constants). Put `agentsHelp` and `helpFor` in a new file `cli/src/agentClient/help.ts`+instead, with its spec `help.spec.ts`; `next.ts` stays the format alone.++- [ ] **Step 1: Write the failing tests**++`cli/src/agentClient/help.spec.ts`:++```ts+import { describe, expect, it } from 'vitest'+import { CLOSE_USAGE, EXIT, PS_USAGE, SHOW_USAGE, WAIT_USAGE, WHOAMI_USAGE } from './commands.js'+import { NEW_USAGE } from '../lib/newCommand.js'+import { agentsHelp, helpFor } from './help.js'++const synopsis = (usage: string) => usage.split('\n')[0].replace(/^Usage: /, '')++describe('harness help agents', () => {+ it('fits in 40 lines and names each verb as its usage does', () => {+ const text = agentsHelp()+ expect(text.split('\n').length).toBeLessThanOrEqual(40)+ for (const usage of [WHOAMI_USAGE, PS_USAGE, NEW_USAGE, WAIT_USAGE, SHOW_USAGE, CLOSE_USAGE]) expect(text).toContain(synopsis(usage))+ expect(text).toContain('harness send <name>[,<name>] "text"')+ })+ it('lists every exit code', () => {+ for (const code of Object.values(EXIT)) expect(agentsHelp()).toMatch(new RegExp(`\\b${code}\\b`))+ })+ it('uses placeholders, never a real name', () => {+ expect(agentsHelp()).not.toMatch(/--machine (?!<)/)+ })+})++describe('harness --help', () => {+ const full = 'harness vX — connect this computer to your machine\n…'+ it('points an agent to its help on the first line', () => {+ expect(helpFor({}, full).split('\n')[0]).toBe('An agent? Run: harness help agents')+ })+ it('puts the agents\' help first when an agent asks', () => {+ expect(helpFor({ CODEX_THREAD_ID: 't' }, full).startsWith(agentsHelp())).toBe(true)+ expect(helpFor({ AI_AGENT: 'cursor' }, full).startsWith(agentsHelp())).toBe(true)+ })+})+```++- [ ] **Step 2: Run to see them fail**++Run: `cd cli && npx vitest run src/agentClient/help.spec.ts`+Expected: FAIL: `./help.js` does not exist.++- [ ] **Step 3: Write `help.ts`**++```ts+/**+ * `harness help agents`: all an agent needs on one screen (docs/design/2026-10-15-agent-experience.md, part 4). Each+ * verb's line is its own usage's first line, so this cannot say an option the verb does not take.+ */+import { CLOSE_USAGE, EXIT, PS_USAGE, SHOW_USAGE, SPAWN_LIMITS, WAIT_USAGE, WHOAMI_USAGE } from './commands.js'+import { NEW_USAGE } from '../lib/newCommand.js'+import { SEND_USAGE } from '../messages/command.js'+import { outsideCaller } from './model.js'++const synopsis = (usage: string): string => usage.split('\n')[0].replace(/^Usage: /, '')+const sendLine = (): string => (SEND_USAGE.split('\n').find((l) => l.includes('harness send <name>[,<name>]')) ?? '').trim().split(/\s{2,}/)[0]++export function agentsHelp(): string {+ return [+ 'Harness for agents: start other agents, wait for them, read their answers, close them,',+ 'on this computer or another of the person\'s machines (--machine <machine>).',+ 'Every harness spends the person\'s tokens: start one only for work that runs beside yours,',+ 'needs another model\'s view, or takes long. Do quick work yourself.',+ '',+ `First: ${synopsis(WHOAMI_USAGE)} who you are here, and whether you may start harnesses`,+ ` ${synopsis(PS_USAGE)}`,+ ` ${synopsis(NEW_USAGE)}`,+ ` ${synopsis(WAIT_USAGE)}`,+ ` ${synopsis(SHOW_USAGE)}`,+ ` ${synopsis(CLOSE_USAGE)}`,+ ` ${sendLine()}`,+ '',+ 'A whole job:',+ ' harness new <agent> --name <name> <project> -- <task>',+ ' harness wait <name>',+ ' harness show <name>',+ ' harness close <name>',+ 'Every command ends with Next: the command to run next. --json gives it as "next".',+ '',+ 'States: working, idle, needs the person, installing, starting, stopped, gone, closed, failed.',+ `Exit codes: ${EXIT.ok} done · ${EXIT.failed} failed · ${EXIT.usage} wrong command · ${EXIT.needsInput} needs the person · `+ + `${EXIT.stopped} stopped or gone · ${EXIT.refused} refused (do not retry) · ${EXIT.timeout} still working when the wait ended.`,+ `Limits: ${SPAWN_LIMITS.livePerHarness} of yours open at once, ${SPAWN_LIMITS.perWindow} starts in ${SPAWN_LIMITS.windowMs / 60_000} minutes;`,+ 'a harness another agent started may not start harnesses.',+ 'Rules: name every harness. Put the whole task in it: you cannot message it after.',+ 'Close what you started once you have its answer. Never close one you did not start.',+ 'When a harness needs the person, tell the person: only they answer it.',+ 'Never ask a harness to publish, deploy, delete or push.',+ '',+ 'More: https://harness.autonomous.ai/agents',+ ].join('\n')+}++/** `harness --help`: a line for agents first; an agent asking gets its own help before the rest. */+export function helpFor(env: NodeJS.ProcessEnv, full: string): string {+ const text = `An agent? Run: harness help agents\n${full}`+ return outsideCaller(env, '') ? `${agentsHelp()}\n\n${text}` : text+}+```++`outsideCaller` reads only the environment, so an agent in a Harness pane counts by its own variables+(`CLAUDECODE` with `CLAUDE_CODE_SESSION_ID`, `CODEX_THREAD_ID`, `AI_AGENT`, `HARNESS_AGENT_SESSION`).++- [ ] **Step 4: Wire it into `cli.ts`**++- `usage()` builds its text into a string `full` and prints `helpFor(process.env, full)`.+- Before the `usage()` call for `help`: `if (cmd === 'help' && args[0] === 'agents') { console.log(agentsHelp()); process.exit(0) }`.+- In the help text, under `harness mcp`, add ` harness help agents the agent commands, states, exit codes and rules on one screen`.++- [ ] **Step 5: Run, and see it built**++Run: `cd cli && npx vitest run src/agentClient/help.spec.ts && npm run typecheck && npx tsx src/cli.ts help agents | wc -l && CODEX_THREAD_ID=t npx tsx src/cli.ts --help | head -3 && npx tsx src/cli.ts --help | head -1`+Expected: tests pass; at most 40 lines; the agent's `--help` starts with `Harness for agents:`; a person's starts with+`An agent? Run: harness help agents`.++- [ ] **Step 6: Commit**++```bash+git add cli/src/agentClient/help.ts cli/src/agentClient/help.spec.ts cli/src/cli.ts+git commit -m "harness help agents: the agent commands, states, exit codes and rules on one screen"+```++## Phase 8: MCP (not in this run)++The person narrowed this run to agents using the CLI (October 15): Tasks 9 and 10 are skipped and kept here for a+later run. Under `harness mcp`, the verbs' `Next` lines already name MCP tools (`step()`), so MCP agents still get them.++### Task 9: Each tool returns its JSON as `structuredContent`, with an `outputSchema`++**Files:**+- Modify: `cli/src/agentClient/commands.ts` (an `emit` helper used by `ps`, `whoami`, `show`, `wait`, `close`),+ `cli/src/lib/newCommand.ts` (its agent success and installing paths), `cli/src/agentClient/mcp.ts`+- Test: `cli/src/agentClient/mcp.spec.ts`, `cli/src/agentClient/commands.spec.ts`++**Interfaces:**+- Produces: `STRUCTURED_MARK = '\u001eharness-json '` (commands.ts): under `HARNESS_VIA_MCP=1` a verb prints its text,+ then one line `STRUCTURED_MARK + JSON`. `result(tool, ran, structured: boolean)` moves that line into+ `structuredContent`.++- [ ] **Step 1: Write the failing tests**++`commands.spec.ts`:++```ts+ it('under harness mcp, prints its JSON on one marked line after the text', async () => {+ const d = new FakeDaemon()+ d.frames = [frame('lead', { engine: 'claude' })]+ const h = harness(d, { env: { HARNESS_VIA_MCP: '1' } })+ expect(await whoamiCommand([], h.deps)).toBe(EXIT.ok)+ const marked = h.out.filter((l) => l.startsWith(STRUCTURED_MARK))+ expect(marked).toHaveLength(1)+ expect(JSON.parse(marked[0].slice(STRUCTURED_MARK.length)).context.caller.kind).toBe('agent')+ expect(h.out[0]).toMatch(/^You: /)+ })+```++`mcp.spec.ts`:++```ts+ it('moves the marked JSON into structuredContent on 2025-06-18 and later, and drops it before', () => {+ const out = `kid on studio: closed. Its conversation is kept; the person can resume it.\n${STRUCTURED_MARK}{"name":"kid","closed":true}\n`+ expect(result('harness_close', { code: 0, out, err: '' }, true)).toEqual({+ content: [{ type: 'text', text: 'kid on studio: closed. Its conversation is kept; the person can resume it.' }],+ structuredContent: { name: 'kid', closed: true },+ })+ expect(result('harness_close', { code: 0, out, err: '' }, false)).toEqual({+ content: [{ type: 'text', text: 'kid on studio: closed. Its conversation is kept; the person can resume it.' }],+ })+ })++ it('declares outputSchema only to clients that read it', async () => {+ const run: Runner = async () => ({ code: 1, out: '', err: '' })+ const state = {}+ await answer({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } }, { run, whoamiMs: 1 }, state)+ const tools = (await answer({ jsonrpc: '2.0', id: 2, method: 'tools/list' }, { run }, state))!.result as { tools: Array<Record<string, unknown>> }+ expect(tools.tools.every((t) => t.name === 'harness_send' || (t.outputSchema as { type?: string })?.type === 'object')).toBe(true)+ const old = {}+ await answer({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-03-26' } }, { run, whoamiMs: 1 }, old)+ const plain = (await answer({ jsonrpc: '2.0', id: 2, method: 'tools/list' }, { run }, old))!.result as { tools: Array<Record<string, unknown>> }+ expect(plain.tools.some((t) => 'outputSchema' in t)).toBe(false)+ })+```++- [ ] **Step 2: Run to see them fail**++Run: `cd cli && npx vitest run src/agentClient -t "marked|structuredContent|outputSchema"`+Expected: FAIL: `STRUCTURED_MARK` is not exported.++- [ ] **Step 3: Implement the marked line**++`commands.ts`:++```ts+/** Under `harness mcp`, the line that carries a verb's JSON after its text, for `structuredContent` (mcp.ts). */+export const STRUCTURED_MARK = '\u001eharness-json '++/** A verb's answer: its JSON with --json; else its text, and under `harness mcp` its JSON on a marked line too. */+function emit(s: Setup, json: boolean, data: unknown, text: string, indent?: number): void {+ if (json) { s.out(JSON.stringify(data, null, indent)); return }+ s.out(text)+ if (s.env[VIA_MCP_ENV] === '1') s.out(STRUCTURED_MARK + JSON.stringify(data))+}+```++`ps`, `whoami`, `show`, `wait` and `close` print through `emit`, each keeping its JSON's indent today (`ps` and+`whoami` and `show` and `wait` use `null, 1`; `close` none). `show` and `wait` collect their lines into one string+first. In `newCommand.ts`, the agent's success and installing paths output the same marked line under+`env[VIA_MCP_ENV] === '1'` (import `STRUCTURED_MARK`).++- [ ] **Step 4: Implement in `mcp.ts`**++- `state` gains `protocol?: string`, set in `initialize` to the negotiated version.+- `const structured = (state.protocol ?? '') >= '2025-06-18'` (the versions are dates, so they compare as strings).+- `tools/list`: with `structured`, each tool but `harness_send` carries `outputSchema` from a table:++```ts+const OUTPUT: Record<string, Record<string, unknown>> = {+ harness_whoami: { context: { type: 'object' } },+ harness_list: { context: { type: 'object' }, harnesses: { type: 'array' }, next: { type: 'array' } },+ harness_start: { ok: { type: 'boolean' }, agent: { type: 'object' }, effect: { type: 'string' }, next: { type: 'array' } },+ harness_wait: { harnesses: { type: 'array' } },+ harness_read: { name: { type: 'string' }, state: { type: 'string' }, answer: { type: 'string' }, next: { type: 'array' } },+ harness_close: { name: { type: 'string' }, closed: { type: 'boolean' }, effect: { type: 'string' }, next: { type: 'array' } },+}+const outputSchema = (tool: string) => ({ type: 'object', properties: OUTPUT[tool] }) // nothing required: a refusal or a cancel has other fields+```++- `result(tool, ran, structured = false)`: take every line of `ran.out` that starts with `STRUCTURED_MARK` out of+ the text; when `structured`, the call is answered (not `isError`), and the last such line parses to an object, add+ `structuredContent`.++- [ ] **Step 5: Run**++Run: `cd cli && npx vitest run src/agentClient src/lib/newCommand.spec.ts && npm run typecheck`+Expected: pass.++- [ ] **Step 6: Commit**++```bash+git add cli/src/agentClient cli/src/lib/newCommand.ts+git commit -m "harness mcp returns each answer's JSON as structuredContent, with an outputSchema per tool"+```++### Task 10: `harness mcp --read-only`++**Files:**+- Modify: `cli/src/agentClient/mcp.ts` (`McpDeps.readOnly`, the tool filter, `INSTRUCTIONS`), `cli/src/cli.ts` (`case 'mcp'`, help line)+- Test: `cli/src/agentClient/mcp.spec.ts`++- [ ] **Step 1: Write the failing test**++```ts+ it('serves only the tools that look and wait with --read-only, and says so', async () => {+ const run: Runner = async () => ({ code: 1, out: '', err: '' })+ const init = await answer({ jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }, { run, readOnly: true, whoamiMs: 1 })+ expect((init!.result as { instructions: string }).instructions).toContain('This server only looks and waits')+ const list = await answer({ jsonrpc: '2.0', id: 2, method: 'tools/list' }, { run, readOnly: true, inPane: true })+ expect((list!.result as { tools: Array<{ name: string }> }).tools.map((t) => t.name)).toEqual(['harness_whoami', 'harness_list', 'harness_wait', 'harness_read'])+ const call = await answer({ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'harness_close', arguments: { name: 'x' } } }, { run, readOnly: true })+ expect(call!.error).toEqual({ code: -32602, message: 'Unknown tool: harness_close' })+ })+```++- [ ] **Step 2: Run to see it fail**++Run: `cd cli && npx vitest run src/agentClient/mcp.spec.ts -t "read-only"`+Expected: FAIL: all tools are listed.++- [ ] **Step 3: Implement**++`McpDeps` gains `readOnly?: boolean`. `const LOOKS = new Set(['harness_whoami', 'harness_list', 'harness_wait', 'harness_read'])`;+the tool filter adds `&& (!deps.readOnly || LOOKS.has(tool.name))`. With `readOnly`, the instructions end with+`\n\nThis server only looks and waits: it cannot start, message or close harnesses.` In `cli.ts`,+`mcpCommand({ …, readOnly: rest.includes('--read-only') })`, and the help line becomes+`harness mcp [--read-only] the agent verbs as an MCP server on stdin/stdout; --read-only: look and wait only`.++- [ ] **Step 4: Run**++Run: `cd cli && npx vitest run src/agentClient/mcp.spec.ts`+Expected: pass.++- [ ] **Step 5: Commit**++```bash+git add cli/src/agentClient/mcp.ts cli/src/agentClient/mcp.spec.ts cli/src/cli.ts+git commit -m "harness mcp --read-only serves only the tools that look and wait"+```++## The pages and the whole check++### Task 11: The pages agents read, the docs, and the end to end++**Files:**+- Modify: `plugins/harness/skills/harness/SKILL.md`, `website/public/llms.txt`, `website/public/agents/index.html`,+ `docs/cli.md`, `docs/design/2026-10-11-agent-client.md`, `cli/src/agentClient/mcp.ts` (`INSTRUCTIONS`),+ `cli/e2e/agentClient.e2e.ts`, `cli/e2e/freshMachineEngines.e2e.ts`+- Test: `website/scripts/agents-site.spec.ts` (unchanged; it must still pass), the e2e file++- [ ] **Step 1: Say the new behaviour where agents read**++In each of SKILL.md, `llms.txt` and `/agents`, with placeholders only:+- every command ends with `Next:`, the command to run next; `--json` has it as `next`;+- exit 5 means refused: do not retry, tell the person or do the work yourself;+- `needs the person`: tell the person;+- `harness help agents` prints all of it on one screen.+`INSTRUCTIONS` gains: `Each answer ends with Next: the call to make next. A refusal is final: do not retry it.`++- [ ] **Step 2: Run the page checks and the agent client**++Run: `cd website && npx vitest run scripts/agents-site.spec.ts && cd ../cli && npx vitest run src/agentClient src/lib/newCommand.spec.ts src/messages src/engines/kit/hookSettings.spec.ts && npm run typecheck`+Expected: pass. The website spec fails on any option the pages name that a usage does not have.++- [ ] **Step 3: Update the end to end's expected text, then run it once**++In `cli/e2e/agentClient.e2e.ts` and `freshMachineEngines.e2e.ts`, change the lines this plan changed (listed by+`grep -n "Created .* on \|Read it: \|Its conversation is kept\|Close it once\|of your own open\|needs-input ·"`): an+agent's start now prints `<name> on this computer: starting. …` and `Next: harness wait <name> (…)`; `close` prints+`<name> on this computer: closed. …`; `show` ends with `Next: harness close <name> (…)`; `ps` ends with Next; `wait`+says `needs the person`. The person's starts in `freshMachineEngines` keep `Created …`.++Run: `cd cli && npx vitest run --config vitest.e2e.config.ts e2e/agentClient.e2e.ts > /tmp/agent-e2e.log 2>&1; tail -30 /tmp/agent-e2e.log`+(Use the e2e config and command the phase 1 to 3 run used.)+Expected: all pass except the known "trust its folder" failure that also fails on `main` (exit 124).++- [ ] **Step 4: Commit**++```bash+git add plugins website docs cli/src/agentClient/mcp.ts cli/e2e+git commit -m "The agent pages and docs teach Next, exit 5, needs the person and harness help agents"+```++### After the last task++- The final whole-branch review, as in phases 1 to 3.+- The eval (phase 11) runs only with the person's approval: once on `main` for the baseline, once on this branch.+- Phases 6 (signed-out detection) and 9 (across machines) get their own plan after a short look at what each machine+ can tell (its Harness version, an engine's sign-in screen).diff --git a/plugins/harness/skills/harness/SKILL.md b/plugins/harness/skills/harness/SKILL.mdindex 9988ed684..8f6918cb7 100644--- a/plugins/harness/skills/harness/SKILL.md+++ b/plugins/harness/skills/harness/SKILL.md@@ -92,9 +92,13 @@ harness close <name> [--now] # when you are done with one- Read the result with `show` instead of asking for a summary.- `close` what you started once you have its answer. It keeps the conversation; the person can resume it.It refuses while the harness is working, unless `--now`. One closed while still starting may have no- conversation to keep yet, and `close` says so. `show` reminds you when one of yours sits idle, and `ps`- says how many of yours are open.-- Add `--json` to any verb for JSON. Every error says what to run next.+ conversation to keep yet, and `close` says so, with how many of yours are still open.+- Every verb ends with `Next:`, the command to run next: follow it. `--json` gives it as `next`. Every error+ says what to run next.+- A harness waiting on a question or a permission is shown as `needs the person`: tell the person.+- Exit 5 means refused (your limits, the person's setting, or a harness you did not start): do not retry it;+ tell the person, or do the work yourself.+- `harness help agents` prints the commands, states, exit codes and rules on one screen.## Inside a harness, or outsidediff --git a/website/public/agents/index.html b/website/public/agents/index.htmlindex 94a9fdfe5..fa91d8167 100644--- a/website/public/agents/index.html+++ b/website/public/agents/index.html@@ -147,7 +147,10 @@ curl -fsSL https://raw.githubusercontent.com/autonomous-ai/openharness/main/plug</div><p>Name every harness you start with <code>--name</code>: an unnamed one takes its session's title, which changes.Every command also takes the start of a harness's id, takes <code>--json</code> for JSON, and prints its usage- with <code>--help</code>. Every error says what to run next.</p>+ with <code>--help</code>. Every command ends with <code>Next:</code>, the command to run next (in JSON,+ <code>next</code>), and every error says what to run next. A harness waiting on a question or a permission is+ shown as <code>needs the person</code>: tell the person. <code>harness help agents</code> prints the commands,+ states, exit codes and rules on one screen.</p><p id="no-prompts">Once Harness runs on a computer, Claude Code and Codex there run these commands and Harness's MCPtools without asking: Harness adds them to their permission rules (Claude Code's <code>settings.json</code>,Codex's <code>rules/harness.rules</code>), and Codex runs them outside its sandbox. What an agent may do with them@@ -166,6 +169,8 @@ curl -fsSL https://raw.githubusercontent.com/autonomous-ai/openharness/main/plug<tr><td><code>3</code></td><td><code>wait</code>: a harness needs the person (a question or a permission). Tellthe person; only they answer it.</td></tr><tr><td><code>4</code></td><td><code>wait</code>: a harness stopped or is gone.</td></tr>+ <tr><td><code>5</code></td><td>Refused: your limits, the person's setting, or a harness you did not start. Do not+ retry it; tell the person, or do the work yourself.</td></tr><tr><td><code>124</code></td><td><code>wait</code>: timed out while a harness was still working. Wait again, orread it.</td></tr></tbody>diff --git a/website/public/llms.txt b/website/public/llms.txtindex 201cb6c3e..5d281770c 100644--- a/website/public/llms.txt+++ b/website/public/llms.txt@@ -27,6 +27,8 @@ harness close NAME [--now] # save its screen and stop i`ps`, `show`, `wait` and `close` take `--machine NAME` too, for a harness on another of the person's machines.+Every command ends with `Next:`, the command to run next, and `--json` gives the same as `next`. Exit 5 means refused (your limits, the person's setting, or a harness you did not start): do not retry it; tell the person, or do the work yourself. A harness waiting on a question or a permission is said as `needs the person`: tell the person, only they answer it. `harness help agents` prints the commands, states, exit codes and rules on one screen.+Once Harness runs on a computer, Claude Code and Codex there run these commands and Harness's MCP tools without asking: Harness adds them to their permission rules, and Codex runs them outside its sandbox. Run each `harness` command by itself or join them with `&&`; piped or joined with other commands, the rule no longer matches. Where Harness has not set an agent up, run `harness` outside its sandbox, which cannot reach Harness's local daemon.`harness mcp` serves the same as MCP tools over stdio (command `harness`, arguments `["mcp"]`): `harness_whoami`, `harness_list`, `harness_start`, `harness_wait`, `harness_read`, `harness_close`, and `harness_send` inside a harness (teammates in its tab only, while Agent Messages are on: Settings ▸ Experimental, off by default).