Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Harness for agents: ps, show, wait, close; new and send for agents (#1180)

Dee3ac4a39cb518
diff --git a/cli/e2e/agentClient.e2e.ts b/cli/e2e/agentClient.e2e.ts
new file mode 100644
index 000000000..1544c1ae8
--- /dev/null
+++ b/cli/e2e/agentClient.e2e.ts
@@ -0,0 +1,121 @@
+/**
+ * Harness for agents on the real daemon (docs/design/2026-10-11-agent-client.md): an agent, from its own pane, runs
+ * the `harness` verbs as it would through its shell tool. It lists the harnesses, starts one with a task, waits for
+ * it, reads its answer, messages it without any tab having Agent Messages on, and closes it; it may not close one it
+ * did not start. The fake engines answer by echoing (harness/fakeEngine.mjs).
+ *
+ * Signed in to the fake backend, which answers the account's tabs: none has Agent Messages on.
+ */
+import { spawn } from 'node:child_process'
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'
+
+const ME: FakeMachine = { machineId: 'b8'.repeat(16), computerId: 'e2e-computer-0000-0000-0000000000b8', name: 'studio', token: 'e2e-token-agent-client' }
+const signIn = (d: IsolatedDaemon) => writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({
+ version: 1, accessToken: ME.token, autonomousEnv: 'prod', computerId: ME.computerId,
+ machineId: ME.machineId, expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',
+}), { mode: 0o600 })
+
+/** `harness <args>` from [pane], as an agent's shell tool runs it: not a terminal, so plain text. */
+function harness(d: IsolatedDaemon, pane: string, args: string[]): Promise<{ code: number; out: string; err: string }> {
+ return new Promise((done) => {
+ const child = spawn(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], {
+ cwd: CLI_ROOT, env: { ...d.env, TMUX_PANE: pane }, stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let out = '', err = ''
+ child.stdout.on('data', (chunk) => { out += chunk })
+ child.stderr.on('data', (chunk) => { err += chunk })
+ child.on('close', (code) => done({ code: code ?? -1, out, err }))
+ })
+}
+
+describe('Harness for agents, end to end', () => {
+ let daemon: IsolatedDaemon | undefined
+ let backend: FakeBackend | undefined
+ afterEach(async () => {
+ await daemon?.close(); daemon = undefined
+ await backend?.close(); backend = undefined
+ })
+
+ it('an agent sees, starts, waits for, reads, messages and closes a harness of its own', async () => {
+ const relay = await FakeBackend.start()
+ backend = relay
+ relay.addMachine(ME)
+ relay.agentMessages = { revision: 1, machines: [{ machineId: ME.machineId, name: 'studio' }], tabs: [] }
+ const d = await IsolatedDaemon.create({ env: {
+ BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId,
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000',
+ } })
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ signIn(d)
+ await d.start()
+ const client = await LocalClient.connect(d, { machineId: ME.machineId })
+
+ const leadDir = join(d.projectsDir, 'lead')
+ mkdirSync(leadDir, { recursive: true })
+ const made = await client.request('agent_create', { engine: 'claude', cwd: leadDir, bypassPermission: true, name: 'lead' }, 90_000)
+ expect(made.error, JSON.stringify(made)).toBeUndefined()
+ const lead = await until('lead to bind its conversation', async () => {
+ const row = ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents).find((a) => a.id === made.agent.id)
+ return row?.sessionId && row.status === 'active' ? row : null
+ }, 60_000, 500)
+ const run = (...args: string[]) => harness(d, String(lead.tmuxPane), args)
+
+ // It sees itself.
+ const ps = await run('ps')
+ expect(ps.code, ps.err).toBe(0)
+ expect(ps.out).toMatch(/^You are "lead" \(/)
+ expect(ps.out).toMatch(/\nlead +Claude Code +\w+ +person \(you\)/)
+
+ // It starts a harness with a task, which reads who sent it.
+ const kidDir = join(d.projectsDir, 'kid')
+ mkdirSync(kidDir, { recursive: true })
+ const started = await run('new', 'claude', kidDir, '--name', 'kid', '--', 'hello kid')
+ expect(started.code, started.err).toBe(0)
+ expect(started.out).toContain('Created kid on this computer')
+ expect(started.out).toContain('Read it: harness show kid · wait for it: harness wait kid')
+ const ledger = readFileSync(join(d.dataDir, 'agent-client', 'started.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line))
+ expect(ledger).toEqual([expect.objectContaining({ depth: 1, by: expect.objectContaining({ agentId: lead.id, name: 'lead' }), child: expect.objectContaining({ name: 'kid' }) })])
+
+ // It waits for it, then reads its answer.
+ const waited = await run('wait', 'kid', '--timeout', '2m')
+ expect(waited.code, waited.out + waited.err).toBe(0)
+ 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).toContain('asked: [from lead · Claude Code · ')
+ expect(shown.out).toContain('the harness that started you. It reads your answer itself; to ask it something while you work: harness send lead "…"]')
+ expect(shown.out).toContain('hello kid')
+ expect((await run('ps')).out).toMatch(/\nkid +Claude Code +\w+ +you /)
+
+ // No tab has Agent Messages on, and still the two message each other.
+ const sent = await run('send', 'kid', 'Also check the footer.')
+ expect(sent.code, sent.out + sent.err).toBe(0)
+ expect(sent.out).toMatch(/→ kid: (queued|delivered)/)
+ const kid = ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents).find((a) => a.name === 'kid')!
+ const back = await harness(d, String(kid.tmuxPane), ['send', 'lead', 'Footer checked.'])
+ expect(back.code, back.out + back.err).toBe(0)
+
+ // 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)
+ 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.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.')
+ const after = await run('ps', '--all', '--json')
+ expect(JSON.parse(after.out).harnesses).toEqual(expect.arrayContaining([expect.objectContaining({ name: 'kid', state: 'stopped', startedBy: 'you' })]))
+ client.close()
+ })
+})
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 8dc30e9cb..671f56292 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -1724,10 +1724,27 @@ export async function run(engine, config = {}, { native = false } = {}) {
}
}
})
+ // A first message on the command line (`claude "…"`, `codex "…"`, the daemon's `firstPromptArgs`) is sent as the
+ // session starts, as both CLIs send theirs. The fake used to drop it, so a harness started with a task never
+ // started its turn here (found by the agent verbs' end to end, e2e/agentClient.e2e.ts).
+ const launchPrompt = firstPromptOf(args)
+ if (launchPrompt) queue = queue.then(() => handle(launchPrompt))
process.on('SIGTERM', () => process.exit(0))
setInterval(() => {}, 60_000)
}
+/** The options both CLIs read a value after, and Codex's `resume <id>` and `fork <id>`: the word after one is not a
+ * prompt. */
+const TAKES_VALUE = new Set(['--model', '-m', '--permission-mode', '--resume', '-r', '--session-id', '--append-system-prompt',
+ '--mcp-config', '--effort', '-c', '--config', '-s', '--sandbox', '-a', '--ask-for-approval', 'resume', 'fork'])
+
+/** The prompt at the end of the command line, when there is one. */
+function firstPromptOf(args) {
+ const last = args.at(-1)
+ if (!last || last.startsWith('-') || TAKES_VALUE.has(last) || args.length > 1 && TAKES_VALUE.has(args.at(-2))) return null
+ return last
+}
+
// The native Codex: this module run as a script by `codexWrapper`. Last, so everything `run` reads at
// the top level of the module is there when it starts.
if (process.env[CODEX_NATIVE] && process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
diff --git a/cli/skills/harness/SKILL.md b/cli/skills/harness/SKILL.md
new file mode 100644
index 000000000..cfa8391d2
--- /dev/null
+++ b/cli/skills/harness/SKILL.md
@@ -0,0 +1,56 @@
+---
+name: harness
+description: You are running inside Harness, which can run other coding agents (Claude Code, Codex, and more) as visible sessions on this machine or the person's other machines. Use when the work calls for another model, another machine, a long-running job that should outlive this turn, or something the person should watch; or to check on, message or close harnesses you started. Not for quick fan-out inside one task: use your own sub-agents for that.
+---
+
+# Harness
+
+You are a harness: one agent session that Harness runs and the person can see. You can start other harnesses,
+read them, wait for them, message them and close them, with the `harness` command.
+
+## When to use it
+
+Only when your own tools cannot do the job:
+
+1. **Another model**: a second opinion from Codex, a task suited to another agent.
+2. **Another machine**: the Mac mini, a GPU box (`harness machines` lists them).
+3. **Work that outlives you**: a long job that should keep running after your turn or your context ends.
+4. **The person should see it**: everything you start appears in Harness, where they can watch and step in.
+
+A quick parallel search or edit inside your own task is cheaper with your own sub-agents. Do that instead.
+
+## New harness or an existing one
+
+1. Run `harness ps`. It lists the harnesses here: state, who started each, and what each is about.
+2. You may give work only to a harness **you started** (STARTED BY says `you`), or to a teammate in a tab with
+ Agent Messages on (`harness send` alone lists them). A harness the person is driving is theirs: you may
+ `show` and `wait` on it, never send it work.
+3. If one you may use is already on **the same work on the same subject**, and it is idle, send it there: it
+ has the context. Otherwise start a new one: for unrelated work, for work to run in parallel, for another
+ agent or machine, or when the matching one is busy with something else.
+
+## The verbs
+
+```
+harness ps [--all] # the harnesses here
+harness new [agent] [@machine] [folder] --name <name> -- <task>
+harness wait <name>[,<name>…] [--any] [--timeout 30m]
+harness show <name> # its state, the last ask and its answer
+harness send <name> "text" # a follow-up to one you started
+harness close <name> # when you are done with one you started
+```
+
+- **Always `--name`** what you start (`--name reviewer`): an unnamed harness takes its session's title, which
+ changes. Every verb also takes the start of an id.
+- Put the whole task in `-- <task>`: what to do, where, what done looks like, and how to report back.
+ The harness reads that it came from you, and how to answer you.
+- `wait` exits 0 when it is idle, 3 when it needs the person (a question or a permission: only the person
+ answers those, so tell them), 4 when it stopped, 124 on timeout.
+- Read the result with `show` instead of asking for a summary; send a follow-up only when you need more.
+- `close` what you started once you have what you need. It keeps the conversation; the person can resume it.
+
+## Limits
+
+At most 8 live harnesses of yours, 20 starts in 10 minutes, and a harness you start may start others, but
+the ones it starts may not. Every limit refuses with a message; do not work around it. Never ask a harness to
+publish, deploy, delete or push to main for you: those are the person's to ask for.
diff --git a/cli/src/agentClient/commands.spec.ts b/cli/src/agentClient/commands.spec.ts
new file mode 100644
index 000000000..e02be7e69
--- /dev/null
+++ b/cli/src/agentClient/commands.spec.ts
@@ -0,0 +1,633 @@
+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, closeCommand, EXIT, parseDuration, psCommand, showCommand, spawnRefusal, SPAWN_LIMITS, waitCommand, type ClientDeps } from './commands.js'
+import { AgentClientError, type Daemon, type Where } from './daemon.js'
+import { Ledger, ledgerPath } from './ledger.js'
+import type { Frame } from './model.js'
+
+const NOW = Date.parse('2026-10-11T12:00:00Z')
+
+const frame = (id: string, over: Partial<Frame> = {}): Frame => ({
+ id, sessionId: `s-${id}`, name: id, engine: 'codex', status: 'active', activity: { state: 'idle' }, tmuxPane: `%${id}`,
+ project: { cwd: `/work/${id}`, branch: 'main' }, createdAt: '2026-10-11T10:00:00Z', updatedAt: '2026-10-11T11:59:00Z', ...over,
+})
+
+type Handler = (payload: Record<string, unknown>) => Record<string, unknown>
+
+/** A daemon answering from a table; `screens` scripts what each inspect sees, one look at a time. */
+class FakeDaemon implements Daemon {
+ requests: Array<{ type: string; payload: Record<string, unknown> }> = []
+ closed = false
+ frames: Frame[] = []
+ screens = new Map<string, string[]>()
+ pages = new Map<string, Record<string, unknown>[]>()
+ extra: Record<string, Handler> = {}
+ constructor(readonly machineId = 'm') {}
+ async request(type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> {
+ this.requests.push({ type, payload })
+ if (this.extra[type]) return this.extra[type](payload)
+ switch (type) {
+ case 'agents_list': return { agents: this.frames.filter((f) => payload.includeStopped || f.status !== 'stopped') }
+ case 'agent_recent': return { agentId: payload.agentId, events: [{ kind: 'summary', text: `${String(payload.agentId)} text`, recap: `${String(payload.agentId)} recap` }], asks: [`ask of ${String(payload.agentId)}`] }
+ case 'agent_close': {
+ if (payload.mode === 'inspect') {
+ const seen = this.screens.get(String(payload.agentId)) ?? []
+ return { activity: seen.length > 1 ? seen.shift() : seen[0] ?? 'idle' }
+ }
+ return { closed: true }
+ }
+ case 'session_get': {
+ const pages = this.pages.get(String(payload.sessionId)) ?? []
+ const index = payload.before ? Number(payload.before) : 0
+ return pages[index] ?? { events: [], hasMore: false }
+ }
+ default: return { error: 'UNKNOWN' }
+ }
+ }
+ close(): void { this.closed = true }
+}
+
+let dir: string
+let where: Where
+beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'agent-client-'))
+ writeFileSync(join(dir, 'machine-name'), 'studio\n')
+ where = { port: 1, dataDir: dir, machineId: 'm' }
+})
+afterEach(() => rmSync(dir, { recursive: true, force: true }))
+
+function harness(daemon: FakeDaemon, over: Partial<ClientDeps> & { others?: Record<string, FakeDaemon> } = {}) {
+ const out: string[] = [], err: string[] = []
+ let clock = NOW
+ const deps: ClientDeps = {
+ pane: '%lead', where: () => where,
+ open: async (_w, machineId) => {
+ if (!machineId || machineId === 'm') return daemon
+ const other = over.others?.[machineId]
+ if (!other) throw new AgentClientError('NO_PEER_LINK', 'not linked')
+ return other
+ },
+ ledger: (d) => new Ledger(ledgerPath(d)),
+ out: (l) => out.push(l), err: (l) => err.push(l),
+ now: () => clock, sleep: async (ms) => { clock += ms }, intervalMs: 1_000,
+ ...over,
+ }
+ return { deps, out, err, ledger: new Ledger(ledgerPath(dir)), advance: (ms: number) => { clock += ms } }
+}
+
+const started = (ledger: Ledger, by: string, child: string, childMachine = 'm', at = NOW) => ledger.append({
+ at, depth: 1, by: { machineId: 'm', agentId: by, name: by, engine: 'claude' }, child: { machineId: childMachine, agentId: child, name: child },
+})
+
+const ev = (type: string, payload: Record<string, unknown> = {}) => ({ type, payload })
+
+describe('harness ps', () => {
+ it('lists the harnesses here: who you are, state, who started each, and what each is about', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead', { engine: 'claude' }), frame('kid', { activity: { state: 'working' } }), frame('sh', { engine: 'terminal' })]
+ const h = harness(d)
+ started(h.ledger, 'lead', 'kid')
+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)
+ const text = h.out.join('\n')
+ expect(text).toMatch(/^You are "lead" \(lead\)\.\nNAME +AGENT +STATE +STARTED BY +ACTIVE +FOLDER/)
+ expect(text).toMatch(/kid +Codex +working +you +1m +\/work\/kid \(main\)\n kid recap/)
+ expect(text).toMatch(/lead +Claude Code +idle +person \(you\)/)
+ expect(text).not.toContain('sh ')
+ expect(d.closed).toBe(true)
+ })
+
+ it('prints JSON for programs, and asks for stopped ones with --all', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead'), frame('old', { status: 'stopped' })]
+ d.extra.agent_recent = (p) => (p.agentId === 'lead' ? { error: 'NOPE' } : { events: [{ kind: 'x', text: '' }, { kind: 'y' }], asks: [' first ask ', 3] })
+ const h = harness(d, { pane: undefined })
+ expect(await psCommand(['--all', '--json'], h.deps)).toBe(EXIT.ok)
+ const parsed = JSON.parse(h.out[0])
+ expect(parsed.you).toBeNull()
+ expect(parsed.machine).toBe('studio')
+ expect(parsed.harnesses.map((r: { name: string }) => r.name)).toEqual(['lead', 'old'])
+ expect(d.requests[0]).toMatchObject({ type: 'agents_list', payload: { includeStopped: true } })
+ // A stopped harness is not asked what it is about.
+ expect(d.requests.filter((r) => r.type === 'agent_recent').map((r) => r.payload.agentId)).toEqual(['lead'])
+ })
+
+ it('says what it shows when there is nothing, uses the asks when there is no summary, and survives a summary that does not come', async () => {
+ const empty = harness(new FakeDaemon())
+ expect(await psCommand([], empty.deps)).toBe(EXIT.ok)
+ expect(empty.out).toEqual(['No harnesses on this machine.'])
+ const d = new FakeDaemon()
+ d.frames = [frame('a'), frame('b')]
+ d.extra.agent_recent = (p) => { if (p.agentId === 'b') throw new Error('slow'); return { events: [], asks: ['the ask'] } }
+ const h = harness(d)
+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)
+ expect(h.out.join('\n')).toContain(' asked: the ask')
+ })
+
+ it('refuses names and unknown options with the usage, and prints the usage for --help', async () => {
+ const h = harness(new FakeDaemon())
+ expect(await psCommand(['kid'], h.deps)).toBe(EXIT.usage)
+ expect(h.err[0]).toBe('harness ps takes no names. To read one: harness show kid')
+ expect(await psCommand(['--bogus'], h.deps)).toBe(EXIT.usage)
+ expect(h.err).toContain('Unknown option --bogus.')
+ expect(await psCommand(['--help'], h.deps)).toBe(EXIT.ok)
+ expect(h.out.at(-1)).toMatch(/^Usage: harness ps/)
+ })
+
+ it('says when the daemon cannot be reached or cannot list, in words or JSON', async () => {
+ const down = harness(new FakeDaemon(), { open: async () => { throw new AgentClientError('DAEMON_UNREACHABLE', 'Harness is not running here.') } })
+ expect(await psCommand([], down.deps)).toBe(EXIT.failed)
+ expect(down.err).toEqual(['Harness is not running here.'])
+ const d = new FakeDaemon()
+ d.extra.agents_list = () => ({ error: 'BUSY' })
+ const h = harness(d)
+ expect(await psCommand(['--json'], h.deps)).toBe(EXIT.failed)
+ expect(JSON.parse(h.out[0])).toEqual({ error: 'BUSY', detail: 'Harness could not list its harnesses. Try again.' })
+ expect(d.closed).toBe(true)
+ const odd = harness(new FakeDaemon(), { open: async () => { throw 'string' } })
+ expect(await psCommand([], odd.deps)).toBe(EXIT.failed)
+ expect(odd.err).toEqual(['string'])
+ })
+})
+
+describe('harness show', () => {
+ it('shows the state and the last turn, reading back a page at a time until it finds the ask', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead'), frame('reviewer')]
+ d.pages.set('s-reviewer', [
+ { events: [ev('tool_start'), ev('tool_end'), ev('text_delta', { content: 'Two bugs.' }), ev('done')], hasMore: true, oldestCursor: '1' },
+ { events: [ev('user_message', { content: 'review 3f2a' })], hasMore: false },
+ ])
+ const h = harness(d)
+ 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',
+ 'folder: /work/reviewer (main)',
+ 'asked: review 3f2a',
+ 'answer (after 1 tool calls):',
+ 'Two bugs.',
+ ])
+ 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' },
+ ])
+ })
+
+ it('clips a long answer and says how to read the rest; says when it waits for the person', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead'), frame('long')]
+ d.screens.set('long', ['needs_input'])
+ 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).toContain('xxxxxxxxx…')
+ expect(h.out).toContain('… 40 more characters: harness show long --chars 50')
+ expect(h.out.at(-1)).toMatch(/waiting for 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('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' })]
+ d.extra.session_get = () => ({ error: 'ENGINE_UNAVAILABLE' })
+ const h = harness(d, { pane: undefined })
+ expect(await showCommand(['fresh'], h.deps)).toBe(EXIT.ok)
+ 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')
+ // 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 ·')
+ })
+
+ it('stops reading back after four pages', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('chatty')]
+ d.pages.set('s-chatty', Array.from({ length: 6 }, (_, i) => ({ events: [ev('tool_start')], hasMore: true, oldestCursor: String(i + 1) })))
+ const h = harness(d, { pane: undefined })
+ expect(await showCommand(['chatty'], h.deps)).toBe(EXIT.ok)
+ expect(d.requests.filter((r) => r.type === 'session_get')).toHaveLength(4)
+ expect(h.out).toContain('No turn yet.')
+ })
+
+ it('refuses no name, two names, a bad --chars, and says which harnesses a name could mean', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('review-a'), frame('review-b'), frame('solo', { status: 'stopped' }), frame('solo2', { name: 'solo', status: 'stopped' })]
+ const h = harness(d, { pane: undefined })
+ expect(await showCommand([], h.deps)).toBe(EXIT.usage)
+ expect(h.err[0]).toBe('Name the harness to show.')
+ expect(await showCommand(['a', 'b'], h.deps)).toBe(EXIT.usage)
+ expect(await showCommand(['a', '--chars', 'x'], h.deps)).toBe(EXIT.usage)
+ expect(await showCommand(['a', '--chars'], h.deps)).toBe(EXIT.usage)
+ expect(h.err).toContain('--chars needs a value.')
+ expect(await showCommand(['review'], h.deps)).toBe(EXIT.failed)
+ expect(h.err.at(-1)).toBe('"review" could be review-a (review-a, idle), review-b (review-b, idle). Use more of the name, or the id.')
+ expect(await showCommand(['solo'], h.deps)).toBe(EXIT.failed)
+ expect(await showCommand(['nobody'], h.deps)).toBe(EXIT.failed)
+ expect(h.err.at(-1)).toBe('No harness named "nobody" on this machine. `harness ps` lists them.')
+ })
+
+ it('prefers a live harness over a stopped one of the same name', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('old', { name: 'fixer', status: 'stopped' }), frame('new', { name: 'fixer' })]
+ const h = harness(d, { pane: undefined })
+ expect(await showCommand(['fixer', '--json'], h.deps)).toBe(EXIT.ok)
+ expect(JSON.parse(h.out.join('\n')).id).toBe('new')
+ })
+
+ it('finds a harness the caller started by the name it was started with, after its engine retitled it', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead'), frame('kid', { name: 'Fix the login test' })]
+ const h = harness(d)
+ started(h.ledger, 'lead', 'kid')
+ h.ledger.append({ ...h.ledger.all()[0], child: { machineId: 'm', agentId: 'kid', name: 'Claude harness 10-11 8:38' } })
+ expect(await showCommand(['Claude harness 10-11 8:38', '--json'], h.deps)).toBe(EXIT.ok)
+ expect(JSON.parse(h.out.join('\n'))).toMatchObject({ id: 'kid', name: 'Fix the login test', startedBy: 'you' })
+ })
+
+ it('finds a harness the caller started on another machine', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead')]
+ const mini = new FakeDaemon('mini')
+ mini.frames = [frame('gpu-job')]
+ const h = harness(d, { others: { mini } })
+ started(h.ledger, 'lead', 'gpu-job', 'mini')
+ expect(await showCommand(['gpu', '--json'], h.deps)).toBe(EXIT.ok)
+ expect(JSON.parse(h.out.join('\n'))).toMatchObject({ name: 'gpu-job', machine: 'mini', startedBy: 'you' })
+ expect(mini.closed).toBe(true)
+ mini.frames = []
+ const gone = harness(d, { others: { mini } })
+ expect(await showCommand(['gpu-job'], gone.deps)).toBe(EXIT.failed)
+ expect(gone.err[0]).toBe('gpu-job is no longer on its machine.')
+ })
+})
+
+describe('harness wait', () => {
+ const inspects = (d: FakeDaemon) => d.requests.filter((r) => r.type === 'agent_close').length
+ const answered = (d: FakeDaemon, id: string) => d.pages.set(`s-${id}`, [{ events: [ev('user_message', { content: 'x' }), ev('text_delta', { content: 'Done.' }), ev('done')], hasMore: false }])
+
+ it('waits while it works, then says it is idle once it stays idle', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead'), frame('kid')]
+ d.screens.set('kid', ['working', 'working', 'idle'])
+ const h = harness(d)
+ expect(await waitCommand(['kid'], h.deps)).toBe(EXIT.ok)
+ expect(h.out).toEqual(['kid: idle · read it: harness show kid'])
+ expect(inspects(d)).toBe(4)
+ expect(d.requests.filter((r) => r.type === 'agent_close').every((r) => r.payload.mode === 'inspect')).toBe(true)
+ })
+
+ it('reads no screen while the daemon says it is working', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('kid', { activity: { state: 'working' } })]
+ let looks = 0
+ d.extra.agents_list = () => ({ agents: [looks++ < 3 ? d.frames[0] : { ...d.frames[0], activity: { state: 'idle' } }] })
+ const h = harness(d)
+ expect(await waitCommand(['kid'], h.deps)).toBe(EXIT.ok)
+ expect(inspects(d)).toBe(2)
+ })
+
+ it('returns, after a second look, for a harness that has already answered', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('done')]
+ 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(inspects(d)).toBe(2)
+ })
+
+ it('does not return on the turn before a message it was just sent', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('kid')]
+ answered(d, 'kid')
+ // Idle on the old turn, then the message is in its box, then it works on it, then it answers it.
+ d.screens.set('kid', ['idle', 'draft', 'working', 'idle'])
+ const h = harness(d)
+ expect(await waitCommand(['kid'], h.deps)).toBe(EXIT.ok)
+ expect(inspects(d)).toBe(5)
+ })
+
+ it('does not take a harness that has not begun its task for one that finished', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('new', { createdAt: new Date(NOW - 5_000).toISOString(), sessionId: '' })]
+ d.screens.set('new', ['idle', 'idle', 'working', 'idle'])
+ const h = harness(d)
+ expect(await waitCommand(['new'], h.deps)).toBe(EXIT.ok)
+ expect(inspects(d)).toBe(5)
+ })
+
+ it('waits on an idle harness whose last turn has no answer yet, until it has one', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('k')]
+ d.pages.set('s-k', [{ events: [ev('user_message', { content: 'x' }), ev('tool_start'), ev('done')], hasMore: false }])
+ const h = harness(d)
+ expect(await waitCommand(['k', '--timeout', '10s'], h.deps)).toBe(EXIT.timeout)
+ })
+
+ it('gives up on a harness with nothing asked of it, once it is past starting', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('blank', { createdAt: '2026-10-11T09:00:00Z' })]
+ const h = harness(d)
+ expect(await waitCommand(['blank'], h.deps)).toBe(EXIT.ok)
+ expect(inspects(d)).toBe(3)
+ // Without a start time it is taken as old.
+ const e = new FakeDaemon()
+ e.frames = [frame('blank', { createdAt: undefined })]
+ expect(await waitCommand(['blank'], harness(e).deps)).toBe(EXIT.ok)
+ })
+
+ it('stops for the person, a stop, a harness that went, or the clock', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('asks'), frame('busy')]
+ d.screens.set('asks', ['needs_input'])
+ 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/)
+ 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')
+ const s = new FakeDaemon()
+ s.frames = [frame('x')]
+ s.screens.set('x', ['working'])
+ let n = 0
+ s.extra.agents_list = () => ({ agents: n++ < 2 ? s.frames : [{ ...s.frames[0], status: 'stopped' }] })
+ const st = harness(s)
+ expect(await waitCommand(['x'], st.deps)).toBe(EXIT.stopped)
+ expect(st.out[0]).toBe('x: stopped · it was stopped')
+ 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[0]).toBe('x: gone · it is gone')
+ })
+
+ it('waits for all of several, listing once a round, or the first with --any; a name twice is one harness', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('a'), frame('b')]
+ d.screens.set('a', ['working', 'idle'])
+ d.screens.set('b', ['working', 'working', 'working', 'idle'])
+ const all = harness(d)
+ expect(await waitCommand(['a,b', 'a'], all.deps)).toBe(EXIT.ok)
+ expect(all.out).toEqual(['a: idle · read it: harness show a', 'b: idle · read it: harness show b'])
+ const lists = d.requests.filter((r) => r.type === 'agents_list').length
+ // The first list names them; then one a round, five rounds.
+ expect(lists).toBe(6)
+ d.screens.set('a', ['working', 'idle'])
+ d.screens.set('b', ['working'])
+ const any = harness(d)
+ expect(await waitCommand(['a,b', '--any'], any.deps)).toBe(EXIT.ok)
+ expect(any.out).toEqual(['a: idle · read it: harness show a'])
+ })
+
+ it('keeps waiting through a slow answer and a screen it cannot read', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('k')]
+ let looks = 0
+ d.extra.agent_close = () => {
+ looks++
+ if (looks === 1) throw new AgentClientError('TIMEOUT', 'slow')
+ if (looks === 2) return { activity: 'unknown' }
+ return looks === 3 ? { activity: 'working' } : { activity: 'idle' }
+ }
+ let lists = 0
+ d.extra.agents_list = () => {
+ // The daemon's own word is unknown while the screen cannot be read; then idle.
+ lists++
+ return { agents: [{ ...d.frames[0], activity: lists < 4 ? null : { state: 'idle' } }] }
+ }
+ const h = harness(d)
+ expect(await waitCommand(['k', '--timeout', '0'], h.deps)).toBe(EXIT.ok)
+ expect(looks).toBe(5)
+ })
+
+ it('passes on a failure it cannot wait through, and waits through a list that timed out', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('k')]
+ let n = 0
+ d.extra.agents_list = () => {
+ n++
+ if (n === 2) throw new AgentClientError('TIMEOUT', 'slow')
+ if (n === 3) throw new AgentClientError('DISCONNECTED', 'The connection to Harness closed.')
+ return { agents: d.frames }
+ }
+ const h = harness(d)
+ expect(await waitCommand(['k'], h.deps)).toBe(EXIT.failed)
+ expect(h.err).toEqual(['The connection to Harness closed.'])
+ })
+
+ it('refuses no name and a time it cannot read', async () => {
+ const h = harness(new FakeDaemon())
+ expect(await waitCommand([], h.deps)).toBe(EXIT.usage)
+ expect(await waitCommand([','], h.deps)).toBe(EXIT.usage)
+ expect(await waitCommand(['a', '--timeout', 'soon'], h.deps)).toBe(EXIT.usage)
+ expect(h.err).toContain('"soon" is not a time: use 90s, 30m or 2h.')
+ expect(parseDuration('90s')).toBe(90_000)
+ expect(parseDuration('30')).toBe(1_800_000)
+ expect(parseDuration('2h')).toBe(7_200_000)
+ })
+
+ it('waits on a harness the caller started on another machine', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead')]
+ const mini = new FakeDaemon('mini')
+ mini.frames = [frame('far')]
+ mini.screens.set('far', ['working', 'idle'])
+ const h = harness(d, { others: { mini } })
+ started(h.ledger, 'lead', 'far', 'mini')
+ expect(await waitCommand(['far'], h.deps)).toBe(EXIT.ok)
+ expect(mini.closed).toBe(true)
+ })
+})
+
+describe('harness close', () => {
+ it('closes a harness the agent started, once it is idle', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead'), frame('kid')]
+ 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(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(d.requests.at(-1)?.payload.mode).toBe('now')
+ })
+
+ 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(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(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(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(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' })]
+ expect(await closeCommand(['theirs'], harness(d, { pane: '%sh', where: () => ({ ...where, harnessPane: true }) }).deps)).toBe(EXIT.ok)
+ expect(await closeCommand(['theirs'], harness(d, { pane: '%own' }).deps)).toBe(EXIT.ok)
+ })
+
+ it('says what to do when it is working or changed, and passes on any other refusal', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('k')]
+ const replies: Array<Record<string, unknown>> = [
+ { error: 'SESSION_NOT_IDLE', activity: 'working' }, { error: 'SESSION_NOT_IDLE', activity: 'needs_input' },
+ { error: 'AGENT_CHANGED' }, { error: 'CLOSE_FAILED', detail: 'disk full' }, { error: 'CLOSE_FAILED' },
+ ]
+ d.extra.agent_close = () => replies.shift()!
+ const h = harness(d, { pane: undefined })
+ for (let i = 0; i < 5; i++) expect(await closeCommand(['k'], h.deps)).toBe(EXIT.failed)
+ expect(h.err).toEqual([
+ 'k is working. Wait for it (harness wait k), or close it anyway with --now.',
+ 'k is waiting for the person. Wait for it (harness wait k), or close it anyway with --now.',
+ 'k changed while closing. Check it with harness show k, then try again.',
+ 'disk full',
+ 'Could not close k.',
+ ])
+ })
+
+ it('closes one harness at a time, by name', async () => {
+ const h = harness(new FakeDaemon())
+ expect(await closeCommand([], h.deps)).toBe(EXIT.usage)
+ expect(await closeCommand(['a', 'b'], h.deps)).toBe(EXIT.usage)
+ expect(h.err).toContain('Close one harness at a time.')
+ })
+})
+
+describe('harness new, run by an agent', () => {
+ it('is nothing outside a harness pane or in a person\'s terminal; refuses when it cannot tell who is calling', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('sh', { engine: 'terminal', tmuxPane: '%9', status: 'offline' })]
+ expect(await agentOrigin(harness(d, { pane: undefined }).deps)).toBeNull()
+ // A person's terminal, in any state: the core marks every session inactive as it starts.
+ expect(await agentOrigin(harness(d, { pane: '%9', where: () => ({ ...where, harnessPane: true }) }).deps)).toBeNull()
+ // The daemon did not answer: outside Harness, the person; in a pane Harness made, refused.
+ const down = async () => { throw new Error('down') }
+ expect(await agentOrigin(harness(d, { open: down }).deps)).toBeNull()
+ const unknown = (await agentOrigin(harness(d, { open: down, where: () => ({ ...where, harnessPane: true }) }).deps))!
+ await expect(unknown.check()).rejects.toThrow(/could not tell which harness/)
+ })
+
+ it('refuses from what is left of an agent whose harness is gone', async () => {
+ const origin = (await agentOrigin(harness(new FakeDaemon(), { pane: '%gone', where: () => ({ ...where, harnessPane: true }) }).deps))!
+ 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('')
+ })
+
+ it('heads the task with who sent it, records what it started, and says how to follow it', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead', { engine: 'claude' })]
+ const h = harness(d)
+ const origin = (await agentOrigin(h.deps))!
+ expect(d.closed).toBe(true)
+ await expect(origin.check()).resolves.toBeUndefined()
+ expect(origin.prompt('review it', 'm')).toBe('[from lead · Claude Code · studio, the harness that started you. It reads your answer itself; to ask it something while you work: harness send lead "…"]\n\nreview it')
+ expect(origin.prompt('train it', 'mini')).toBe('[from lead · Claude Code · studio, the harness that started you. It reads your answer itself.]\n\ntrain it')
+ // A task longer than a first message holds: the whole of it in a file, its start in the message.
+ const long = `Review all of it. ${'x'.repeat(3_000)}`
+ const sent = origin.prompt(long, 'm')
+ expect(sent.length).toBeLessThanOrEqual(2_000)
+ const file = /All of it is in (\S+): read the whole file/.exec(sent)![1]
+ expect(readFileSync(file, 'utf8')).toBe(long)
+ expect(sent).toContain('It begins:\n\nReview all of it. xxx')
+ expect(() => origin.prompt(long, 'mini')).toThrow(/another machine holds at most/)
+ expect(await origin.created('m', { id: 'kid', name: 'reviewer' })).toBeNull()
+ expect(await origin.created('m', { name: 'no id' })).toBeNull()
+ 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 · message it: harness send 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" ·')
+ 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')
+ })
+
+ it('keeps the record on the other machine too, and says when that machine could not keep it', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead', { engine: 'claude' })]
+ const h = harness(d)
+ const asked: Array<[string, Record<string, unknown>]> = []
+ const origin = (await agentOrigin(h.deps, async (target, payload) => { asked.push([target.machineId, payload]); return { recorded: true } }))!
+ expect(await origin.created('mini', { id: 'far', name: 'gpu-job' })).toBeNull()
+ expect(asked).toEqual([['mini', { action: 'started', row: expect.objectContaining({ depth: 1, child: { machineId: 'mini', agentId: 'far', name: 'gpu-job' } }) }]])
+ const old = (await agentOrigin(h.deps, async () => { throw new Error('UNKNOWN_ACTION') }))!
+ expect(await old.created('mini', { id: 'far2', name: '' })).toBe('The harness runs on a machine whose Harness did not record who started it: there, its limits start from zero.')
+ expect(h.ledger.childrenOf({ machineId: 'm', agentId: 'lead' }).map((r) => r.child.agentId)).toEqual(['far', 'far2'])
+ })
+
+ it('refuses past the limits: depth, live harnesses per harness and per machine, and starts in ten minutes', () => {
+ const l = new Ledger(ledgerPath(dir))
+ const lead = { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }
+ const live = new Set(['m/lead'])
+ expect(spawnRefusal(lead, live, l, 'm', NOW)).toBeNull()
+ l.append({ at: NOW, depth: SPAWN_LIMITS.depth, by: { ...lead, agentId: 'up' }, child: { machineId: 'm', agentId: 'deep', name: 'deep' } })
+ expect(spawnRefusal({ ...lead, agentId: 'deep' }, live, l, 'm', NOW)).toMatch(/this far down/)
+ for (let i = 0; i < SPAWN_LIMITS.livePerHarness - 1; i++) {
+ started(l, 'lead', `k${i}`, 'm', NOW - 3_600_000)
+ live.add(`m/k${i}`)
+ }
+ started(l, 'lead', 'far', 'mini', NOW - 3_600_000)
+ expect(spawnRefusal(lead, live, l, 'm', NOW)).toBeNull()
+ live.add('mini/far')
+ expect(spawnRefusal(lead, live, l, 'm', NOW)).toBe('You have 8 harnesses running. Close one you are done with first (harness close <name>).')
+ const crowd = new Ledger(ledgerPath(mkdtempSync(join(dir, 'crowd-'))))
+ const busy = new Set<string>()
+ for (let i = 0; i < SPAWN_LIMITS.livePerMachine; i++) {
+ crowd.append({ at: 0, depth: 1, by: { ...lead, agentId: `p${i}` }, child: { machineId: 'm', agentId: `c${i}`, name: `c${i}` } })
+ busy.add(`m/c${i}`)
+ }
+ expect(spawnRefusal(lead, busy, crowd, 'm', NOW)).toMatch(/^Agents have 40 harnesses running on this machine/)
+ const quick = new Ledger(ledgerPath(mkdtempSync(join(dir, 'quick-'))))
+ for (let i = 0; i < SPAWN_LIMITS.perWindow; i++) started(quick, 'lead', `q${i}`, 'm', NOW - 60_000)
+ expect(spawnRefusal(lead, new Set(), quick, 'm', NOW)).toBe('You started 20 harnesses in 10 minutes. Wait, or work with the ones you have.')
+ })
+
+ it('counts what it started on other machines as those machines say, and a day of them when one cannot be asked', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('lead')]
+ const mini = new FakeDaemon('mini')
+ // Seven closed on mini: they free their places.
+ mini.frames = [frame('alive'), ...Array.from({ length: 7 }, (_, i) => frame(`gone${i}`, { status: 'stopped' }))]
+ const h = harness(d, { others: { mini } })
+ started(h.ledger, 'lead', 'alive', 'mini')
+ for (let i = 0; i < 7; i++) started(h.ledger, 'lead', `gone${i}`, 'mini')
+ await expect((await agentOrigin(h.deps))!.check()).resolves.toBeUndefined()
+ expect(mini.closed).toBe(true)
+ // An old one is not asked about.
+ started(h.ledger, 'lead', 'ancient', 'away', NOW - 8 * 24 * 3_600_000)
+ // A machine that cannot be asked: its last day's starts count.
+ for (let i = 0; i < 8; i++) started(h.ledger, 'lead', `x${i}`, 'offline', NOW - 3_600_000)
+ await expect((await agentOrigin(h.deps))!.check()).rejects.toThrow(/You have 9 harnesses running/)
+ const later = harness(d, { others: { mini }, now: () => NOW + 2 * 86_400_000 })
+ await expect((await agentOrigin(later.deps))!.check()).resolves.toBeUndefined()
+ const odd = new FakeDaemon('mini')
+ odd.extra.agents_list = () => ({ agents: 'nope' })
+ await expect((await agentOrigin(harness(d, { others: { mini: odd } }).deps))!.check()).rejects.toThrow(/You have 8 harnesses running/)
+ })
+})
diff --git a/cli/src/agentClient/commands.ts b/cli/src/agentClient/commands.ts
new file mode 100644
index 000000000..d89affe0e
--- /dev/null
+++ b/cli/src/agentClient/commands.ts
@@ -0,0 +1,600 @@
+/**
+ * Harness for agents (docs/design/2026-10-11-agent-client.md): the verbs an agent runs from its own pane to see,
+ * read, wait for and close other harnesses. `harness new` and `harness send` are the other two; this file gives
+ * `new` what it needs when an agent runs it (`agentOrigin`).
+ *
+ * harness ps [--all] [--json]
+ * harness show <name> [--chars N] [--json]
+ * harness wait <name>[,<name>…] [--any] [--timeout 30m] [--json]
+ * harness close <name> [--now] [--json]
+ *
+ * Text by default, because agents read it as well as people do and it costs them a fraction of the tokens;
+ * `--json` for programs. Everything is composed from requests the daemon already answers: `agents_list`,
+ * `agent_recent`, a bounded `session_get` page, and `agent_close` (its `inspect` mode tells needs-input from idle).
+ */
+import { randomBytes } from 'node:crypto'
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { hostname } from 'node:os'
+import { join } from 'node:path'
+import { MAX_FIRST_PROMPT_CHARS } from '../lib/engineLaunch.js'
+import type { NewOrigin } from '../lib/newCommand.js'
+import { engineName } from '../messages/model.js'
+import { AgentClientError, openDaemon, whereFor, type Daemon, type Where } from './daemon.js'
+import { Ledger, ledgerPath, type Started } from './ledger.js'
+import { messagesRpc, type Rpc } from '../messages/rpc.js'
+import { callerOf, clip, isAgent, lastTurn, matching, rowsOf, stateOf, STOPPED_WITHIN_MS, type Caller, type Frame, type HistoryEvent, type Row, type State } from './model.js'
+
+export interface ClientDeps {
+ pane?: string | undefined
+ where?: () => Where
+ open?: (where: Where, machineId?: string) => Promise<Daemon>
+ ledger?: (dataDir: string) => Ledger
+ out?: (line: string) => void
+ err?: (line: string) => void
+ now?: () => number
+ sleep?: (ms: number) => Promise<void>
+ /** How often `wait` looks. */
+ intervalMs?: number
+}
+
+export const PS_USAGE = `Usage: harness ps [--all] [--json]
+
+The harnesses on this machine: name, agent, state, who started it, when it was last active, and what it is about.
+--all adds the ones stopped in the last week.`
+export const SHOW_USAGE = `Usage: harness show <name> [--chars N] [--json]
+
+A harness's state and its last turn: what it was asked and what it answered (the first N characters, 4000 by default).`
+export const WAIT_USAGE = `Usage: harness wait <name>[,<name>…] [--any] [--timeout 30m] [--json]
+
+Waits until each harness has stopped working, then prints its state. --any returns when the first one does.
+Exit status: 0 idle, 3 one needs the person (a question or a permission), 4 one stopped or is gone, 124 timed out.
+--timeout takes 90s, 30m, 2h; 0 waits as long as it takes.`
+export const CLOSE_USAGE = `Usage: harness close <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.`
+
+export const EXIT = { ok: 0, failed: 1, usage: 2, needsInput: 3, stopped: 4, timeout: 124 } as const
+
+const DEFAULT_CHARS = 4_000
+const DEFAULT_TIMEOUT_MS = 30 * 60_000
+const DEFAULT_INTERVAL_MS = 3_000
+/** How many harnesses `ps` asks what they are about; the rest list without it. */
+const ABOUT_MAX = 40
+/** A harness that never worked while waited on, with nothing in its transcript: nothing to wait for. */
+const QUIET_LOOKS = 3
+/** How long a new harness may take to start and have its task typed (a Codex start with its trust prompt is the
+ * slowest seen). Before it, a harness that is not working may simply not have begun. */
+const STARTING_MS = 2 * 60_000
+
+class UsageError extends Error {}
+
+const ORPHAN = 'This pane\'s harness is no longer running, so nothing here may close or start harnesses. Only the person can.'
+
+interface Opened {
+ where: Where; daemon: Daemon; frames: Frame[]; caller: Caller | null; ledger: Ledger; machine: string
+ /** Run from a pane Harness made whose harness it no longer knows (closed, forgotten): what is left of an agent,
+ * a background job it started, say. Never the person: it may look, not close or start. */
+ orphan: boolean
+ /** `frames` holds the stopped harnesses too. */
+ stopped: boolean
+}
+
+function setup(deps: ClientDeps) {
+ return {
+ pane: 'pane' in deps ? deps.pane : process.env.TMUX_PANE,
+ where: deps.where ?? (() => whereFor('pane' in deps ? deps.pane : process.env.TMUX_PANE)),
+ open: deps.open ?? ((where: Where, machineId?: string) => openDaemon(where, machineId)),
+ ledger: deps.ledger ?? ((dataDir: string) => new Ledger(ledgerPath(dataDir))),
+ out: deps.out ?? ((line: string) => console.log(line)),
+ err: deps.err ?? ((line: string) => console.error(line)),
+ now: deps.now ?? Date.now,
+ sleep: deps.sleep ?? ((ms: number) => new Promise<void>((done) => setTimeout(done, ms))),
+ intervalMs: deps.intervalMs ?? DEFAULT_INTERVAL_MS,
+ }
+}
+type Setup = ReturnType<typeof setup>
+
+/** This machine's name as Harness shows it (`machine-name` in the data folder), else the host's. */
+export function machineNameOf(dataDir: string): string {
+ try {
+ const name = readFileSync(join(dataDir, 'machine-name'), 'utf8').trim()
+ if (name) return name
+ } catch { /* the host's name below */ }
+ return hostname().replace(/\.local$/, '')
+}
+
+async function list(daemon: Daemon, includeStopped: boolean): Promise<Frame[]> {
+ const reply = await daemon.request('agents_list', { includeStopped })
+ if (reply.error) throw new AgentClientError(String(reply.error), 'Harness could not list its harnesses. Try again.')
+ return Array.isArray(reply.agents) ? reply.agents as Frame[] : []
+}
+
+/**
+ * The line to the caller's daemon, its harnesses, who is calling, and the ledger. Live ones (and offline ones) only,
+ * unless asked: the list with every stopped harness took 128 ms against 10 ms on the owner's Mac (391 harnesses, 21
+ * live), and a stopped harness keeps no pane, so the caller is never one.
+ */
+async function opened(s: Setup, includeStopped = false): Promise<Opened> {
+ const where = s.where()
+ const daemon = await s.open(where)
+ try {
+ const frames = await list(daemon, includeStopped)
+ const caller = callerOf(frames, s.pane, where.machineId)
+ // Any status: the core marks every session inactive as it starts (core/main.ts), and a person's terminal is theirs
+ // through it. A stopped harness keeps no pane (`toStoppedProject`), so an old pane number never matches one.
+ const terminal = frames.some((f) => f.tmuxPane === s.pane && f.engine === 'terminal')
+ const orphan = !!s.pane && !!where.harnessPane && !caller && !terminal
+ return { where, daemon, frames, caller, orphan, stopped: includeStopped, ledger: s.ledger(where.dataDir), machine: machineNameOf(where.dataDir) }
+ } catch (error) { daemon.close(); throw error }
+}
+
+interface Target { daemon: Daemon; frame: Frame; machineId: string; machine: string; yours: boolean; remote: boolean }
+
+/**
+ * The harness [name] means: one on this machine, else one the caller started on another machine. A live harness
+ * is preferred over a stopped one of the same name.
+ */
+async function target(s: Setup, o: Opened, name: string): Promise<Target> {
+ const named = (frames: Frame[]) => frames.filter(isAgent).map((f) => ({ ...f, name: f.name || f.id.slice(0, 8) }))
+ const yoursOn = (machineId: string, agentId: string): boolean => {
+ const parent = o.ledger.parentOf({ machineId, agentId })
+ return !!o.caller && !!parent && parent.by.agentId === o.caller.agentId && parent.by.machineId === o.caller.machineId
+ }
+ let found = matching(name, named(o.frames))
+ // No live one by that name: the stopped ones too, read once.
+ if (!found.length && !o.stopped) {
+ o.frames = await list(o.daemon, true)
+ o.stopped = true
+ found = matching(name, named(o.frames))
+ }
+ if (found.some((f) => f.status !== 'stopped')) found = found.filter((f) => f.status !== 'stopped')
+ if (found.length === 1) {
+ const frame = found[0]
+ return { daemon: o.daemon, frame, machineId: o.where.machineId, machine: o.machine, yours: yoursOn(o.where.machineId, frame.id), remote: false }
+ }
+ if (found.length > 1) {
+ throw new AgentClientError('AMBIGUOUS', `"${name}" could be ${found.slice(0, 6).map((f) => `${f.name} (${f.id.slice(0, 8)}, ${stateOf(f)})`).join(', ')}. Use more of the name, or the id.`)
+ }
+ // One the caller started, by the name it was started with (an unnamed harness takes its session's title once it
+ // has one), here or on another machine.
+ const mine = o.caller ? o.ledger.childrenOf(o.caller) : []
+ const elsewhere = matching(name, mine.map((row) => ({ name: row.child.name || row.child.agentId.slice(0, 8), id: row.child.agentId, row })))
+ const here = elsewhere.length === 1 && elsewhere[0].row.child.machineId === o.where.machineId
+ ? named(o.frames).find((f) => f.id === elsewhere[0].row.child.agentId) : undefined
+ if (here) return { daemon: o.daemon, frame: here, machineId: o.where.machineId, machine: o.machine, yours: true, remote: false }
+ if (elsewhere.length === 1 && elsewhere[0].row.child.machineId !== o.where.machineId) {
+ const { row } = elsewhere[0]
+ const daemon = await s.open(o.where, row.child.machineId)
+ const frame = named(await list(daemon, true)).find((f) => f.id === row.child.agentId)
+ if (!frame) { daemon.close(); throw new AgentClientError('GONE', `${elsewhere[0].name} is no longer on its machine.`) }
+ return { daemon, frame, machineId: row.child.machineId, machine: row.child.machineId.slice(0, 8), yours: true, remote: true }
+ }
+ throw new AgentClientError('UNKNOWN_HARNESS', `No harness named "${name}" on this machine. \`harness ps\` lists them.`)
+}
+
+type Screen = 'working' | 'needs-input' | 'idle' | 'draft'
+
+/** What the screen says now (the windows' read, `agent_close` `inspect`); null when it cannot be read. `draft`:
+ * text waits in its box, the person's or a message being typed, so the agent is about to work. */
+async function inspect(t: { daemon: Daemon; frame: Frame }): Promise<Screen | null> {
+ const reply = await t.daemon.request('agent_close', {
+ agentId: t.frame.id, sessionId: t.frame.sessionId ?? '', createdAt: t.frame.createdAt ?? '', mode: 'inspect',
+ }).catch(() => ({} as Record<string, unknown>))
+ switch (reply.activity) {
+ case 'working': return 'working'
+ case 'needs_input': return 'needs-input'
+ case 'idle': return 'idle'
+ case 'draft': return 'draft'
+ default: return null
+ }
+}
+
+/** The last turn, from the end of the transcript, a page at a time: never the whole file (the attach OOM). */
+async function readLastTurn(t: { daemon: Daemon; frame: Frame }, pages = 4) {
+ if (!t.frame.sessionId) return null
+ let before: string | undefined
+ let events: HistoryEvent[] = []
+ for (let i = 0; i < pages; i++) {
+ const page = await t.daemon.request('session_get', { sessionId: t.frame.sessionId, limit: 80, ...(before ? { before } : {}) })
+ if (page.error) return null
+ events = [...(Array.isArray(page.events) ? page.events as HistoryEvent[] : []), ...events]
+ const turn = lastTurn(events)
+ if (turn || page.hasMore !== true || typeof page.oldestCursor !== 'string') return turn
+ before = page.oldestCursor
+ }
+ return lastTurn(events)
+}
+
+function words(argv: readonly string[], known: Record<string, 'flag' | 'value'>): { names: string[]; flags: Map<string, string | true> } {
+ const names: string[] = [], flags = new Map<string, string | true>()
+ for (let i = 0; i < argv.length; i++) {
+ const word = argv[i]
+ if (word === '--help' || word === '-h') throw new UsageError('')
+ if (word.startsWith('--')) {
+ const [key, inline] = word.split('=', 2)
+ const kind = known[key]
+ if (!kind) throw new UsageError(`Unknown option ${key}.`)
+ if (kind === 'flag') flags.set(key, true)
+ else {
+ const value = inline ?? argv[++i]
+ if (value === undefined) throw new UsageError(`${key} needs a value.`)
+ flags.set(key, value)
+ }
+ } else names.push(word)
+ }
+ return { names, flags }
+}
+
+export function parseDuration(value: string): number {
+ const m = /^(\d+)(s|m|h)?$/.exec(value.trim())
+ if (!m) throw new UsageError(`"${value}" is not a time: use 90s, 30m or 2h.`)
+ return Number(m[1]) * (m[2] === 'h' ? 3_600_000 : m[2] === 's' ? 1_000 : 60_000)
+}
+
+const ago = (iso: string | null, now: number): string => {
+ if (!iso) return '-'
+ const s = Math.max(0, Math.round((now - Date.parse(iso)) / 1000))
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : s < 86_400 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86_400)}d`
+}
+
+const home = process.env.HOME ?? ''
+const tilde = (path: string | null): string => (!path ? '-' : home && path.startsWith(home) ? `~${path.slice(home.length)}` : path)
+
+async function run(usage: string, deps: ClientDeps, json: (argv: readonly string[]) => boolean, argv: readonly string[],
+ body: (s: Setup) => Promise<number>): Promise<number> {
+ const s = setup(deps)
+ try { return await body(s) } catch (error) {
+ if (error instanceof UsageError) {
+ if (error.message) s.err(error.message)
+ ;(error.message ? s.err : s.out)(usage)
+ return error.message ? EXIT.usage : EXIT.ok
+ }
+ 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 wantsJson = (argv: readonly string[]): boolean => argv.includes('--json')
+
+// ── ps ─────────────────────────────────────────────────────────────────────────────────────────────
+
+export function formatRows(rows: Row[], caller: Caller | null, now: number): string {
+ if (!rows.length) return 'No harnesses on this machine.'
+ const width = Math.min(32, Math.max(4, ...rows.map((r) => r.name.length)))
+ const head = `${'NAME'.padEnd(width)} ${'AGENT'.padEnd(11)} ${'STATE'.padEnd(11)} ${'STARTED BY'.padEnd(12)} ${'ACTIVE'.padEnd(6)} FOLDER`
+ const lines = rows.map((r) => {
+ const name = clip(r.name, width).padEnd(width)
+ const line = `${name} ${clip(r.agent, 11).padEnd(11)} ${r.state.padEnd(11)} ${clip(r.self ? `${r.startedBy} (you)` : r.startedBy, 12).padEnd(12)} ${ago(r.lastActive, now).padEnd(6)} ${tilde(r.folder)}${r.branch ? ` (${r.branch})` : ''}`
+ const about = r.about ?? (r.asks?.length ? `asked: ${r.asks[0]}` : '')
+ return about ? `${line}\n${' '.repeat(2)}${clip(about.replace(/\s+/g, ' '), 200)}` : line
+ })
+ return [caller ? `You are "${caller.name}" (${caller.agentId.slice(0, 8)}).` : null, head, ...lines].filter((l) => l !== null).join('\n')
+}
+
+export function psCommand(argv: readonly string[], deps: ClientDeps = {}): Promise<number> {
+ return run(PS_USAGE, deps, wantsJson, argv, async (s) => {
+ const { names, flags } = words(argv, { '--all': 'flag', '--json': 'flag' })
+ if (names.length) throw new UsageError(`harness ps takes no names. To read one: harness show ${names[0]}`)
+ const o = await opened(s, flags.has('--all'))
+ try {
+ const rows = rowsOf(o.frames, { machineId: o.where.machineId, machine: o.machine, caller: o.caller, ledger: o.ledger, now: s.now(), all: flags.has('--all') })
+ // What each is about: the summaries the daemon keeps (no transcript read), for the live ones.
+ await Promise.all(rows.filter((r) => r.state !== 'stopped').slice(0, ABOUT_MAX).map(async (row) => {
+ const recent = await o.daemon.request('agent_recent', { agentId: row.id, n: 3 }, 3_000).catch(() => null)
+ if (!recent || recent.error) return
+ const asks = (Array.isArray(recent.asks) ? recent.asks as unknown[] : []).filter((a): a is string => typeof a === 'string' && !!a.trim()).slice(0, 2)
+ const about = (Array.isArray(recent.events) ? recent.events as Array<Record<string, unknown>> : [])
+ .map((e) => (typeof e.recap === 'string' && e.recap ? e.recap : typeof e.text === 'string' ? e.text : '').replace(/\s+/g, ' ').trim())
+ .filter(Boolean).slice(0, 3).map((t) => clip(t, 140))
+ if (asks.length) row.asks = asks.map((a) => clip(a.replace(/\s+/g, ' ').trim(), 200))
+ if (about.length) row.about = about.join(' / ')
+ }))
+ s.out(flags.has('--json') ? JSON.stringify({ you: o.caller ? o.caller.name : null, machine: o.machine, harnesses: rows }, null, 1) : formatRows(rows, o.caller, s.now()))
+ return EXIT.ok
+ } finally { o.daemon.close() }
+ })
+}
+
+// ── show ───────────────────────────────────────────────────────────────────────────────────────────
+
+export function showCommand(argv: readonly string[], deps: ClientDeps = {}): Promise<number> {
+ return run(SHOW_USAGE, deps, wantsJson, argv, async (s) => {
+ const { names, flags } = words(argv, { '--chars': 'value', '--json': 'flag' })
+ if (names.length !== 1) throw new UsageError(names.length ? 'Name one harness.' : 'Name the harness to show.')
+ const chars = flags.has('--chars') ? Number(flags.get('--chars')) : DEFAULT_CHARS
+ if (!Number.isInteger(chars) || chars < 1) throw new UsageError('--chars takes a whole number.')
+ const o = await opened(s)
+ let t: Target | null = null
+ try {
+ t = await target(s, o, names[0])
+ const listed = stateOf(t.frame)
+ const screen = listed === 'stopped' || listed === 'offline' ? null : await inspect(t)
+ const state: State = screen === 'draft' ? 'idle' : screen ?? listed
+ const turn = await readLastTurn(t)
+ const 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 ?? ''
+ 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,
+ }
+ 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(`folder: ${tilde(result.folder)}${result.branch ? ` (${result.branch})` : ''}`)
+ if (!turn) s.out('No turn yet.')
+ else {
+ s.out(`asked: ${clip(result.ask ?? '', 600)}`)
+ s.out(`answer${result.tools ? ` (after ${result.tools} tool calls)` : ''}:`)
+ s.out(result.answer || '(no text)')
+ if (result.truncated) s.out(`… ${answer.length - chars} more characters: harness show ${result.name} --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.`)
+ }
+ return EXIT.ok
+ } finally { if (t?.remote) t.daemon.close(); o.daemon.close() }
+ })
+}
+
+// ── wait ───────────────────────────────────────────────────────────────────────────────────────────
+
+type Settled = 'idle' | 'needs-input' | 'stopped' | 'gone' | 'timeout'
+
+export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Promise<number> {
+ return run(WAIT_USAGE, deps, wantsJson, argv, async (s) => {
+ const { names, flags } = words(argv, { '--any': 'flag', '--timeout': 'value', '--json': 'flag' })
+ const wanted = names.flatMap((n) => n.split(',')).map((n) => n.trim()).filter(Boolean)
+ if (!wanted.length) throw new UsageError('Name the harness to wait for.')
+ const timeoutMs = flags.has('--timeout') ? parseDuration(String(flags.get('--timeout'))) : DEFAULT_TIMEOUT_MS
+ const o = await opened(s)
+ const targets: Target[] = []
+ try {
+ for (const name of wanted) {
+ const t = await target(s, o, name)
+ if (!targets.some((x) => x.machineId === t.machineId && x.frame.id === t.frame.id)) targets.push(t)
+ }
+ const deadline = timeoutMs > 0 ? s.now() + timeoutMs : Infinity
+ const settled = new Map<Target, Settled>()
+ const sawWorking = new Set<Target>()
+ /** Idle looks in a row, on the same turn. */
+ const idle = new Map<Target, { turn: string; looks: number }>()
+ const look = async (t: Target, frames: Frame[]): Promise<Settled | null> => {
+ const frame = frames.find((f) => f.id === t.frame.id)
+ // Not live: stopped, or gone. Asked of the full list only then.
+ if (!frame) return (await list(t.daemon, true)).some((f) => f.id === t.frame.id) ? 'stopped' : 'gone'
+ t.frame = frame
+ if (frame.status === 'stopped') return 'stopped'
+ // The daemon says it is working: no need to read its screen.
+ const screen = frame.activity?.state === 'working' ? 'working' : await inspect(t)
+ if (screen === 'working') { sawWorking.add(t); idle.delete(t); return null }
+ if (screen === 'needs-input') return 'needs-input'
+ if (screen === 'draft' || (screen === null && stateOf(frame) !== 'idle')) { idle.delete(t); return null }
+ // Idle, on two looks in a row with the same last turn: a message sent just before is typed within a look,
+ // and the turn it starts shows as working. One idle look returned before it, on the turn before (#1180).
+ const turn = await readLastTurn(t, 1)
+ const key = turn ? `${turn.ask}\u0000${turn.tools}\u0000${turn.answer.length}` : ''
+ const before = idle.get(t)
+ const looks = before && before.turn === key ? before.looks + 1 : 1
+ idle.set(t, { turn: key, looks })
+ if (sawWorking.has(t)) return looks >= 2 ? 'idle' : null
+ if (turn) return looks >= 2 && turn.answered ? 'idle' : null
+ // Nothing asked of it at all, past its start: a harness started without a task has nothing to finish. A harness
+ // just started with a task is idle for a moment before the task is typed.
+ const age = frame.createdAt ? s.now() - Date.parse(frame.createdAt) : Infinity
+ return age > STARTING_MS && looks >= QUIET_LOOKS ? 'idle' : null
+ }
+ for (;;) {
+ // One list per machine a round, however many harnesses are waited on there.
+ const lists = new Map<Daemon, Promise<Frame[]>>()
+ for (const t of targets) {
+ if (settled.has(t)) continue
+ const result = await (async () => {
+ if (!lists.has(t.daemon)) lists.set(t.daemon, list(t.daemon, false))
+ return look(t, await lists.get(t.daemon)!)
+ })().catch((error) => {
+ if (error instanceof AgentClientError && error.code === 'TIMEOUT') return null
+ throw error
+ })
+ if (result) settled.set(t, result)
+ }
+ const done = flags.has('--any') ? settled.size > 0 : settled.size === targets.length
+ if (done) break
+ if (s.now() >= deadline) { for (const t of targets) if (!settled.has(t)) settled.set(t, 'timeout'); break }
+ await s.sleep(Math.min(s.intervalMs, Math.max(0, deadline - s.now())))
+ }
+ const results = targets.filter((t) => settled.has(t)).map((t) => ({ name: t.frame.name ?? t.frame.id.slice(0, 8), id: t.frame.id, state: settled.get(t)! }))
+ if (flags.has('--json')) s.out(JSON.stringify({ harnesses: results }, null, 1))
+ else for (const r of results) {
+ const next = r.state === 'idle' ? `read it: harness show ${r.name}`
+ : r.state === 'needs-input' ? 'it waits for the person (a question or a permission); only the person answers it'
+ : r.state === 'timeout' ? `still working; wait again or read it: harness show ${r.name}`
+ : r.state === 'stopped' ? 'it was stopped' : 'it is gone'
+ s.out(`${r.name}: ${r.state} · ${next}`)
+ }
+ const states = results.map((r) => r.state)
+ return states.includes('timeout') ? EXIT.timeout : states.includes('needs-input') ? EXIT.needsInput
+ : states.some((x) => x === 'stopped' || x === 'gone') ? EXIT.stopped : EXIT.ok
+ } finally {
+ for (const t of targets) if (t.remote) t.daemon.close()
+ o.daemon.close()
+ }
+ })
+}
+
+// ── close ──────────────────────────────────────────────────────────────────────────────────────────
+
+export function closeCommand(argv: readonly string[], deps: ClientDeps = {}): Promise<number> {
+ return run(CLOSE_USAGE, deps, wantsJson, argv, async (s) => {
+ const { names, flags } = words(argv, { '--now': 'flag', '--json': 'flag' })
+ if (names.length !== 1) throw new UsageError(names.length ? 'Close one harness at a time.' : 'Name the harness to close.')
+ const o = await opened(s)
+ let t: Target | null = null
+ try {
+ t = await target(s, o, names[0])
+ const name = t.frame.name ?? t.frame.id.slice(0, 8)
+ if (o.orphan) throw new AgentClientError('NOT_YOURS', ORPHAN)
+ if (o.caller && o.caller.agentId === t.frame.id && t.machineId === o.where.machineId) {
+ throw new AgentClientError('NOT_YOURS', 'That is your own harness. The person closes it.')
+ }
+ // An agent closes only what it started; the person, at a terminal, closes anything.
+ if (o.caller && !t.yours) throw new AgentClientError('NOT_YOURS', `You did not start ${name}, so you may not close it. Only the person can.`)
+ const reply = await t.daemon.request('agent_close', {
+ agentId: t.frame.id, sessionId: t.frame.sessionId ?? '', createdAt: t.frame.createdAt ?? '', mode: flags.has('--now') ? 'now' : 'idle',
+ }, 60_000)
+ if (reply.error === 'SESSION_NOT_IDLE') {
+ throw new AgentClientError('WORKING', `${name} is ${reply.activity === 'needs_input' ? 'waiting for the person' : 'working'}. Wait for it (harness wait ${name}), or close it anyway with --now.`)
+ }
+ if (reply.error === 'AGENT_CHANGED') throw new AgentClientError('AGENT_CHANGED', `${name} changed while closing. Check it with harness show ${name}, then try again.`)
+ if (reply.error) throw new AgentClientError(String(reply.error), typeof reply.detail === 'string' && reply.detail ? reply.detail : `Could not close ${name}.`)
+ s.out(flags.has('--json') ? JSON.stringify({ name, id: t.frame.id, closed: true }) : `Closed ${name}. Its conversation is kept.`)
+ return EXIT.ok
+ } finally { if (t?.remote) t.daemon.close(); o.daemon.close() }
+ })
+}
+
+// ── new, run by an agent ───────────────────────────────────────────────────────────────────────────
+
+/** Limits on starting harnesses (the design's "Limits"): runaway spawning is the risk. */
+export const SPAWN_LIMITS = { livePerHarness: 8, livePerMachine: 40, depth: 2, perWindow: 20, windowMs: 10 * 60_000 } as const
+
+/** A harness by machine and id, as the limits count the live ones. */
+const memberKey = (machineId: string, agentId: string): string => `${machineId}/${agentId}`
+
+/**
+ * Why [caller] may not start another harness now, or null. [live] holds the live harnesses the limits count: this
+ * machine's, and the caller's on the other machines it reached.
+ */
+export function spawnRefusal(caller: Caller, live: ReadonlySet<string>, ledger: Ledger, localMachineId: string, now: number): string | null {
+ if (ledger.depthOf(caller) >= SPAWN_LIMITS.depth) {
+ return 'A harness started this far down may not start more. Do the work yourself, or tell the harness that started you.'
+ }
+ const mine = ledger.childrenOf(caller)
+ const liveMine = new Set(mine.filter((row) => live.has(memberKey(row.child.machineId, row.child.agentId))).map((row) => memberKey(row.child.machineId, row.child.agentId)))
+ if (liveMine.size >= SPAWN_LIMITS.livePerHarness) {
+ return `You have ${liveMine.size} harnesses running. Close one you are done with first (harness close <name>).`
+ }
+ const machineWide = new Set(ledger.all().filter((row) => row.child.machineId === localMachineId && live.has(memberKey(localMachineId, row.child.agentId))).map((row) => row.child.agentId))
+ if (machineWide.size >= SPAWN_LIMITS.livePerMachine) {
+ return `Agents have ${machineWide.size} harnesses running on this machine, the most allowed. Close some first.`
+ }
+ if (mine.filter((row) => now - row.at < SPAWN_LIMITS.windowMs).length >= SPAWN_LIMITS.perWindow) {
+ return `You started ${SPAWN_LIMITS.perWindow} harnesses in 10 minutes. Wait, or work with the ones you have.`
+ }
+ return null
+}
+
+/** How long a harness started on another machine counts toward the limits when that machine cannot be asked. */
+const UNREACHABLE_LIVE_MS = 24 * 60 * 60_000
+
+/**
+ * The live harnesses the limits count: this machine's, and those the caller started on other machines, asked of
+ * each (a harness closed there frees its place: counted for a day whatever became of it, eight of them on another
+ * machine refused every start for that day, and `close` did not help; the review of #1180). A machine that cannot be
+ * asked has its last day's starts counted.
+ */
+async function liveFor(s: Setup, o: Opened, caller: Caller): Promise<Set<string>> {
+ const live = new Set(o.frames.filter((f) => f.status === 'active').map((f) => memberKey(o.where.machineId, f.id)))
+ const away = new Map<string, Started[]>()
+ for (const row of o.ledger.childrenOf(caller)) {
+ if (row.child.machineId === o.where.machineId || s.now() - row.at > STOPPED_WITHIN_MS) continue
+ away.set(row.child.machineId, [...(away.get(row.child.machineId) ?? []), row])
+ }
+ await Promise.all([...away].map(async ([machineId, rows]) => {
+ try {
+ const daemon = await s.open(o.where, machineId)
+ try {
+ const reply = await daemon.request('agents_list', {}, 8_000)
+ for (const f of Array.isArray(reply.agents) ? reply.agents as Frame[] : []) if (f.status === 'active') live.add(memberKey(machineId, f.id))
+ } finally { daemon.close() }
+ } catch {
+ for (const row of rows) if (s.now() - row.at < UNREACHABLE_LIVE_MS) live.add(memberKey(machineId, row.child.agentId))
+ }
+ }))
+ return live
+}
+
+/** How another harness names [caller] to `harness send`: its name when that is a plain word or two, else its id's
+ * start. An unnamed harness is called by its session title, which is a sentence ("so we have built harness web,")
+ * that a recipient list splits at the comma. */
+export function addressOf(caller: Caller): string {
+ return /^[\w.-]+( [\w.-]+)?$/.test(caller.name) && caller.name.length <= 40 ? (caller.name.includes(' ') ? `"${caller.name}"` : caller.name) : caller.agentId.slice(0, 8)
+}
+
+/** 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: () => '',
+})
+
+/**
+ * When an agent runs `harness new` from its pane: its limits, the header on its task, and the record of it. Null for
+ * the person. A pane Harness made whose harness cannot be told is refused, never taken for the person: a daemon that
+ * did not answer used to mean no limits, no header and no record (the review of #1180).
+ */
+export async function agentOrigin(deps: ClientDeps = {}, record: Rpc = messagesRpc): Promise<NewOrigin | null> {
+ const s = setup(deps)
+ if (!s.pane) return null
+ let o: Opened
+ try { o = await opened(s) } catch {
+ return s.where().harnessPane ? refusing('UNKNOWN_CALLER', 'Harness could not tell which harness is starting this. Try again in a moment.') : null
+ }
+ o.daemon.close()
+ if (o.orphan) return refusing('NOT_YOURS', ORPHAN)
+ const caller = o.caller
+ if (!caller) return null
+ return {
+ check: async () => {
+ const refusal = spawnRefusal(caller, await liveFor(s, o, caller), o.ledger, o.where.machineId, s.now())
+ if (refusal) throw new AgentClientError('SPAWN_LIMIT', refusal)
+ },
+ prompt: (text, machineId) => {
+ // Said once, at the top: the task is from an agent, not the person (the lamp team's tmux paste read as the
+ // owner's). The answer route works where the two share a machine (Agent Messages' lineage scope).
+ const here = machineId === o.where.machineId
+ // It reads the answer itself (`show`): an invitation to reply had the first eval's agent send its whole report
+ // back as a message as well, which would land in the middle of the starter's own turn.
+ const reply = here ? ` It reads your answer itself; to ask it something while you work: harness send ${addressOf(caller)} "…"` : ' It reads your answer itself.'
+ const header = `[from ${caller.name} · ${engineName(caller.engine)} · ${o.machine}, the harness that started you.${reply}]\n\n`
+ if (header.length + text.length <= MAX_FIRST_PROMPT_CHARS) return header + text
+ // A first message holds 2,000 characters (engineLaunch.ts), and a task an agent hands on is often longer: the
+ // first eval's prompts were refused whole. The task goes in a file the new harness is told to read.
+ if (!here) throw new AgentClientError('PROMPT_TOO_LONG', `A task for another machine holds at most ${MAX_FIRST_PROMPT_CHARS - header.length} characters. Shorten it.`)
+ const dir = join(o.where.dataDir, 'agent-client', 'tasks')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, `${new Date(s.now()).toISOString().slice(0, 10)}-${randomBytes(4).toString('hex')}.md`)
+ writeFileSync(file, text, { mode: 0o600 })
+ const lead = `Your task is longer than a first message holds. All of it is in ${file}: read the whole file before you start. It begins:\n\n`
+ const room = MAX_FIRST_PROMPT_CHARS - header.length - lead.length - 1
+ return `${header}${lead}${clip(text, room)}`
+ },
+ created: async (machineId, agent) => {
+ const id = typeof agent.id === 'string' ? agent.id : ''
+ if (!id) return null
+ const name = typeof agent.name === 'string' ? agent.name : ''
+ const row: Started = {
+ at: s.now(),
+ by: { machineId: caller.machineId, agentId: caller.agentId, name: caller.name, engine: caller.engine },
+ child: { machineId, agentId: id, name },
+ depth: o.ledger.depthOf(caller) + 1,
+ }
+ o.ledger.append(row)
+ if (machineId === o.where.machineId) return null
+ // The other machine keeps the line too: there the new harness's limits and depth start from it. Without it a
+ // harness started on another machine was one the person started there, and a chain hopping between machines had
+ // no depth at all (the review of #1180).
+ try {
+ await record({ port: o.where.port, dataDir: o.where.dataDir, machineId }, { action: 'started', row }, 10_000)
+ return null
+ } catch {
+ return `${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: harness show ${at} · wait for it: harness wait ${at} · message it: harness send ${at} "…"`
+ },
+ }
+}
diff --git a/cli/src/agentClient/daemon.ts b/cli/src/agentClient/daemon.ts
new file mode 100644
index 000000000..c212ef52c
--- /dev/null
+++ b/cli/src/agentClient/daemon.ts
@@ -0,0 +1,118 @@
+/**
+ * The agent verbs' line to a daemon (docs/design/2026-10-11-agent-client.md): the local socket of the daemon
+ * that owns the caller's pane, as `harness send` finds it, opened as a TOOL. A window's registration would turn
+ * on the question watcher and count as a person looking (backendSocket.ts `registerLocalClient`), and an agent
+ * polling every few seconds is not one. Another of the owner's machines is reached through the same socket over
+ * the paired relay (`machine_select` naming it).
+ */
+import { randomUUID } from 'node:crypto'
+import { existsSync, readFileSync } from 'node:fs'
+import { WebSocket } from 'ws'
+import { env } from '../config/env.js'
+import { readAuthSession } from '../lib/authSession.js'
+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) }
+}
+
+/** Which daemon: its port and data folder, and this machine's id as the daemon knows it. */
+export interface Where {
+ port: number
+ dataDir: string
+ machineId: string
+ /** The caller's pane is one a Harness daemon made (it carries the daemon's tag). */
+ harnessPane?: boolean
+}
+
+export interface Daemon {
+ /** The machine this line reaches. */
+ machineId: string
+ request(type: string, payload?: Record<string, unknown>, timeoutMs?: number): Promise<Record<string, unknown>>
+ close(): void
+}
+
+/** The least of a WebSocket this needs, so a test can hand in a fake. */
+export interface ClientSocket {
+ send(data: string): void
+ close(): void
+ on(event: 'open', listener: () => void): unknown
+ on(event: 'message', listener: (data: { toString(): string }, binary: boolean) => void): unknown
+ on(event: 'close', listener: (code: number) => void): unknown
+ on(event: 'error', listener: (error: Error) => void): unknown
+}
+
+export type Connect = (where: Where) => ClientSocket
+
+/** The daemon that made [pane], else the one this CLI's settings name. */
+export function whereFor(pane: string | undefined, owner: typeof paneOwner = paneOwner): Where {
+ const found = pane ? owner(pane) : null
+ let machineId = readAuthSession()?.machineId ?? env.ADAPTER_COMPUTER_ID ?? ''
+ if (!machineId) try { machineId = readFileSync(env.ADAPTER_COMPUTER_ID_FILE, 'utf8').trim() } catch { /* refused below */ }
+ return { port: found?.port ?? env.PORT, dataDir: found?.dataDir ?? env.ADAPTER_DATA_DIR, machineId, harnessPane: !!found }
+}
+
+/** The Unix socket when the daemon has one (file permissions are its lock), else loopback TCP. */
+export const connectSocket: Connect = (where) => {
+ const path = localSocketPath(where.dataDir, where.port)
+ return path && existsSync(path) ? new WebSocket(`ws+unix://${path}:/api/local-ws`) : new WebSocket(`ws://127.0.0.1:${where.port}/api/local-ws`)
+}
+
+export const DEFAULT_TIMEOUT_MS = 20_000
+
+/** Opens a line to [machineId] (this machine when left out) through [where]'s daemon. */
+export function openDaemon(where: Where, machineId: string = where.machineId, connect: Connect = connectSocket): Promise<Daemon> {
+ if (!where.machineId) return Promise.reject(new AgentClientError('NOT_SIGNED_IN', 'This computer has no Harness machine id yet. Run `harness login`.'))
+ return new Promise((resolveOpen, rejectOpen) => {
+ const socket = connect(where)
+ const waiting = new Map<string, { done: (payload: Record<string, unknown>) => void; fail: (error: Error) => void; timer: NodeJS.Timeout }>()
+ let ready = false, closed = false
+ const failAll = (error: AgentClientError): void => {
+ closed = true
+ for (const entry of waiting.values()) { clearTimeout(entry.timer); entry.fail(error) }
+ waiting.clear()
+ if (!ready) rejectOpen(error)
+ }
+ socket.on('error', () => failAll(new AgentClientError('DAEMON_UNREACHABLE', 'Harness is not running here. Start it with `harness start`.')))
+ socket.on('close', (code) => failAll(code === 4404
+ ? new AgentClientError('NO_PEER_LINK', 'That machine is not linked to this one. Run `harness link` first.')
+ : new AgentClientError('DISCONNECTED', 'The connection to Harness closed.')))
+ socket.on('open', () => socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1, tool: true } })))
+ socket.on('message', (raw, binary) => {
+ if (binary) return
+ let frame: { type?: string; payload?: Record<string, unknown> }
+ try { frame = JSON.parse(raw.toString()) } catch { return }
+ if (frame.type === 'machine_select_error') {
+ failAll(new AgentClientError(String(frame.payload?.error ?? 'MACHINE_UNAVAILABLE'), 'That machine is not reachable now. `harness machines` lists which are online.'))
+ socket.close()
+ return
+ }
+ if (!ready && frame.type === 'connected') {
+ ready = true
+ resolveOpen({
+ machineId,
+ close: () => { closed = true; socket.close() },
+ request: (type, payload = {}, timeoutMs = DEFAULT_TIMEOUT_MS) => new Promise((done, fail) => {
+ if (closed) { fail(new AgentClientError('DISCONNECTED', 'The connection to Harness closed.')); return }
+ const requestId = randomUUID()
+ const timer = setTimeout(() => {
+ waiting.delete(requestId)
+ fail(new AgentClientError('TIMEOUT', `Harness did not answer ${type} in time. Try again.`))
+ }, timeoutMs)
+ waiting.set(requestId, { done, fail, timer })
+ socket.send(JSON.stringify({ type, payload: { ...payload, requestId } }))
+ }),
+ })
+ return
+ }
+ const requestId = frame.payload?.requestId
+ const entry = typeof requestId === 'string' ? waiting.get(requestId) : undefined
+ if (!entry || !frame.payload) return
+ waiting.delete(requestId as string)
+ clearTimeout(entry.timer)
+ // A refusal is an answer: the caller reads `error` itself, as each request's codes mean different things.
+ entry.done(frame.payload)
+ })
+ })
+}
diff --git a/cli/src/agentClient/ledger.spec.ts b/cli/src/agentClient/ledger.spec.ts
new file mode 100644
index 000000000..8f6fb4635
--- /dev/null
+++ b/cli/src/agentClient/ledger.spec.ts
@@ -0,0 +1,74 @@
+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { Ledger, ledgerPath, parseStarted, ROTATE_BYTES, type Started } from './ledger.js'
+
+const dirs: string[] = []
+const fresh = (): Ledger => {
+ const dir = mkdtempSync(join(tmpdir(), 'ledger-'))
+ dirs.push(dir)
+ return new Ledger(ledgerPath(dir))
+}
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+
+const row = (by: string, child: string, depth = 1, at = 1): Started => ({
+ at, depth,
+ by: { machineId: 'm', agentId: by, name: by, engine: 'claude' },
+ child: { machineId: 'm', agentId: child, name: child },
+})
+
+describe('the ledger of who started which harness', () => {
+ it('reads nothing from a file that is not there', () => {
+ const ledger = fresh()
+ expect(ledger.all()).toEqual([])
+ expect(ledger.parentOf({ machineId: 'm', agentId: 'x' })).toBeNull()
+ expect(ledger.depthOf({ machineId: 'm', agentId: 'x' })).toBe(0)
+ })
+
+ it('answers parents, children, depth and links from what was appended', () => {
+ const ledger = fresh()
+ ledger.append(row('lead', 'a'))
+ ledger.append(row('lead', 'b'))
+ ledger.append(row('a', 'a1', 2))
+ expect(ledger.childrenOf({ machineId: 'm', agentId: 'lead' }).map((r) => r.child.agentId)).toEqual(['a', 'b'])
+ expect(ledger.parentOf({ machineId: 'm', agentId: 'a1' })?.by.agentId).toBe('a')
+ expect(ledger.depthOf({ machineId: 'm', agentId: 'a1' })).toBe(2)
+ expect(ledger.linked({ machineId: 'm', agentId: 'a' }, { machineId: 'm', agentId: 'lead' })).toBe(true)
+ expect(ledger.linked({ machineId: 'm', agentId: 'b' }, { machineId: 'm', agentId: 'a' })).toBe(false)
+ expect(ledger.links({ machineId: 'm', agentId: 'a' })).toEqual([{ machineId: 'm', agentId: 'lead' }, { machineId: 'm', agentId: 'a1' }])
+ // Another machine's harness with the same id is another harness.
+ expect(ledger.links({ machineId: 'other', agentId: 'a' })).toEqual([])
+ expect(statSync(ledger.path).mode & 0o777).toBe(0o600)
+ })
+
+ it('reads the file again only when it changed, and skips lines it cannot read', () => {
+ const ledger = fresh()
+ ledger.append(row('lead', 'a'))
+ const first = ledger.all()
+ expect(ledger.all()).toBe(first)
+ writeFileSync(ledger.path, `${readFileSync(ledger.path, 'utf8')}not json\n{"at":1}\n${JSON.stringify(row('lead', 'b'))}\n`)
+ expect(ledger.all().map((r) => r.child.agentId)).toEqual(['a', 'b'])
+ })
+
+ it('moves its lines aside past its size, and still reads them', () => {
+ const ledger = fresh()
+ ledger.append(row('lead', 'first'))
+ writeFileSync(ledger.path, `${JSON.stringify(row('lead', 'first'))}\n`.padEnd(ROTATE_BYTES + 1, ' ') + '\n')
+ ledger.append(row('lead', 'second'))
+ expect(existsSync(ledger.previous)).toBe(true)
+ expect(existsSync(ledger.path)).toBe(false)
+ ledger.append(row('lead', 'third'))
+ expect(ledger.all().map((r) => r.child.agentId)).toEqual(['first', 'second', 'third'])
+ })
+
+ it('checks every line it reads', () => {
+ expect(parseStarted('')).toBeNull()
+ expect(parseStarted('null')).toBeNull()
+ expect(parseStarted(JSON.stringify({ ...row('a', 'b'), depth: 0 }))).toBeNull()
+ expect(parseStarted(JSON.stringify({ ...row('a', 'b'), by: { machineId: 'm' } }))).toBeNull()
+ expect(parseStarted(JSON.stringify({ ...row('a', 'b'), child: { machineId: '', agentId: 'b' } }))).toBeNull()
+ const bare = { at: 1, depth: 1, by: { machineId: 'm', agentId: 'a' }, child: { machineId: 'm', agentId: 'b' } }
+ expect(parseStarted(JSON.stringify(bare))).toEqual({ at: 1, depth: 1, by: { machineId: 'm', agentId: 'a', name: '', engine: '' }, child: { machineId: 'm', agentId: 'b', name: '' } })
+ })
+})
diff --git a/cli/src/agentClient/ledger.ts b/cli/src/agentClient/ledger.ts
new file mode 100644
index 000000000..5fe0afa20
--- /dev/null
+++ b/cli/src/agentClient/ledger.ts
@@ -0,0 +1,113 @@
+/**
+ * Who started which harness (docs/design/2026-10-11-agent-client.md, "Who started it"): one line per harness an
+ * agent started with `harness new`, appended by the CLI to the data folder of the daemon that owns the agent's
+ * pane. A harness with no line was started by the person.
+ *
+ * Read by `harness ps` (who started each), by `new` and `stop` (limits, and which harnesses an agent may stop),
+ * and by Agent Messages, which lets a harness and the harnesses it started message each other without a tab.
+ * Like Agent Messages it is a collaboration scope, not a sandbox: any process of this user can write the file.
+ */
+import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+
+export interface LedgerMember { machineId: string; agentId: string }
+export interface Started {
+ at: number
+ /** The harness that ran `harness new`. */
+ by: LedgerMember & { name: string; engine: string }
+ /** The harness it started. */
+ child: LedgerMember & { name: string }
+ /** 1 for a harness a person's harness started, 2 for one that harness started. */
+ depth: number
+}
+
+/** The file, in the daemon's data folder. */
+export const ledgerPath = (dataDir: string): string => join(dataDir, 'agent-client', 'started.jsonl')
+
+/** The file's size before it becomes the previous one: the two hold about 20,000 starts. */
+export const ROTATE_BYTES = 2 * 1024 * 1024
+
+const member = (v: unknown): v is LedgerMember => {
+ const m = v as Record<string, unknown> | null
+ return !!m && typeof m.machineId === 'string' && !!m.machineId && typeof m.agentId === 'string' && !!m.agentId
+}
+
+export function parseStarted(line: string): Started | null {
+ let v: Record<string, unknown>
+ try { v = JSON.parse(line) } catch { return null }
+ if (!v || typeof v !== 'object' || typeof v.at !== 'number' || !member(v.by) || !member(v.child)
+ || typeof v.depth !== 'number' || v.depth < 1) return null
+ const by = v.by as unknown as Record<string, unknown>, child = v.child as unknown as Record<string, unknown>
+ return {
+ at: v.at,
+ by: { machineId: by.machineId as string, agentId: by.agentId as string, name: String(by.name ?? ''), engine: String(by.engine ?? '') },
+ child: { machineId: child.machineId as string, agentId: child.agentId as string, name: String(child.name ?? '') },
+ depth: v.depth,
+ }
+}
+
+const same = (a: LedgerMember, b: LedgerMember): boolean => a.machineId === b.machineId && a.agentId === b.agentId
+
+export class Ledger {
+ private cache: { key: string; rows: Started[] } | null = null
+ constructor(readonly path: string) {}
+
+ /** Where the older lines went when the file passed its size. */
+ get previous(): string { return `${this.path}.1` }
+
+ /** Every line, oldest first: the previous file's, then this one's. An unreadable file is an empty one. Read again
+ * only when either changed. */
+ all(): Started[] {
+ const files = [this.previous, this.path].map((path) => { try { const st = statSync(path); return { path, key: `${st.mtimeMs}:${st.size}` } } catch { return null } })
+ const key = files.map((f) => f?.key ?? '-').join('|')
+ if (this.cache?.key === key) return this.cache.rows
+ const rows: Started[] = []
+ for (const file of files) {
+ if (!file) continue
+ let text = ''
+ try { text = readFileSync(file.path, 'utf8') } catch { continue }
+ for (const line of text.split('\n')) { const row = line ? parseStarted(line) : null; if (row) rows.push(row) }
+ }
+ this.cache = { key, rows }
+ return rows
+ }
+
+ append(row: Started): void {
+ mkdirSync(dirname(this.path), { recursive: true })
+ // One short line with O_APPEND: two agents starting harnesses at once never interleave.
+ appendFileSync(this.path, `${JSON.stringify(row)}\n`, { mode: 0o600 })
+ // Past its size the file becomes the previous one, by a rename: a line appended meanwhile lands in one file or the
+ // other, both read. Rewriting the file in place lost a line appended during the rewrite (the review of #1180).
+ try { if (statSync(this.path).size > ROTATE_BYTES) renameSync(this.path, this.previous) } catch { /* rotated by another */ }
+ }
+
+ /** The line that says who started [m], or null when the person did. */
+ parentOf(m: LedgerMember): Started | null {
+ return this.all().findLast((row) => same(row.child, m)) ?? null
+ }
+
+ /** The harnesses [m] started, newest last. */
+ childrenOf(m: LedgerMember): Started[] {
+ return this.all().filter((row) => same(row.by, m))
+ }
+
+ /** 0 for a harness the person started. */
+ depthOf(m: LedgerMember): number {
+ return this.parentOf(m)?.depth ?? 0
+ }
+
+ /** Whether one of the two started the other. */
+ linked(a: LedgerMember, b: LedgerMember): boolean {
+ return this.all().some((row) => (same(row.by, a) && same(row.child, b)) || (same(row.by, b) && same(row.child, a)))
+ }
+
+ /** The harnesses [m] may message without a tab: its parent and its children. */
+ links(m: LedgerMember): LedgerMember[] {
+ const out: LedgerMember[] = []
+ for (const row of this.all()) {
+ const other = same(row.by, m) ? row.child : same(row.child, m) ? row.by : null
+ if (other && !out.some((o) => same(o, other))) out.push({ machineId: other.machineId, agentId: other.agentId })
+ }
+ return out
+ }
+}
diff --git a/cli/src/agentClient/model.spec.ts b/cli/src/agentClient/model.spec.ts
new file mode 100644
index 000000000..750c954a8
--- /dev/null
+++ b/cli/src/agentClient/model.spec.ts
@@ -0,0 +1,108 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { Ledger, ledgerPath } from './ledger.js'
+import { callerOf, clip, lastTurn, matching, rowsOf, stateOf, STOPPED_WITHIN_MS, type Frame } from './model.js'
+
+const dirs: string[] = []
+const ledger = (): Ledger => {
+ const dir = mkdtempSync(join(tmpdir(), 'model-'))
+ dirs.push(dir)
+ return new Ledger(ledgerPath(dir))
+}
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+
+const NOW = Date.parse('2026-10-11T12:00:00Z')
+const frame = (id: string, over: Partial<Frame> = {}): Frame => ({
+ id, sessionId: `s-${id}`, name: id, engine: 'claude', status: 'active', activity: { state: 'idle' }, tmuxPane: `%${id.length}`,
+ project: { cwd: `/work/${id}`, branch: 'main' }, createdAt: '2026-10-11T10:00:00Z', updatedAt: '2026-10-11T11:00:00Z', ...over,
+})
+
+describe('a harness as the agent verbs show it', () => {
+ it('has one state from its status and activity', () => {
+ expect(stateOf(frame('a', { status: 'stopped' }))).toBe('stopped')
+ expect(stateOf(frame('a', { status: 'offline' }))).toBe('offline')
+ expect(stateOf(frame('a', { activity: { state: 'working' } }))).toBe('working')
+ expect(stateOf(frame('a'))).toBe('idle')
+ expect(stateOf(frame('a', { activity: null }))).toBe('unknown')
+ })
+
+ it('knows the caller by its pane in any state, and a terminal is not one', () => {
+ const frames = [frame('lead', { tmuxPane: '%4' }), frame('sh', { tmuxPane: '%5', engine: 'terminal' }), frame('old', { tmuxPane: '%6', status: 'stopped' }),
+ frame('away', { tmuxPane: '%8', status: 'offline' }), frame('older', { tmuxPane: '%6', status: 'stopped', updatedAt: '2026-10-01T00:00:00Z' }),
+ // tmux numbered panes anew: a person's terminal now has a stopped harness's old pane.
+ frame('ghost', { tmuxPane: '%5', status: 'stopped' })]
+ expect(callerOf(frames, '%4', 'm')).toEqual({ machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' })
+ expect(callerOf(frames, '%5', 'm')).toBeNull()
+ // Stopped or offline, an agent is still that agent, never the person.
+ expect(callerOf(frames, '%6', 'm')?.agentId).toBe('old')
+ expect(callerOf(frames, '%8', 'm')?.agentId).toBe('away')
+ expect(callerOf(frames, '%99', 'm')).toBeNull()
+ expect(callerOf([frame('x', { tmuxPane: '%1', status: 'stopped', updatedAt: undefined }), frame('y', { tmuxPane: '%1', status: 'stopped', updatedAt: undefined })], '%1', 'm')?.agentId).toBe('x')
+ expect(callerOf(frames, undefined, 'm')).toBeNull()
+ expect(callerOf([frame('abcdefghij', { name: '', tmuxPane: '%7' })], '%7', 'm')?.name).toBe('abcdefgh')
+ })
+
+ it('lists agents only, working first, says who started each, and keeps a stopped one a week with --all', () => {
+ const l = ledger()
+ l.append({ at: 1, depth: 1, by: { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }, child: { machineId: 'm', agentId: 'kid', name: 'kid' } })
+ l.append({ at: 1, depth: 1, by: { machineId: 'm', agentId: 'other', name: 'other', engine: 'codex' }, child: { machineId: 'm', agentId: 'cousin', name: 'cousin' } })
+ const frames = [
+ frame('lead'), frame('kid', { activity: { state: 'working' } }), frame('cousin', { updatedAt: '2026-10-11T11:30:00Z' }),
+ frame('sh', { engine: 'terminal' }),
+ frame('recent', { status: 'stopped', updatedAt: new Date(NOW - 60_000).toISOString() }),
+ frame('ancient', { status: 'stopped', updatedAt: new Date(NOW - STOPPED_WITHIN_MS - 1).toISOString() }),
+ frame('wt', { project: { cwd: '/work/repo/.wt/x', root: '/work/repo', worktree: true, branch: null }, updatedAt: 'nonsense' }),
+ ]
+ const caller = { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }
+ const rows = rowsOf(frames, { machineId: 'm', machine: 'mac', caller, ledger: l, now: NOW, all: false })
+ expect(rows.map((r) => r.name)).toEqual(['kid', 'cousin', 'lead', 'wt'])
+ const by = Object.fromEntries(rows.map((r) => [r.name, r]))
+ expect(by.kid).toMatchObject({ startedBy: 'you', yours: true, self: false, state: 'working', agent: 'Claude Code', machine: 'mac' })
+ expect(by.cousin).toMatchObject({ startedBy: 'other', yours: false })
+ expect(by.lead).toMatchObject({ startedBy: 'person', self: true, folder: '/work/lead', branch: 'main' })
+ expect(by.wt).toMatchObject({ folder: '/work/repo', branch: null, lastActive: null })
+ const all = rowsOf(frames, { machineId: 'm', machine: 'mac', caller: null, ledger: l, now: NOW, all: true })
+ expect(all.map((r) => r.name)).toContain('recent')
+ expect(all.map((r) => r.name)).not.toContain('ancient')
+ expect(all.find((r) => r.name === 'kid')).toMatchObject({ startedBy: 'lead', yours: false })
+ })
+
+ it('finds a harness by its whole name, a name\'s start, or an id\'s start', () => {
+ const rows = [{ name: 'Reviewer', id: 'aaaaaaaa-1' }, { name: 'reviewer-2', id: 'bbbbbbbb-2' }, { name: 'fixer', id: 'cccccccc-3' }]
+ expect(matching('reviewer', rows).map((r) => r.id)).toEqual(['aaaaaaaa-1'])
+ expect(matching('rev', rows)).toHaveLength(2)
+ expect(matching('fix', rows).map((r) => r.id)).toEqual(['cccccccc-3'])
+ expect(matching('cccccc', rows).map((r) => r.id)).toEqual(['cccccccc-3'])
+ expect(matching('ccc', rows)).toEqual([])
+ expect(matching('bbbbbbbb-2', rows).map((r) => r.name)).toEqual(['reviewer-2'])
+ expect(matching(' ', rows)).toEqual([])
+ })
+
+ it('reads the last turn: the ask, the answer after its last tool call, and whether it has answered', () => {
+ const ev = (type: string, payload: Record<string, unknown> = {}) => ({ type, payload })
+ expect(lastTurn([])).toBeNull()
+ expect(lastTurn([ev('text_delta', { content: 'orphan' })])).toBeNull()
+ const turn = lastTurn([
+ ev('user_message', { content: 'old' }), ev('text_delta', { content: 'old answer' }), ev('done'),
+ ev('user_message', { content: ' fix the test ' }), ev('text_delta', { content: 'Looking.' }),
+ ev('tool_start'), ev('tool_end'), ev('tool_start'), ev('tool_end'),
+ ev('text_delta', { content: 'Fixed ' }), ev('text_delta', { content: 'it.' }), ev('done', { result: 'success' }),
+ ])
+ expect(turn).toEqual({ ask: 'fix the test', answer: 'Fixed it.', tools: 2, answered: true })
+ // Still working, as the history reader pages it: a `done` at the end of every newest page all the same.
+ expect(lastTurn([ev('user_message', { content: 'go' }), ev('text_delta', { content: 'Starting.' }), ev('tool_start'), ev('tool_end'), ev('done', { result: 'success' })]))
+ .toEqual({ ask: 'go', answer: 'Starting.', tools: 1, answered: false })
+ // A tool that has not answered yet is the turn's last word.
+ expect(lastTurn([ev('user_message', { content: 'go' }), ev('tool_start'), ev('done', { result: 'success' })]))
+ .toEqual({ ask: 'go', answer: '', tools: 1, answered: false })
+ expect(lastTurn([ev('user_message'), ev('text_delta', { content: 'Hi.' })])).toEqual({ ask: null, answer: 'Hi.', tools: 0, answered: true })
+ expect(lastTurn([ev('user_message', { content: 'x' }), ev('text_delta', { content: 7 })])).toEqual({ ask: 'x', answer: '', tools: 0, answered: false })
+ })
+
+ it('clips long text with an ellipsis', () => {
+ expect(clip('abcdef', 4)).toBe('abc…')
+ expect(clip('abc', 4)).toBe('abc')
+ })
+})
diff --git a/cli/src/agentClient/model.ts b/cli/src/agentClient/model.ts
new file mode 100644
index 000000000..13b23ff0a
--- /dev/null
+++ b/cli/src/agentClient/model.ts
@@ -0,0 +1,160 @@
+/**
+ * What the agent verbs show, as pure functions of what the daemon answers (docs/design/2026-10-11-agent-client.md):
+ * a harness's row in `harness ps`, which harness a name means, and its last turn from a page of its transcript.
+ */
+import { engineName } from '../messages/model.js'
+import type { Ledger, LedgerMember } from './ledger.js'
+
+/** The part of the daemon's `AgentFrame` (lib/agentFrame.ts) the verbs read. */
+export interface Frame {
+ id: string
+ sessionId?: string
+ name?: string
+ title?: string | null
+ engine?: string
+ status?: string
+ activity?: { state?: string } | null
+ tmuxPane?: string | null
+ project?: { cwd?: string; root?: string; branch?: string | null; worktree?: boolean } | null
+ createdAt?: string
+ updatedAt?: string
+}
+
+/** The harness running the verb: an agent in its own pane. Null for a person at a terminal. */
+export interface Caller extends LedgerMember { name: string; engine: string }
+
+export type State = 'working' | 'idle' | 'needs-input' | 'stopped' | 'offline' | 'unknown'
+
+export interface Row {
+ name: string
+ id: string
+ agent: string
+ machine: string
+ state: State
+ folder: string | null
+ branch: string | null
+ /** 'person', 'you' (the caller), or the name of the harness that started it. */
+ startedBy: string
+ /** The caller started it: it may send it work and close it. */
+ yours: boolean
+ /** This is the caller's own harness. */
+ self: boolean
+ lastActive: string | null
+ /** The person's last asks and the last turns' summaries, newest first, when the daemon has them. */
+ asks?: string[]
+ about?: string
+}
+
+/** How long a stopped harness stays one to list: what ⌘B offers (desktop task_route.dart `stoppedSessionsWithin`). */
+export const STOPPED_WITHIN_MS = 7 * 24 * 60 * 60_000
+
+export const isAgent = (frame: Frame): boolean => !!frame.id && frame.engine !== 'terminal'
+
+export function stateOf(frame: Frame): State {
+ if (frame.status === 'stopped') return 'stopped'
+ if (frame.status === 'offline') return 'offline'
+ const state = frame.activity?.state
+ return state === 'working' ? 'working' : state === 'idle' ? 'idle' : 'unknown'
+}
+
+/**
+ * The harness on [pane] in [frames], when it is an agent: who is calling. Null only for a person: a terminal's pane,
+ * or one Harness does not know. Matching active harnesses only made an agent the person, with the person's right to
+ * close anything, whenever the daemon listed it offline for a moment (found by e2e/agentClient.e2e.ts). A stopped
+ * harness keeps no pane (`toStoppedProject`), so an old pane number never matches one.
+ */
+export function callerOf(frames: Frame[], pane: string | undefined, machineId: string): Caller | null {
+ if (!pane) return null
+ const on = frames.filter((f) => f.tmuxPane === pane)
+ const frame = on.find((f) => f.status === 'active') ?? on.filter(isAgent).sort((a, b) => (b.updatedAt ?? '').localeCompare(a.updatedAt ?? ''))[0]
+ if (!frame || !isAgent(frame)) return null
+ return { machineId, agentId: frame.id, name: frame.name || frame.id.slice(0, 8), engine: frame.engine ?? '' }
+}
+
+export interface RowContext {
+ machineId: string
+ machine: string
+ caller: Caller | null
+ ledger: Ledger
+ now: number
+ /** Include stopped harnesses (within a week). */
+ all: boolean
+}
+
+export function rowsOf(frames: Frame[], ctx: RowContext): Row[] {
+ const rows: Row[] = []
+ for (const frame of frames) {
+ if (!isAgent(frame)) continue
+ const state = stateOf(frame)
+ const last = frame.updatedAt ? Date.parse(frame.updatedAt) : NaN
+ if (state === 'stopped' && (!ctx.all || !(ctx.now - last < STOPPED_WITHIN_MS))) continue
+ const member = { machineId: ctx.machineId, agentId: frame.id }
+ const you = ctx.caller?.agentId === frame.id && ctx.caller.machineId === ctx.machineId
+ const parent = ctx.ledger.parentOf(member)
+ const yours = !!ctx.caller && !!parent && parent.by.machineId === ctx.caller.machineId && parent.by.agentId === ctx.caller.agentId
+ rows.push({
+ name: frame.name || frame.id.slice(0, 8),
+ id: frame.id,
+ agent: engineName(frame.engine ?? ''),
+ machine: ctx.machine,
+ state,
+ folder: frame.project?.worktree && frame.project.root ? frame.project.root : frame.project?.cwd ?? null,
+ branch: frame.project?.branch ?? null,
+ startedBy: yours ? 'you' : parent ? parent.by.name || parent.by.agentId.slice(0, 8) : 'person',
+ yours,
+ self: you,
+ lastActive: Number.isFinite(last) ? new Date(last).toISOString() : null,
+ })
+ }
+ // Working first, then by last activity: what an agent choosing where work goes looks at first.
+ const rank = (r: Row): number => (r.state === 'working' || r.state === 'needs-input' ? 0 : r.state === 'idle' || r.state === 'unknown' ? 1 : 2)
+ return rows.sort((a, b) => rank(a) - rank(b) || (b.lastActive ?? '').localeCompare(a.lastActive ?? ''))
+}
+
+/** 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()
+ if (!wanted) return []
+ const exact = rows.filter((r) => r.name.toLowerCase() === wanted || r.id.toLowerCase() === wanted)
+ if (exact.length) return exact
+ const prefix = rows.filter((r) => r.name.toLowerCase().startsWith(wanted))
+ if (prefix.length) return prefix
+ return wanted.length >= 6 ? rows.filter((r) => r.id.toLowerCase().startsWith(wanted)) : []
+}
+
+/** One transcript event as the daemon's history reader answers it (`session_get`). */
+export interface HistoryEvent { type?: string; payload?: Record<string, unknown> }
+
+export interface LastTurn {
+ ask: string | null
+ answer: string
+ tools: number
+ /** It has answered: there is text after its last tool call. A turn still at work may have said something since
+ * its last tool too, so this alone never means done; `wait` also needs the screen idle, twice. */
+ answered: boolean
+}
+
+const text = (value: unknown): string => (typeof value === 'string' ? value : '')
+
+/**
+ * The last turn in [events], oldest first: the last ask, and the answer, which is the text after the turn's last
+ * tool call (the narration before it is the working, not the result). Null when the page holds no ask.
+ *
+ * `done` says nothing here: Claude Code's and Codex's history readers end every newest page with one
+ * (`{ result: 'success' }`, claude/normalize.ts), whether the turn ended or not. Read as the end of the turn, it
+ * made `wait` return at once after a `send` and `show` print "success" for a turn of tool calls (the review of
+ * #1180).
+ */
+export function lastTurn(events: HistoryEvent[]): LastTurn | null {
+ let start = -1
+ for (let i = events.length - 1; i >= 0; i--) if (events[i].type === 'user_message') { start = i; break }
+ if (start < 0) return null
+ const turn = events.slice(start + 1)
+ let lastTool = -1, tools = 0
+ turn.forEach((e, i) => { if (e.type === 'tool_start') tools++; if (e.type === 'tool_end' || e.type === 'tool_start') lastTool = i })
+ const said = (from: number) => turn.slice(from).filter((e) => e.type === 'text_delta').map((e) => text(e.payload?.content)).join('').trim()
+ const final = said(lastTool + 1)
+ return { ask: text(events[start].payload?.content).trim() || null, answer: final || said(0), tools, answered: !!final }
+}
+
+export const clip = (value: string, max: number): string => (value.length > max ? `${value.slice(0, max - 1)}…` : value)
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index f9e7b0db4..bd815c102 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -137,7 +137,12 @@ Machine:
harness search <words> find the conversation on this computer that said them: every turn of
every harness, live or stopped (--limit=N, --json)
harness send <name> "text" from an agent's pane: message a teammate in this tab, when Agent Messages
- are on there (the tab's chat icon); \`harness send\` alone lists who is here
+ are on there (the tab's chat icon), or a harness it started;
+ \`harness send\` alone lists who is here
+ harness ps [--all] the harnesses here: state, who started each, what each is about
+ harness show <name> a harness's state and last turn: what it was asked and what it answered
+ harness wait <name>[,<name>] wait until they stop working (--any, --timeout 30m); exit 3 = needs the person
+ harness close <name> [--now] save a harness's screen and stop it; an agent closes only what it started
harness 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
harness version print the installed version (v${VERSION})
@@ -2443,6 +2448,7 @@ async function logsExportCommand(json: boolean): Promise<void> {
import { orchestratorCommand } from './orchestrator/command.js'
import { sendCommand } from './messages/command.js'
+import { agentOrigin, closeCommand, psCommand, showCommand, waitCommand } from './agentClient/commands.js'
// ── arg parse ──────────────────────────────────────────────────────────────────────────────────
// `hn` is the terminal client's short name (like tmux, fzf): the same CLI, entered at `tui`. A call
@@ -2474,6 +2480,18 @@ switch (cmd) {
case 'send':
sendCommand(rest).then(code => { process.exitCode = code }).catch(onError)
break
+ case 'ps':
+ psCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ break
+ case 'show':
+ showCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ break
+ case 'wait':
+ waitCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ break
+ case 'close':
+ closeCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ break
case 'orchestrator':
orchestratorCommand(rest).then(code => { process.exitCode = code }).catch(onError)
break
@@ -2595,6 +2613,7 @@ switch (cmd) {
connect: (url) => new NewCommandSocket(url),
output: (line) => console.log(line),
error: (line) => console.error(line),
+ origin: () => agentOrigin(),
}).then((code) => { process.exitCode = code }).catch(onError)
break
case 'shell-launch':
diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.ts
index c94d09eea..56014a88b 100644
--- a/cli/src/lib/newCommand.spec.ts
+++ b/cli/src/lib/newCommand.spec.ts
@@ -142,7 +142,8 @@ describe('harness new: the daemon', () => {
const d = deps(['codex'], socket)
expect(await newCommand(d)).toBe(0)
expect(socket.sent.map((frame) => frame.type)).toEqual(['machine_select', 'agent_create'])
- expect(socket.sent[0]!.payload).toEqual({ machineId: 'm2', localProtocolVersion: 1 })
+ // A tool, not a window: a window would turn the question watcher on and count as someone looking.
+ expect(socket.sent[0]!.payload).toEqual({ machineId: 'm2', localProtocolVersion: 1, tool: true })
expect(socket.sent[1]!.payload).toMatchObject({ engine: 'codex', cwd: '/work/repo' })
expect(d.out[0]).toBe('Created Codex harness 9-19 10:02 on this computer in /work/repo.')
})
@@ -169,6 +170,85 @@ describe('harness new: the daemon', () => {
expect(refused.err[0]).toBe('Install it first: harness dsh install acme/typst')
})
+ it('says a launch the machine refused or could not confirm failed, never "Created"', async () => {
+ const failed = deps(['codex'], new FakeSocket((frame) => frame.type === 'agent_create'
+ ? { creationId: 'c1', state: 'failed', failure: { code: 'SPAWN_FAILED', detail: 'no codex' } } : null))
+ expect(await newCommand(failed)).toBe(1)
+ expect(failed.err[0]).toBe('The agent could not be started. (no codex)')
+ expect(failed.out).toEqual([])
+ const unknownCode = deps(['codex', '--json'], new FakeSocket((frame) => frame.type === 'agent_create'
+ ? { creationId: 'c1', state: 'failed', failure: { code: 'ODD' } } : null))
+ expect(await newCommand(unknownCode)).toBe(1)
+ expect(JSON.parse(unknownCode.out[0]!)).toEqual({ ok: false, error: 'ODD' })
+ const bare = deps(['codex'], new FakeSocket((frame) => frame.type === 'agent_create' ? { creationId: 'c1', state: 'failed' } : null))
+ expect(await newCommand(bare)).toBe(1)
+ expect(bare.err[0]).toBe('The harness could not be started.')
+ const unconfirmed = deps(['codex'], new FakeSocket((frame) => frame.type === 'agent_create' || frame.type === 'agent_create_status'
+ ? { creationId: 'c1', state: 'unconfirmed' } : null), { sleep: async () => {} })
+ expect(await newCommand(unconfirmed)).toBe(1)
+ expect(unconfirmed.err[0]).toMatch(/could not confirm .*\(unconfirmed\).*harness ps/)
+ })
+
+ it('asks after a launch the machine holds until it is made, by its creation id', async () => {
+ let asks = 0
+ const socket = new FakeSocket((frame) => {
+ if (frame.type === 'agent_create') return { creationId: frame.payload.creationId, state: 'pending' }
+ if (frame.type === 'agent_create_status') return ++asks < 3 ? { creationId: frame.payload.creationId, state: 'pending' } : { state: 'created', agent: { id: 'h1', name: 'held' } }
+ return null
+ })
+ const slept: number[] = []
+ const d = deps(['codex'], socket, { sleep: async (ms) => { slept.push(ms) } })
+ expect(await newCommand(d)).toBe(0)
+ expect(d.out[0]).toBe('Created held on this computer in /work/repo.')
+ const create = socket.sent.find((f) => f.type === 'agent_create')!
+ expect(socket.sent.filter((f) => f.type === 'agent_create_status').every((f) => f.payload.creationId === create.payload.creationId)).toBe(true)
+ expect(slept).toEqual([2_000, 2_000, 2_000])
+ })
+
+ it('reads the folder off the harness the machine made', async () => {
+ const socket = new FakeSocket((frame) => frame.type === 'agent_create'
+ ? { state: 'created', agent: { id: 'a1', name: 'fixer', project: { cwd: '/work/repo/.worktrees/x' } } } : null)
+ const d = deps(['codex'], socket)
+ expect(await newCommand(d)).toBe(0)
+ expect(d.out[0]).toBe('Created fixer on this computer in /work/repo/.worktrees/x.')
+ })
+
+ 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
+ const origin = {
+ 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)}`,
+ }
+ 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 })
+ expect(await newCommand(d)).toBe(0)
+ expect(socket.sent[1]!.payload.prompt).toBe('[from lead on m2]\n\nreview it')
+ expect(created).toEqual([['m2', { id: 'a9', name: 'reviewer' }]])
+ expect(d.out[1]).toBe('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)
+ expect(quiet.sent[1]!.payload.prompt).toBeUndefined()
+ // Over a limit: refused before anything is asked of the machine.
+ const refused = new FakeSocket(() => null)
+ const over = deps(['codex', '--', 'go'], refused, { origin: async () => ({ ...origin, check: async () => { throw new Error('You have 8 harnesses running.') } }) })
+ expect(await newCommand(over)).toBe(1)
+ expect(over.err[0]).toBe('You have 8 harnesses running.')
+ expect(refused.sent).toEqual([])
+ // A record another machine could not keep: said, and the harness is still made.
+ warning = 'its limits start from zero'
+ const far = deps(['codex', '--', 'go'], new FakeSocket((frame) => frame.type === 'agent_create' ? { state: 'created', agent: { id: 'f1', name: 'far' } } : null), { origin: async () => origin })
+ expect(await newCommand(far)).toBe(0)
+ expect(far.err).toEqual(['its limits start from zero'])
+ // A person at a terminal: no origin, the old words.
+ const person = deps(['codex'], new FakeSocket((frame) => frame.type === 'agent_create' ? { state: 'created', agent: { id: 'c1', name: 'x' } } : null), { origin: async () => null })
+ expect(await newCommand(person)).toBe(0)
+ expect(person.out[1]).toBe('Open it in Harness with ⌘O.')
+ })
+
it('turns the machine\'s refusal into words, and a usage slip into the usage', async () => {
const socket = new FakeSocket((frame) => frame.type === 'agent_create' ? { error: 'INVALID_CWD', detail: '/nope' } : null)
const d = deps(['codex', '/nope'], socket)
diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.ts
index 5c2fd8042..8514bcd78 100644
--- a/cli/src/lib/newCommand.ts
+++ b/cli/src/lib/newCommand.ts
@@ -226,6 +226,22 @@ export interface NewCommandDeps {
output: (line: string) => void
error: (line: string) => void
timeoutMs?: number
+ /** Who is starting it, when an agent runs this from its pane (agentClient/commands.ts `agentOrigin`). */
+ origin?: () => Promise<NewOrigin | null>
+ sleep?: (ms: number) => Promise<void>
+}
+
+/** An agent starting a harness (docs/design/2026-10-11-agent-client.md): its limits, the header its task carries,
+ * and the record of who started what. */
+export interface NewOrigin {
+ /** Rejects when the caller may not start another harness now. */
+ check(): Promise<void>
+ /** The first message as the new harness reads it. */
+ prompt(text: string, machineId: string): string
+ /** Records it; a warning to print when the record could not be kept everywhere. */
+ created(machineId: string, agent: Record<string, unknown>): Promise<string | null>
+ /** How to read, wait for and message what was started. */
+ next(agent: Record<string, unknown>): string
}
const ERRORS: Record<string, string> = {
@@ -234,6 +250,7 @@ const ERRORS: Record<string, string> = {
INVALID_DSH: 'That harness is not in the machine\'s catalog, or does not run on that engine.',
PROJECT_EXISTS: 'A project with that name already exists. Name its folder instead.',
PROMPT_UNSUPPORTED: 'That agent cannot be started with a first message.',
+ PROMPT_TOO_LONG: 'A first message holds at most 2,000 characters. Put the rest in a file and name the file in it.',
SPAWN_FAILED: 'The agent could not be started.',
}
@@ -251,7 +268,8 @@ export function daemonSession(deps: Pick<NewCommandDeps, 'port' | 'connect' | 't
waiting.clear()
if (!ready) rejectSession(error)
}
- socket.on('open', () => socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } })))
+ // A tool, not a window: a window's registration turns on the question watcher and counts as someone looking.
+ socket.on('open', () => socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1, tool: true } })))
socket.on('error', (error) => failAll(error))
socket.on('close', (code, reason) => failAll(new Error(
code === 4404 ? 'That machine is not linked to this one yet. Run `harness link` first.'
@@ -302,6 +320,8 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {
return 1
}
try {
+ const origin = (await deps.origin?.()) ?? null
+ await origin?.check()
let machineId = deps.localMachineId
let machineLabel = 'this computer'
if (args.machine !== null) {
@@ -333,13 +353,36 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {
if (entry.installed === false) throw new Error(`Install it first: harness dsh install ${args.agent}`)
if (typeof entry.engine === 'string' && entry.engine) baseEngine = entry.engine
}
- const result = await session.request('agent_create', newAgentPayload(args, cwd, baseEngine))
+ const asked = origin && args.prompt ? { ...args, prompt: origin.prompt(args.prompt, machineId) } : args
+ const payload = newAgentPayload(asked, cwd, baseEngine)
+ let result = await session.request('agent_create', payload)
+ // A launch the daemon holds (a native launch waiting its turn) is still on its way: asked after until it is not,
+ // for a minute. Given up on at once, it could start later with an agent's task and no record of who started it
+ // (the review of #1180).
+ for (let i = 0; i < 30 && (result.state === 'pending' || result.state === 'unconfirmed'); i++) {
+ await (deps.sleep ?? ((ms: number) => new Promise((done) => setTimeout(done, ms))))(2_000)
+ result = await session.request('agent_create_status', { creationId: payload.creationId })
+ }
+ // With a creation id the daemon answers what became of the launch: only `created` made a harness. A refusal
+ // it recorded (`failed`) and an outcome it could not confirm used to print "Created" all the same.
+ if (result.state !== undefined && result.state !== 'created') {
+ const failure = (result.failure ?? {}) as Record<string, unknown>
+ const code = typeof failure.code === 'string' ? failure.code : ''
+ const detail = typeof failure.detail === 'string' && failure.detail ? ` (${failure.detail})` : ''
+ throw new Error(result.state === 'failed'
+ ? `${ERRORS[code] ?? (code || 'The harness could not be started.')}${detail}`
+ : `Harness could not confirm the harness started (${String(result.state)}). Check with \`harness ps\` before starting another.`)
+ }
const agent = (result.agent ?? {}) as Record<string, unknown>
+ const warning = await origin?.created(machineId, agent)
+ if (warning) deps.error(warning)
if (args.json) deps.output(JSON.stringify({ ok: true, machineId, agent }))
else {
- const where = typeof agent.cwd === 'string' ? ` in ${agent.cwd}` : cwd ? ` in ${cwd}` : ''
- deps.output(`Created ${String(agent.name ?? agent.id ?? 'a harness')} on ${machineLabel}${where}.`)
- deps.output('Open it in Harness with ⌘O.')
+ 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}.`)
+ deps.output(origin ? origin.next(agent) : 'Open it in Harness with ⌘O.')
}
return 0
} finally { session.close() }
diff --git a/cli/src/messages/command.ts b/cli/src/messages/command.ts
index 6c348c7c2..562ea59aa 100644
--- a/cli/src/messages/command.ts
+++ b/cli/src/messages/command.ts
@@ -23,7 +23,8 @@ export const SEND_USAGE = `harness send — message your teammates in this tab
harness send <name>[,<name>] "text" message one or more teammates
harness send <name> --text-file PATH a longer message, from a file
-Run it in your own harness pane. Agent Messages must be on in the tab (the chat icon on the tab).
+Run it in your own harness pane. Agent Messages must be on in the tab (the chat icon on the tab), except
+between a harness and the harnesses it started on this machine.
Use --json for structured output.`
export interface SendArgs { names: string[]; text: string; json: boolean }
diff --git a/cli/src/messages/service.spec.ts b/cli/src/messages/service.spec.ts
index 12b03bd1f..e4b05aecb 100644
--- a/cli/src/messages/service.spec.ts
+++ b/cli/src/messages/service.spec.ts
@@ -9,7 +9,8 @@ import { PaneInbox } from './inbox.js'
import { deliveryKey } from './mailbox.js'
import { LIMITS, MessageError } from './model.js'
import type { Rpc } from './rpc.js'
-import { REMOTE_STATUS_MS, startAgentMessages, SWEEP_AFTER_MS, TICK_MS } from './service.js'
+import { REMOTE_STATUS_MS, startAgentMessages, STARTED_TAB, SWEEP_AFTER_MS, TICK_MS } from './service.js'
+import { Ledger, ledgerPath } from '../agentClient/ledger.js'
let root: string
beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'agent-messages-')) })
@@ -187,6 +188,64 @@ describe('harness send', () => {
})
})
+describe('a harness and the harnesses it started', () => {
+ const start = (by: string, child: string, childMachine = 'm1') => new Ledger(ledgerPath(root)).append({
+ at: 1, depth: 1, by: { machineId: 'm1', agentId: by, name: by, engine: 'codex' }, child: { machineId: childMachine, agentId: child, name: child },
+ })
+
+ it('message each other with no tab, both ways; others stay out of reach', async () => {
+ const t = setup({ tabs: [{ id: 'app', name: 'app', enabled: false, panes: [{ machineId: 'm1', agentId: 'lead' }, { machineId: 'm1', agentId: 'api' }] }] })
+ expect((await t.ask({ action: 'send', pane: '%1', to: 'web', text: 'x' })).error).toBe('MESSAGES_OFF')
+ start('lead', 'web')
+ const down = await t.ask({ action: 'send', pane: '%1', to: 'web', text: 'Also check the footer.' })
+ expect(down).toMatchObject({ tab: STARTED_TAB.name, recipients: [{ name: 'web', state: 'queued' }] })
+ expect(t.delivered.at(-1)).toEqual(['web', `[${String(down.id)} from lead · Codex · studio]\nAlso check the footer.`, expect.any(String)])
+ const up = await t.ask({ action: 'send', pane: '%3', to: 'lead', text: 'Done: 3 fixes.' })
+ expect(up.recipients).toEqual([{ name: 'lead', state: 'queued' }])
+ expect((await t.ask({ action: 'send', pane: '%1', to: 'api', text: 'x' })).error).toBe('UNKNOWN_RECIPIENT')
+ expect((await t.ask({ action: 'send', pane: '%2', to: 'web', text: 'x' })).error).toBe('MESSAGES_OFF')
+ const roster = await t.ask({ action: 'send', pane: '%1' })
+ expect(roster.roster).toBe('[Harness] The harness that started you, and those you started:\n web Claude Code · studio · web\nMessage them: harness send <name> "…"')
+ })
+
+ it('reach one another by the start of an id, for a harness whose name is a sentence', async () => {
+ const titled = { ...session('abcdef99-1', '%3'), title: 'so we have built it, then' } as unknown as RegisteredSession
+ const t = setup({ tabs: [], agents: [session('lead', '%1', 'codex'), titled] })
+ start('abcdef99-1', 'lead')
+ expect((await t.ask({ action: 'send', pane: '%1', to: 'abcdef', text: 'x' })).recipients).toEqual([{ name: 'so we have built it, then', state: 'queued' }])
+ // Too short to be an id's start.
+ expect((await t.ask({ action: 'send', pane: '%1', to: 'abcde', text: 'x' })).error).toBe('UNKNOWN_RECIPIENT')
+ })
+
+ it('keep the record of a harness another machine started here, from that machine only', async () => {
+ const t = setup()
+ const row = { at: 5, depth: 2, by: { machineId: 'm2', agentId: 'phone', name: 'phone', engine: 'claude' }, child: { machineId: 'm1', agentId: 'web', name: 'web' } }
+ expect(await t.ask({ action: 'started', row }, OWNER_REMOTE)).toEqual({ recorded: true })
+ expect(new Ledger(ledgerPath(root)).parentOf({ machineId: 'm1', agentId: 'web' })).toMatchObject({ depth: 2, by: { machineId: 'm2' } })
+ expect((await t.ask({ action: 'started', row }, OWNER_LOCAL)).error).toBe('REMOTE_ONLY')
+ expect((await t.ask({ action: 'started', row: { ...row, child: { ...row.child, machineId: 'm3' } } }, OWNER_REMOTE)).error).toBe('INVALID_RECORD')
+ expect((await t.ask({ action: 'started', row: { ...row, by: { ...row.by, machineId: 'm1' } } }, OWNER_REMOTE)).error).toBe('INVALID_RECORD')
+ expect((await t.ask({ action: 'started' }, OWNER_REMOTE)).error).toBe('INVALID_RECORD')
+ expect((await t.ask({ action: 'started', row: { ...row, child: { ...row.child, agentId: 'nobody' } } }, OWNER_REMOTE)).error).toBe('UNKNOWN_HARNESS')
+ })
+
+ it('stay apart across machines: another machine checks against its own tabs', async () => {
+ const t = setup({ tabs: [] })
+ start('lead', 'phone', 'm2')
+ expect((await t.ask({ action: 'send', pane: '%1', to: 'phone', text: 'x' })).error).toBe('MESSAGES_OFF')
+ })
+
+ it('appear once beside their tab teammates, and the roster shows both', async () => {
+ const t = setup()
+ start('lead', 'api')
+ start('lead', 'web')
+ const roster = await t.ask({ action: 'send', pane: '%1' })
+ expect(roster.roster).toMatch(/Teammates:[\s\S]*api[\s\S]*\n\n\[Harness\] The harness that started you, and those you started:\n web /)
+ const both = await t.ask({ action: 'send', pane: '%1', to: 'api,web', text: 'sync' })
+ expect(both).toMatchObject({ tab: 'app', recipients: [{ name: 'api' }, { name: 'web' }] })
+ })
+})
+
describe('from the owner\'s other machines', () => {
const incoming = (to = 'api', from = { machineId: 'm2', agentId: 'phone' }) => ({
id: 'm00000aa', tabId: 'app', text: 'from the phone', at: 5,
diff --git a/cli/src/messages/service.ts b/cli/src/messages/service.ts
index 73022c960..da219f37a 100644
--- a/cli/src/messages/service.ts
+++ b/cli/src/messages/service.ts
@@ -17,8 +17,9 @@ import type { RegisteredSession } from '../lib/registry.js'
import { MessageDirectory, type Member } from './directory.js'
import { PaneInbox } from './inbox.js'
import { Mailbox, type MailboxAgent } from './mailbox.js'
-import { LIMITS, MessageError, messageId, note, parseMessage, rendered, type DeliveryStatus, type Message, type Recipient, type Teammate } from './model.js'
+import { LIMITS, MessageError, engineName, messageId, note, parseMessage, rendered, type DeliveryStatus, type Message, type Recipient, type Teammate } from './model.js'
import { messagesRpc, type Rpc } from './rpc.js'
+import { Ledger, ledgerPath, parseStarted } from '../agentClient/ledger.js'
import { MessageStore, type LocalDelivery } from './store.js'
export interface MessagesOptions {
@@ -29,6 +30,8 @@ export interface MessagesOptions {
rpc?: Rpc
/** The local socket's folder (`ADAPTER_DATA_DIR`) the other machines are reached through. */
dataDir?: string
+ /** Who started which harness (agentClient/ledger.ts); an isolated fixture's own. */
+ ledgerFile?: string
/** Something that decides whether a typed delivery may be written changed: the process tells the core. */
changed?: () => void
now?: () => number
@@ -55,6 +58,9 @@ export const SWEEP_AFTER_MS = 10 * 60_000
const PANE = /^%\d{1,9}$/
const key = (m: Member): string => `${m.machineId}/${m.agentId}`
+const same = (a: Member, b: Member): boolean => a.machineId === b.machineId && a.agentId === b.agentId
+/** Where a message between a harness and one it started is kept: they need share no tab. */
+export const STARTED_TAB = { id: 'started', name: 'started' } as const
export function startAgentMessages(core: CoreApi, options: MessagesOptions = {}): AgentMessages {
const now = options.now ?? Date.now
@@ -62,6 +68,13 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
const self = (): string => core.daemon.machineId()
const at = (machineId: string) => ({ port: core.daemon.port, machineId, dataDir: options.dataDir ?? core.dataDir })
const store = new MessageStore(options.stateDir ?? join(core.dataDir, 'agent-messages'))
+ const lineage = new Ledger(options.ledgerFile ?? ledgerPath(core.dataDir))
+ /**
+ * The harnesses [me] may message without a tab: the one that started it and those it started
+ * (docs/design/2026-10-11-agent-client.md). This machine's only: another machine checks a delivery against its
+ * own directory, and has no record of who started what here.
+ */
+ const linked = (me: Member): Member[] => (me.machineId === self() ? lineage.links(me).filter((m) => m.machineId === self()) : [])
const inbox = new PaneInbox(options.inboxRoot ?? env.HARNESS_AGENT_MESSAGES_DIR)
/** Other machines' names for their agents, with when they were asked. */
const who = new Map<string, { name: string; engine: string; project?: string; at: number }>()
@@ -113,6 +126,7 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
if (!directory.current()) return null
const recipient = { machineId: self(), agentId: delivery.agentId }
if (directory.shared(entry.message.from, recipient)) return null
+ if (linked(recipient).some((m) => same(m, entry.message.from))) return null
const tab = directory.current()!.tabs.find((t) => t.id === entry.message.tabId)
return tab && !tab.enabled ? 'Agent Messages were turned off in this tab' : 'it is no longer in a tab with the sender'
}
@@ -200,6 +214,27 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
return { text, signature: createHash('sha256').update(text).digest('hex').slice(0, 12) }
}
+ /**
+ * Another of the owner's machines started a harness here for one of its agents (`harness new @this-machine`): kept
+ * in this machine's record too, so the new harness's depth and this machine's limits count it.
+ */
+ function started(payload: Record<string, unknown>): Record<string, unknown> {
+ const row = parseStarted(JSON.stringify(payload.row ?? null))
+ if (!row || row.child.machineId !== self() || row.by.machineId === self()) throw new MessageError('INVALID_RECORD', 'That is not a harness another machine started here.')
+ if (!core.agents.live().some((s) => s.agentId === row.child.agentId)) throw new MessageError('UNKNOWN_HARNESS', 'No such harness on this machine.')
+ lineage.append(row)
+ return { recorded: true }
+ }
+
+ /** The harnesses an agent started, or the one that started it, as `harness send` alone lists them. */
+ function linkedNote(links: Member[]): string {
+ const mates = links.map(teammate)
+ const width = Math.max(...mates.map((t) => t.name.length))
+ return ['[Harness] The harness that started you, and those you started:',
+ ...mates.map((t) => ` ${t.name.padEnd(width)} ${[engineName(t.engine), t.machine, t.where].filter(Boolean).join(' · ')}`),
+ 'Message them: harness send <name> "…"'].join('\n')
+ }
+
function withdrawNote(agentId: string): void {
const pending = store.state.notes[agentId]
if (!pending) return
@@ -249,8 +284,10 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
if (!session) throw new MessageError('NOT_A_HARNESS', 'This pane is not a harness Harness knows. Run harness send from an agent\'s pane.')
if (!await directory.refresh()) throw new MessageError('DIRECTORY_UNAVAILABLE', 'Harness could not read which tabs have Agent Messages on. Try again in a moment.')
const me = { machineId: self(), agentId: session.agentId }
- const peers = directory.peers(me)
- if (!directory.tabsOf(me).length) throw new MessageError('MESSAGES_OFF', 'Agent Messages are off in this tab. The person turns them on with the chat icon on the tab, or the tab\'s right-click menu.')
+ const inTabs = directory.peers(me)
+ const links = linked(me).filter((m) => !inTabs.some((p) => same(p, m)))
+ const peers = [...inTabs, ...links]
+ if (!directory.tabsOf(me).length && !links.length) throw new MessageError('MESSAGES_OFF', 'Agent Messages are off in this tab. The person turns them on with the chat icon on the tab, or the tab\'s right-click menu.')
await learnNames(peers, true)
const mates = peers.map(teammate)
const names = (Array.isArray(payload.to) ? payload.to : typeof payload.to === 'string' ? payload.to.split(',') : [])
@@ -259,7 +296,10 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
// No recipient and no text: who is here, the rules, and this agent's last messages. An agent whose context
// was compacted asks this to learn again what it was told: seen on a real team, one rebuilt it from its team
// history in five commands.
- if (!names.length && !text) return { roster: rosterOf(session.agentId)?.text ?? 'No teammates in this tab yet.', recent: recentFor(me) }
+ if (!names.length && !text) {
+ const started = links.length ? linkedNote(links) : null
+ return { roster: [rosterOf(session.agentId)?.text, started].filter(Boolean).join('\n\n') || 'No teammates in this tab yet.', recent: recentFor(me) }
+ }
if (!names.length) throw new MessageError('USAGE', 'Name who to message: harness send <name> "text"')
if (!text.trim()) throw new MessageError('USAGE', 'Write the message: harness send <name> "text"')
if (text.length > LIMITS.text) throw new MessageError('TOO_LONG', `A message holds at most ${LIMITS.text} characters.`)
@@ -267,7 +307,10 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
for (const name of names) {
const wanted = name.toLowerCase()
const exact = mates.filter((m) => m.name.toLowerCase() === wanted)
- const found = exact.length ? exact : mates.filter((m) => m.name.toLowerCase().startsWith(wanted))
+ const prefix = exact.length ? exact : mates.filter((m) => m.name.toLowerCase().startsWith(wanted))
+ // Or the start of its id: a name is the session's title until someone names it, and a title can hold a comma,
+ // which the recipient list splits on (a harness that started another tells it its id to answer to).
+ const found = prefix.length || wanted.length < 6 ? prefix : mates.filter((m) => m.member.agentId.toLowerCase().startsWith(wanted))
const list = mates.map((m) => m.name).join(', ') || 'nobody yet'
if (!found.length) throw new MessageError('UNKNOWN_RECIPIENT', `No teammate named "${name}" in this tab. Teammates: ${list}.`)
if (found.length > 1) throw new MessageError('AMBIGUOUS_RECIPIENT', `"${name}" could be ${found.map((m) => m.name).join(' or ')}. Use more of the name.`)
@@ -285,7 +328,7 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
throw new MessageError('MAILBOX_FULL', 'Too many messages are waiting on this machine. Try again once some are delivered.')
}
sent.set(session.agentId, [...times, now()])
- const tab = directory.shared(me, recipients[0])!
+ const tab = directory.shared(me, recipients[0]) ?? STARTED_TAB
const message: Message = {
id: messageId(), tabId: tab.id, to: recipients, text, at: now(),
from: { ...me, name: core.agents.displayName(session) || session.agentId.slice(0, 8), engine: session.engine, machine: machineName(self()) },
@@ -448,7 +491,7 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
// A pane is only this machine's to name; a hand-over, its status and its names are another machine's
// daemon's to ask, over the relay, never a process here's.
const fromHere = ['send'].includes(String(payload.action))
- if (['send', 'deliver', 'status', 'who'].includes(String(payload.action)) && asker.local !== fromHere) {
+ if (['send', 'deliver', 'status', 'who', 'started'].includes(String(payload.action)) && asker.local !== fromHere) {
throw new MessageError(fromHere ? 'LOCAL_ONLY' : 'REMOTE_ONLY', fromHere ? 'harness send runs in a pane on this machine.' : 'Only another of your machines hands messages over.')
}
switch (payload.action) {
@@ -456,6 +499,7 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
case 'deliver': return deliver(payload)
case 'status': return statusOf(payload)
case 'who': return whoAre(payload)
+ case 'started': return started(payload)
case 'history': return history(payload)
default: throw new MessageError('UNKNOWN_ACTION', 'Unknown Agent Messages request.')
}
diff --git a/docs/design/2026-10-11-agent-client.md b/docs/design/2026-10-11-agent-client.md
new file mode 100644
index 000000000..9f5ebf228
--- /dev/null
+++ b/docs/design/2026-10-11-agent-client.md
@@ -0,0 +1,200 @@
+# Harness for agents
+
+October 11, 2026. First version built (branch `agent-client`).
+
+Web, desktop, phone and `hn` are Harness for people. This is Harness for the agents running in it: a few
+`harness` verbs an agent calls from its shell to see other harnesses, start one, read it, wait for it, message
+it and close it. Same daemon, no screen.
+
+## Why
+
+Agents already try to use Harness and build the missing parts themselves:
+
+- The lamp team (October 10) made its own message IDs, coordination files in Git and a `team.sh` around a
+ 64-character key, and a Codex lead typed into a Claude pane with `tmux paste-buffer` because Harness had no
+ way in. ([Agent Messages](2026-10-10-agent-messages.md) fixed the messaging; nothing yet covers start, read,
+ wait or close.)
+- Each piece exists apart: `harness new`, `harness send`, `harness search`, `harness orchestrator`, Harness
+ Monitor's `hps`. None prints for a program, none waits, and none records that an agent started a harness.
+
+The bet: agents will drive Harness far more than people do. A person opens 5 to 20 harnesses a day and reads
+them; an orchestrating agent can open hundreds, around the clock, and check each one every few seconds. If that
+holds, the agent verbs are the product and the windows become where people watch and steer.
+
+### When an agent should use it
+
+Only when Harness does what the agent's own tools cannot. A quick fan-out inside one task stays with the
+engine's sub-agents (Claude Code's Agent tool, Codex sub-agents): cheaper, faster, results come straight back.
+Harness is for:
+
+1. **Another model**: Claude Code cannot start Codex, Gemini or Devin; Harness runs all thirteen engines.
+2. **Another machine**: the Mac mini, the GPU box, a cloud agent.
+3. **Work that outlives the caller**: a harness keeps running after the caller's turn, context or process ends,
+ and resumes later.
+4. **The person sees it**: what an agent starts appears as a pane on the desktop and the phone, where the person
+ can watch, answer or stop it. Sub-agents are invisible.
+5. **Existing peers**: harnesses the person started, in a tab with Agent Messages on.
+
+Claude Code itself now has `ListAgents`, `SendMessage` and `notify_when_idle` for its own sessions on one
+machine. The verbs below take the same shape on purpose; what Harness adds is every engine, every machine,
+and the person's view of it.
+
+## The agent's side
+
+```
+harness ps [--all] # the harnesses here: state, who started each, what each is about
+harness new [agent] [@machine] [folder] --name N -- <task> # exists; now knows when an agent runs it
+harness show <name> [--chars N] # its state, the last ask and the answer
+harness wait <name>[,<name>…] [--any] [--timeout 30m]
+harness send <name>[,<name>…] "text" # exists (Agent Messages); now also to what you started
+harness close <name> [--now] # save its screen and stop it; resumable
+```
+
+Text by default, for agents as much as people: they read it as well, and it is a third of JSON's size (`ps` on
+the 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.
+
+**Close, not stop** (owner, October 11): `harness stop` stops the daemon, and an agent typing it with a name
+left empty would have stopped Harness. `close` is the app's close (`agent_close`): it saves the screen, stops the
+harness and keeps its conversation, and refuses while the harness is working unless `--now`.
+
+The agent's instructions are a skill, [cli/skills/harness/SKILL.md](../../cli/skills/harness/SKILL.md): when to
+use Harness at all, the rule below, the verbs and the limits. How it reaches agents (installed for Claude Code
+and Codex, or a startup note) is not decided yet.
+
+### ⌘N or ⌘P: new harness or an existing one
+
+This is the choice ⌘B's router makes for a person ([auto router](2026-10-09-auto-router.md)). An agent makes it
+itself: it is a capable model and knows its own task better than any router. It needs what the router sees,
+which `harness ps` gives it (name, what it is about, state, engine, machine, folder, how long ago it stopped),
+and one rule, in its startup note:
+
+1. **Ownership first.** An agent may give work only to a harness it started, or to one in a tab with Agent
+ Messages on. A harness a person is driving is read-only to agents: `show` and `wait` it, never `send`.
+2. **Then sameness.** If a harness it may use is on the same work on the same subject (the router's question),
+ and is idle or resumable, send there: it holds the context. Otherwise `new`: unrelated work, work to run in
+ parallel, another engine or machine, or the matching harness is busy with something else.
+
+No Jev: Jev is for ⌘B only.
+
+## Who started it
+
+Every harness an agent starts is recorded: one line in `<data>/agent-client/started.jsonl` of the daemon that owns
+the agent's pane, with who started it (id, name, engine, machine), the new harness, the time and its depth. A
+harness with no line was started by the person. `ps` shows it (STARTED BY: `person`, `you`, or a name), and
+limits, `close` and measurement read it.
+
+It is a file the CLI appends to, not a field in the core's registry, so this first version changes nothing in the
+core and can be removed whole. Like Agent Messages it is a collaboration scope, not a sandbox: any process of the
+same user can write it. If agents use this, the record moves into the registry beside `forkedFrom`, and the
+windows can show it in the pane header.
+
+The task a harness is started with carries one header line, so the new harness knows it is from an agent and not
+the person (the lamp team's tmux paste read as the owner's), and how to answer:
+
+```
+[from lead · Claude Code · studio, the harness that started you. It reads your answer itself; to ask it something while you work: harness send lead "…"]
+
+Review 3f2a9c1 …
+```
+
+The reply address is the name when it is a plain word or two, else the start of the id: an unnamed harness is
+called by its session title, a sentence that can hold the comma `harness send` splits recipients on (found in the
+live trial: "so we have built harness web,").
+
+## Limits
+
+Spawning is cheap, so runaway spawning is the risk (the Jev loops cost $60 at one caller). Every limit refuses
+with a clear error; nothing is dropped silently.
+
+- Live harnesses started by one harness: 8.
+- Live harnesses started by agents, per machine: 40.
+- Depth: an agent-started harness may start harnesses; one started two levels down may not.
+- `new` per harness: 20 in 10 minutes.
+- An agent never answers a permission dialog, and never closes a harness it did not start.
+
+## How it works
+
+`cli/src/agentClient/`, a CLI module outside the core, composed only of requests the daemon already answers.
+No core change, no new service.
+
+- **The line.** The daemon that owns the caller's pane (`@harness_daemon`, as `harness send` finds it), over its
+ Unix socket, as a **tool**, not a window: a window's registration turns on the question watcher and counts as
+ someone looking. `harness new` registered as a window too; it no longer does.
+- **Who is calling.** `$TMUX_PANE`, matched against the harnesses the daemon lists, offline ones included:
+ matching active ones only made an agent "the person" whenever the daemon listed it offline for a moment (found by
+ the end to end). A person's terminal (in any state: the core marks every session inactive as it starts), or a pane
+ Harness did not make, is the person. A pane Harness made whose harness it no longer knows is what is left of an
+ agent, and so is a caller the daemon did not answer about: they may look, not close or start.
+- **Listing.** Live harnesses only, unless a verb needs the stopped ones (`ps --all`, a name no live harness has,
+ a waited-on harness that left the list): with every stopped one the list took 128 ms against 10 ms here (391
+ harnesses, 21 live).
+- **`ps`**: `agents_list`, plus `agent_recent` (the daemon's stored turn summaries and the person's last asks,
+ no transcript read) for up to 40 live harnesses. 0.8 s for 22 harnesses on the owner's Mac.
+- **`show`**: `agent_close` in `inspect` mode for needs-input (the screen, as the windows read it), and
+ `session_get` with a `limit`, a page at a time from the end, at most four pages: never the whole transcript
+ (the attach OOM, October 3). The answer is the text after the turn's last tool call.
+- **`wait`**: a round every 3 s: one live list per machine, and the screen (`inspect`) only for a harness the daemon
+ does not already call working. Done when it is idle on two looks in a row with the same last turn, and it either
+ worked while waited on or has answered (text after its last tool call). A draft in its box is not done. The history
+ readers end every newest page with a `done` event whether the turn ended or not, so `done` is never read as the
+ end (the review caught `wait` returning at once after a `send`). A harness with nothing asked of it two minutes
+ after it started is done. Cost per round here: a live list 10 ms, an inspect 29 to 48 ms, a transcript page 7 ms.
+- **`close`**: `agent_close`, `idle` mode (or `now`). An agent closes only what it started; the person anything.
+- **`new`**: `lib/newCommand.ts` asks `agentOrigin()` when run from an agent's pane: the limits, the header, the
+ record. The limits count the caller's harnesses on other machines as those machines list them (one closed there
+ frees its place); a machine that cannot be asked has its last day's starts counted. A harness started on another
+ machine is recorded there too (Agent Messages' `started`, from another of the owner's machines only), so its depth
+ and that machine's limits count it; an older daemon there that cannot keep it is said in words. A launch the daemon
+ holds is asked after by its creation id for up to a minute, so a held launch is not left running with an agent's
+ task and no record. `new` also stopped printing "Created" for a launch the daemon refused or could not confirm.
+ Two starts at the same moment from one harness can both pass the limits: they count what was recorded before.
+- **`send`**: Agent Messages lets a harness and the harnesses it started message each other with no tab, on the
+ same machine. It also takes the start of an id. Kept in a `started` log beside the tabs' logs. **Open for the
+ owner:** these messages pass even when the person has turned Agent Messages off in a tab the two share, and no
+ window shows the `started` log yet. Like every Agent Message they need the account's directory read.
+- **Another machine.** `new @mini` works as before; `show`, `wait` and `close` find a harness the caller started
+ there through its record and reach it over the paired relay.
+
+### Verified
+
+- Unit: the module (47 tests), `harness new` (17), Agent Messages (21, with lineage, id prefixes and the
+ `started` record). An independent review found the `done` misreading, the day-long count of other machines'
+ harnesses, the limits restarting on another machine, a caller taken for the person on errors, held launches and
+ the ledger's compaction losing lines; each is fixed and tested above.
+- End to end on the real daemon with the fake engines (`e2e/agentClient.e2e.ts`, 10 s): from an agent's pane,
+ `ps`, `new` with a task, `wait`, `show` (the header and the echoed answer), `send` both ways with no tab on,
+ `close` refused for its own harness and for one its child did not start, then allowed for its child. The fake
+ engine now takes a first message on the command line, as both CLIs do; it used to drop it.
+- Live, on the owner's Mac from this session's own pane against the running daemon: `ps` (22 harnesses, 0.8 s),
+ `new claude --name probe-child -- "Reply with the single word ready"` (0.4 s), `wait` (idle in 7 s), `show`
+ (the header and "ready"), `close` refused for "Harness OS", allowed for the child. `send` answered
+ `UNSUPPORTED` there: that daemon is a dev build whose Agent Messages backend is not deployed until Monday.
+- Not claimed: whether agents choose well (the eval below).
+
+## Measuring it
+
+- **Use:** harnesses started per day by people and by agents, and the ratio. Agents passing 10× people on our
+ own machines within two weeks is the signal to invest.
+- **Choice:** an eval in the style of `cli/scripts/route-eval/` (English only, with a red team and a held-out
+ set): a desk, a task, and whether a Claude Code and a Codex agent pick `send` to the right harness, `new`, or
+ their own sub-agents.
+- **Outcome:** for the same tasks, with and without the verbs, does the work finish and is it better.
+
+### First eval (October 11, three Claude Code agents, the skill given as a file)
+
+| Task | Right choice | What the agent did |
+|---|---|---|
+| A second opinion from Codex on a function, then one follow-up to the same reviewer | `new`, then `send` | `ps`, `new codex --name window-sum-review`, `wait`, `show`; the follow-up went to the same reviewer with `send` ("mine, idle, on the same subject"), and when `send` failed it did not start a second Codex to work around it |
+| Count test files in two folders | its own tools | `find`; started nothing ("a one-line local command") |
+| "Have billing-fix do it": a harness the person started | not `send` | read it with `show`, refused to give it work, did the one-line change itself and said why |
+
+3 of 3 chose right. What it changed: the first message's 2,000-character cap (long tasks now go in a file), and the
+header's reply invitation (every child sent its report back as a message too; it now says the starter reads the
+answer itself). Not yet run: Codex as the starting agent, a red team, a held-out set, and the outcome comparison.
+
+## Not now
+
+An MCP server (a thin wrapper once the CLI holds), agents outside Harness (a Claude Code plugin, `npx`, the MCP
+registries), the windows' tree of who started whom, `ps` across all machines (today: this one, and what you
+started elsewhere), parent and child messaging across machines.