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.

Name another machine with --machine, and read and wait on its harnesses (#1333)

Dee5eb0fd3207c8
diff --git a/cli/src/agentClient/commands.spec.ts b/cli/src/agentClient/commands.spec.ts
index be996f383..29c74d45f 100644
--- a/cli/src/agentClient/commands.spec.ts
+++ b/cli/src/agentClient/commands.spec.ts
@@ -305,7 +305,11 @@ describe('harness show', () => {
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.')
+ expect(h.err.at(-1)).toBe('No harness named "nobody" on this machine. `harness ps` lists them. One on another of your machines: add --machine <name> (`harness ps --machine <name>` lists those).')
+ // An MCP client has no `--machine` to give.
+ const mcp = harness(d, { pane: undefined, env: { HARNESS_VIA_MCP: '1' } })
+ expect(await showCommand(['nobody'], mcp.deps)).toBe(EXIT.failed)
+ expect(mcp.err.at(-1)).toBe('No harness named "nobody" on this machine. `harness_list` lists them.')
})
it('prefers a live harness over a stopped one of the same name', async () => {
@@ -1146,3 +1150,179 @@ describe('an agent asking again for a harness it already has', () => {
expect(h.ledger.parentOf({ machineId: 'm', agentId: 'k5' })?.child).toEqual({ machineId: 'm', agentId: 'k5', name: 'cx', creationId: 'c5' })
})
})
+
+describe('a harness on another machine, named with --machine', () => {
+ // The lamp (lamp-4ace, 2026-10-14 21:36): a program outside Harness ran `harness new claude @office lamp-first-task`,
+ // then could not read the answer with `show` or `wait`. It is the person here: no pane, no agent in its shell.
+ const machines = async () => [
+ { machineId: 'm', label: 'studio', status: 'online', current: true },
+ { machineId: 'office-id', label: 'office', status: 'online', current: false },
+ { machineId: 'mini-id', label: 'Mac mini', status: 'online', current: false },
+ ]
+ const answered = [{ events: [ev('user_message', { content: 'What is 2+2?' }), ev('text_delta', { content: 'Four.' })], hasMore: false }]
+ const lamp = () => {
+ const d = new FakeDaemon(), office = new FakeDaemon('office-id')
+ office.frames = [frame('lamp-first-task', { engine: 'claude' })]
+ office.pages.set('s-lamp-first-task', answered)
+ return { d, office, h: harness(d, { pane: undefined, machines, others: { 'office-id': office } }) }
+ }
+
+ it('shows it through that machine, which a name alone does not reach', async () => {
+ const { d, office, h } = lamp()
+ expect(await showCommand(['lamp-first-task'], h.deps)).toBe(EXIT.failed)
+ expect(h.err[0]).toMatch(/^No harness named "lamp-first-task" on this machine\. .*add --machine <name>/)
+ expect(await showCommand(['--machine', 'office', 'lamp-first-task', '--json'], h.deps)).toBe(EXIT.ok)
+ expect(JSON.parse(h.out.join('\n'))).toMatchObject({ name: 'lamp-first-task', machine: 'office', state: 'idle', startedBy: 'person', ask: 'What is 2+2?', answer: 'Four.' })
+ expect(office.requests.map((r) => r.type)).toEqual(['agents_list', 'agent_close', 'session_get'])
+ expect(office.closed).toBe(true)
+ expect(d.closed).toBe(true)
+ // The option after the name or before it, `--machine=`, a name's start, and a machine by its id or the start of its
+ // name.
+ h.out.length = 0
+ expect(await showCommand(['lamp', '--machine=office-id'], h.deps)).toBe(EXIT.ok)
+ expect(h.out[0]).toBe('lamp-first-task · Claude Code · office · idle · started by person')
+ expect(h.out).toContain('Four.')
+ // More of the answer is asked for on that machine too, as it was named.
+ h.out.length = 0
+ expect(await showCommand(['--machine', 'off', 'lamp-first-task', '--chars', '2'], h.deps)).toBe(EXIT.ok)
+ expect(h.out.at(-1)).toBe('… 3 more characters: harness show --machine off lamp-first-task --chars 5')
+ })
+
+ it('refuses the old @machine with what to type, before asking any machine', async () => {
+ const { d, office, h } = lamp()
+ expect(await showCommand(['@office', 'lamp-first-task'], h.deps)).toBe(EXIT.usage)
+ expect(h.err[0]).toBe('Name the machine with --machine office.')
+ expect(await waitCommand(['lamp-first-task', '@Mac mini'], h.deps)).toBe(EXIT.usage)
+ expect(h.err).toContain('Name the machine with --machine "Mac mini".')
+ expect(await psCommand(['@'], h.deps)).toBe(EXIT.usage)
+ expect(h.err).toContain('Name the machine with --machine <name>.')
+ expect(d.requests).toEqual([])
+ expect(office.requests).toEqual([])
+ })
+
+ it('reads this machine as without --machine, and says what it cannot find there or which machine it does not know', async () => {
+ const { d, office, h } = lamp()
+ d.frames = [frame('here')]
+ expect(await showCommand(['--machine', 'studio', 'here', '--json'], h.deps)).toBe(EXIT.ok)
+ expect(JSON.parse(h.out.join('\n'))).toMatchObject({ name: 'here', machine: 'studio' })
+ expect(office.requests).toEqual([])
+ expect(await showCommand(['--machine', 'office', 'nobody'], h.deps)).toBe(EXIT.failed)
+ expect(h.err.at(-1)).toBe('No harness named "nobody" on office. `harness ps --machine office` lists them.')
+ expect(await showCommand(['--machine', 'nowhere', 'x', '--json'], h.deps)).toBe(EXIT.failed)
+ expect(JSON.parse(h.out.at(-1)!)).toEqual({ error: 'UNKNOWN_MACHINE', detail: 'No machine called “nowhere”. Yours: studio, office, Mac mini.' })
+ // A machine that is not linked here says so.
+ expect(await showCommand(['--machine', 'mini', 'x'], h.deps)).toBe(EXIT.failed)
+ expect(h.err.at(-1)).toBe('not linked')
+ expect(await showCommand(['x', '--machine'], h.deps)).toBe(EXIT.usage)
+ expect(await showCommand(['--machine', '--json', 'x'], h.deps)).toBe(EXIT.usage)
+ expect(await showCommand(['--machine=', 'x'], h.deps)).toBe(EXIT.usage)
+ expect(h.err.filter((l) => l === '--machine needs a value.')).toHaveLength(3)
+ expect(await showCommand(['--machine', 'office', '--machine', 'mini', 'x'], h.deps)).toBe(EXIT.usage)
+ expect(h.err).toContain('Name one machine.')
+ // Without the account's machines to resolve it against, it is refused rather than guessed.
+ const bare = harness(d, { pane: undefined })
+ expect(await showCommand(['--machine', 'office', 'x'], bare.deps)).toBe(EXIT.failed)
+ expect(bare.err).toEqual(['Harness could not list your machines here.'])
+ })
+
+ it('waits on it through that machine, every name there, and names the next step with its machine', async () => {
+ const { office, h } = lamp()
+ office.frames.push(frame('second'))
+ office.screens.set('lamp-first-task', ['working', 'idle'])
+ office.pages.set('s-second', answered)
+ expect(await waitCommand(['--machine', 'office', 'lamp-first-task,second'], h.deps)).toBe(EXIT.ok)
+ expect(h.out).toEqual(['lamp-first-task: idle · read it: harness show --machine office lamp-first-task', 'second: idle · read it: harness show --machine office second'])
+ expect(office.closed).toBe(true)
+ // A machine with a space in its name is quoted.
+ const mini = new FakeDaemon('mini-id')
+ mini.frames = [frame('gpu')]
+ mini.pages.set('s-gpu', answered)
+ const spaced = harness(new FakeDaemon(), { pane: undefined, machines, others: { 'mini-id': mini } })
+ expect(await waitCommand(['--machine', 'Mac mini', 'gpu'], spaced.deps)).toBe(EXIT.ok)
+ expect(spaced.out).toEqual(['gpu: idle · read it: harness show --machine "Mac mini" gpu'])
+ })
+
+ // Review of #1333: each name opened its own connection there, and a second name for the same harness was dropped
+ // with its connection still open, holding the process after it printed.
+ it('closes every connection it opens there, a name given twice or by its start included', async () => {
+ const { office, h } = lamp()
+ const opened: Array<{ closed: boolean }> = []
+ const open: ClientDeps['open'] = async (w, machineId) => {
+ if (machineId !== 'office-id') return h.deps.open!(w, machineId)
+ const line = { machineId: 'office-id', closed: false, request: (type: string, payload?: Record<string, unknown>) => office.request(type, payload), close() { this.closed = true } }
+ opened.push(line)
+ return line as unknown as Daemon
+ }
+ expect(await waitCommand(['--machine', 'office', 'lamp-first-task,lamp,lamp-first-task'], { ...h.deps, open })).toBe(EXIT.ok)
+ expect(h.out).toEqual(['lamp-first-task: idle · read it: harness show --machine office lamp-first-task'])
+ expect(opened.length).toBeGreaterThan(1)
+ expect(opened.filter((line) => !line.closed)).toEqual([])
+ })
+
+ it('lists that machine\'s harnesses, asking it what each is about', async () => {
+ const { d, office, h } = lamp()
+ d.frames = [frame('local-one')]
+ expect(await psCommand(['--machine', 'office'], h.deps)).toBe(EXIT.ok)
+ const text = h.out.join('\n')
+ expect(text).toMatch(/^NAME +AGENT/)
+ expect(text).toMatch(/lamp-first-task +Claude Code +idle +person /)
+ expect(text).toContain('lamp-first-task recap')
+ expect(text).not.toContain('local-one')
+ expect(office.requests.filter((r) => r.type === 'agent_recent').map((r) => r.payload.agentId)).toEqual(['lamp-first-task'])
+ expect(d.requests.filter((r) => r.type === 'agent_recent')).toEqual([])
+ expect(office.closed).toBe(true)
+ h.out.length = 0
+ expect(await psCommand(['--machine', 'office', '--json'], h.deps)).toBe(EXIT.ok)
+ expect(JSON.parse(h.out.join('\n'))).toMatchObject({ you: null, machine: 'office', harnesses: [{ name: 'lamp-first-task', machine: 'office' }] })
+ office.frames = []
+ h.out.length = 0
+ expect(await psCommand(['--machine', 'office'], h.deps)).toBe(EXIT.ok)
+ expect(h.out).toEqual(['No harnesses on office.'])
+ expect(await psCommand(['--machine', 'office', 'x'], h.deps)).toBe(EXIT.usage)
+ expect(h.err[0]).toBe('harness ps takes no names. To read one: harness show --machine office x')
+ })
+
+ it('closes one there as here: the person anything, an agent only what it started', async () => {
+ const { d, office, h } = lamp()
+ expect(await closeCommand(['--machine', 'office', 'lamp-first-task'], h.deps)).toBe(EXIT.ok)
+ expect(h.out).toEqual(['Closed lamp-first-task. Its conversation is kept.'])
+ expect(office.requests.at(-1)).toMatchObject({ type: 'agent_close', payload: { agentId: 'lamp-first-task', mode: 'idle' } })
+ // One still working is waited for on its machine.
+ office.extra.agent_close = (p) => (p.mode === 'inspect' ? { activity: 'working' } : { error: 'SESSION_NOT_IDLE', activity: 'working' })
+ expect(await closeCommand(['--machine', 'office', 'lamp-first-task'], h.deps)).toBe(EXIT.failed)
+ expect(h.err.at(-1)).toBe('lamp-first-task is working. Wait for it (harness wait --machine office lamp-first-task), or close it anyway with --now.')
+ delete office.extra.agent_close
+ // An agent in a pane here: `--machine office` gives it no more than it has here.
+ d.frames = [frame('lead', { engine: 'claude' })]
+ office.frames.push(frame('kid'))
+ const agent = harness(d, { machines, others: { 'office-id': office } })
+ expect(await closeCommand(['--machine', 'office', 'lamp-first-task'], agent.deps)).toBe(EXIT.failed)
+ expect(agent.err[0]).toBe('You did not start lamp-first-task, so you may not close it. Only the person can.')
+ started(agent.ledger, 'lead', 'kid', 'office-id')
+ expect(await closeCommand(['--machine', 'office', 'kid'], agent.deps)).toBe(EXIT.ok)
+ expect(office.requests.at(-1)).toMatchObject({ type: 'agent_close', payload: { agentId: 'kid' } })
+ })
+
+ it('follows an agent\'s harness that has not started on that machine, and only that machine\'s', async () => {
+ const d = new FakeDaemon(), office = new FakeDaemon('office-id')
+ d.frames = [frame('lead', { engine: 'claude' })]
+ const launching = () => ({ state: 'pending', held: { service: 'launch', detail: 'Waiting for launch preparation.' } })
+ office.extra.agent_create_status = launching
+ d.extra.agent_create_status = launching
+ const h = harness(d, { machines, others: { 'office-id': office } })
+ const asked = (name: string, creationId: string, machineId: string) => h.ledger.append({
+ at: NOW, depth: 1, by: { machineId: 'm', agentId: 'lead', name: 'lead', engine: 'claude' }, creation: { machineId, creationId, name, engine: 'codex' },
+ })
+ asked('far', 'c1', 'office-id'); asked('near', 'c2', 'm')
+ expect(await psCommand(['--machine', 'office'], h.deps)).toBe(EXIT.ok)
+ const text = h.out.join('\n')
+ expect(text).toMatch(/\nfar +Codex +starting +you /)
+ expect(text).toContain('far has not started yet: it is starting (Waiting for launch preparation). It starts by itself; wait for it with harness wait --machine office far.')
+ expect(text).not.toContain('near')
+ expect(await showCommand(['--machine', 'office', 'far'], h.deps)).toBe(EXIT.failed)
+ expect(h.err.at(-1)).toBe('far has not started yet: it is starting (Waiting for launch preparation). It starts by itself; wait for it with harness wait --machine office far.')
+ // `near` is starting on this machine, not office.
+ expect(await showCommand(['--machine', 'office', 'near'], h.deps)).toBe(EXIT.failed)
+ expect(h.err.at(-1)).toBe('No harness named "near" on office. `harness ps --machine office` lists them.')
+ })
+})
diff --git a/cli/src/agentClient/commands.ts b/cli/src/agentClient/commands.ts
index 6193076ab..5fe7e8ce8 100644
--- a/cli/src/agentClient/commands.ts
+++ b/cli/src/agentClient/commands.ts
@@ -3,10 +3,12 @@
* 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]
+ * harness ps [--machine <name>] [--all] [--json]
+ * harness show [--machine <name>] <name> [--chars N] [--json]
+ * harness wait [--machine <name>] <name>[,<name>…] [--any] [--timeout 30m] [--json]
+ * harness close [--machine <name>] <name> [--now] [--json]
+ *
+ * `--machine` names another of the owner's machines, as `harness new` takes it; without it, this one.
*
* 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`,
@@ -18,7 +20,7 @@ import { hostname } from 'node:os'
import { join } from 'node:path'
import { readAgentSettings } from '../lib/agentSettings.js'
import { MAX_FIRST_PROMPT_CHARS } from '../lib/engineLaunch.js'
-import type { NewOrigin } from '../lib/newCommand.js'
+import { NewUsageError, resolveNewMachine, type NewMachine, 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 Pending, type Started } from './ledger.js'
@@ -40,25 +42,33 @@ export interface ClientDeps {
intervalMs?: number
/** How a start is recorded on another machine (the messages service's `started`). */
record?: Rpc
+ /** The account's machines, for `--machine` (cli.ts asks the backend, as `harness new` does). */
+ machines?: () => Promise<NewMachine[]>
}
-export const PS_USAGE = `Usage: harness ps [--all] [--json]
+const ON_MACHINE = '--machine <name> is another of your machines, by its name or id as harness new takes it; this one when left out.'
+
+export const PS_USAGE = `Usage: harness ps [--machine <name>] [--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]
+The harnesses on a 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.
+${ON_MACHINE}`
+export const SHOW_USAGE = `Usage: harness show [--machine <name>] <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]
+A harness's state and its last turn: what it was asked and what it answered (the first N characters, 4000 by default).
+${ON_MACHINE}`
+export const WAIT_USAGE = `Usage: harness wait [--machine <name>] <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 or closed by you, 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]
+--timeout takes 90s, 30m, 2h; 0 waits as long as it takes.
+${ON_MACHINE}`
+export const CLOSE_USAGE = `Usage: harness close [--machine <name>] <name> [--now] [--json]
Saves the harness's screen and stops it. Its conversation is kept: the person can resume it.
-It is refused while the harness is working, unless --now. An agent may close only harnesses it started.`
+It is refused while the harness is working, unless --now. An agent may close only harnesses it started.
+${ON_MACHINE}`
export const EXIT = { ok: 0, failed: 1, usage: 2, needsInput: 3, stopped: 4, timeout: 124 } as const
@@ -128,10 +138,39 @@ function setup(deps: ClientDeps) {
sleep: deps.sleep ?? ((ms: number) => new Promise<void>((done) => setTimeout(done, ms))),
intervalMs: deps.intervalMs ?? DEFAULT_INTERVAL_MS,
record: deps.record ?? messagesRpc,
+ machines: deps.machines ?? (async (): Promise<NewMachine[]> => {
+ throw new AgentClientError('MACHINES_UNAVAILABLE', 'Harness could not list your machines here.')
+ }),
}
}
type Setup = ReturnType<typeof setup>
+/** Another machine named with `--machine`: as typed, and its id and name as the account knows them. */
+export interface Away { word: string; machineId: string; label: string }
+
+/**
+ * The machine `--machine` names, resolved as `harness new` resolves it (an id, else a name, case-blind); null for this
+ * one, which is then read exactly as with no `--machine` at all. The lamp (lamp-4ace, 2026-10-14 21:36), a program running the CLI
+ * outside Harness, started `lamp-first-task` on office with `harness new claude @office`, and `show` and `wait` could
+ * not reach it: they looked on the lamp alone, and only an agent's starts are recorded for them to follow.
+ */
+async function machineOf(s: Setup, where: Where, word: string | null): Promise<Away | null> {
+ if (word === null) return null
+ let machine: NewMachine
+ try { machine = resolveNewMachine(word, await s.machines()) } catch (error) {
+ if (error instanceof NewUsageError) throw new AgentClientError('UNKNOWN_MACHINE', error.message)
+ throw error
+ }
+ return machine.current || machine.machineId === where.machineId ? null : { word, machineId: machine.machineId, label: machine.label }
+}
+
+/** `--machine <name>` as a shell takes it: the name quoted when it has a space (`--machine "Mac mini"`). */
+export const machineOption = (word: string): string =>
+ `--machine ${/^[\w.:-]+$/.test(word) ? word : `"${word.replace(/(["\\$`])/g, '\\$1')}"`}`
+
+/** A next step's harness, with the machine it was named on: `--machine office lamp-first-task`. */
+const onAway = (name: string, away: Away | null): string => (away ? `${machineOption(away.word)} ${name}` : name)
+
/** 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 {
@@ -231,36 +270,57 @@ async function askAfter(s: Setup, where: Where, daemon: Daemon, ledger: Ledger,
/** How a harness asked for is called: its name, else its creation's start. */
const askedName = (a: Asked): string => a.row.creation.name || a.row.creation.creationId.slice(0, 8)
-/** What the caller asked for by [name] that has not started: the latest, by the name it was given or its creation's start. */
-const askedNamed = (o: Opened, name: string): Asked | undefined => {
+/** What the caller asked for by [name] that has not started: the latest, by the name it was given or its creation's start.
+ * On [machineId] alone when a machine was named with `--machine`. */
+const askedNamed = (o: Opened, name: string, machineId?: string): Asked | undefined => {
const wanted = name.trim().toLowerCase()
- return o.asked.filter((a) => askedName(a).toLowerCase() === wanted || (wanted.length >= 6 && a.row.creation.creationId.toLowerCase().startsWith(wanted))).at(-1)
+ return o.asked.filter((a) => (machineId === undefined || a.row.creation.machineId === machineId)
+ && (askedName(a).toLowerCase() === wanted || (wanted.length >= 6 && a.row.creation.creationId.toLowerCase().startsWith(wanted)))).at(-1)
}
/** One line on a harness that has not started: what it waits for, or why it never will. */
-function askedLine(env: NodeJS.ProcessEnv, a: Asked): string {
+function askedLine(env: NodeJS.ProcessEnv, a: Asked, away: Away | null = null): string {
const name = askedName(a), engine = engineName(a.row.creation.engine)
if (a.state === 'failed') return `${name} never started: ${a.detail || 'its machine refused it'}.`
const why = a.state === 'installing' ? `Harness is installing ${engine}` : `it is starting${a.detail ? ` (${a.detail.replace(/\.$/, '')})` : ''}`
- return `${name} has not started yet: ${why}. It starts by itself; wait for it with ${step(env, 'wait', name)}.`
+ return `${name} has not started yet: ${why}. It starts by itself; wait for it with ${step(env, 'wait', onAway(name, away))}.`
}
+const notStarted = (env: NodeJS.ProcessEnv, a: Asked, away: Away | null = null): AgentClientError =>
+ new AgentClientError(a.state === 'failed' ? 'NEVER_STARTED' : 'NOT_STARTED', askedLine(env, a, away))
+
interface Target { daemon: Daemon; frame: Frame; machineId: string; machine: string; yours: boolean; remote: boolean }
+/** A machine's harnesses by the names the verbs call them: a terminal is the person's, and an unnamed one is its id's start. */
+const named = (frames: Frame[]) => frames.filter(isAgent).map((f) => ({ ...f, name: f.name || f.id.slice(0, 8) }))
+
+/** Exactly [name], by its name or its id. */
+const exactly = (name: string) => (f: Frame) => f.name?.toLowerCase() === name.trim().toLowerCase() || f.id.toLowerCase() === name.trim().toLowerCase()
+
+/** The caller started it, as the ledger says. */
+const yoursOn = (o: Opened, 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
+}
+
+/** The one of [found] [name] means: a live harness before a stopped one of the same name; null for none. */
+function oneOf<T extends Frame & { name: string }>(name: string, found: T[]): T | null {
+ if (found.some((f) => f.status !== 'stopped')) found = found.filter((f) => f.status !== 'stopped')
+ 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.`)
+ }
+ return found[0] ?? null
+}
+
/**
* 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.
+ * is preferred over a stopped one of the same name. With `--machine` ([away]), one on that machine (`targetAway`).
*/
-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
- }
+async function target(s: Setup, o: Opened, name: string, away: Away | null = null): Promise<Target> {
+ if (away) return targetAway(s, o, name, away)
// Asked for by exactly this name and not started: it, before a harness whose name merely starts so.
const pending = askedNamed(o, name)
- const exactly = (f: Frame) => f.name?.toLowerCase() === name.trim().toLowerCase() || f.id.toLowerCase() === name.trim().toLowerCase()
- if (pending && !named(o.frames).some(exactly)) throw new AgentClientError(pending.state === 'failed' ? 'NEVER_STARTED' : 'NOT_STARTED', askedLine(s.env, pending))
+ if (pending && !named(o.frames).some(exactly(name))) throw notStarted(s.env, pending)
let found = matching(name, named(o.frames))
// No live one by that name: the stopped ones too, read once.
if (!found.length && !o.stopped) {
@@ -268,14 +328,8 @@ async function target(s: Setup, o: Opened, name: string): Promise<Target> {
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.`)
- }
+ const frame = oneOf(name, found)
+ if (frame) return { daemon: o.daemon, frame, machineId: o.where.machineId, machine: o.machine, yours: yoursOn(o, o.where.machineId, frame.id), remote: false }
// 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) : []
@@ -291,8 +345,29 @@ async function target(s: Setup, o: Opened, name: string): Promise<Target> {
return { daemon, frame, machineId: row.child.machineId, machine: row.child.machineId.slice(0, 8), yours: true, remote: true }
}
const asked = askedNamed(o, name)
- if (asked) throw new AgentClientError(asked.state === 'failed' ? 'NEVER_STARTED' : 'NOT_STARTED', askedLine(s.env, asked))
- throw new AgentClientError('UNKNOWN_HARNESS', `No harness named "${name}" on this machine. \`${step(s.env, 'ps')}\` lists them.`)
+ if (asked) throw notStarted(s.env, asked)
+ // A harness on another machine is named with its machine: the lamp's program was told only "on this machine".
+ const elsewhereHint = s.env[VIA_MCP_ENV] === '1' ? '' : ` One on another of your machines: add --machine <name> (\`harness ps --machine <name>\` lists those).`
+ throw new AgentClientError('UNKNOWN_HARNESS', `No harness named "${name}" on this machine. \`${step(s.env, 'ps')}\` lists them.${elsewhereHint}`)
+}
+
+/**
+ * The harness [name] means on the machine named with `--machine`: any harness there, as on this machine, read through
+ * that machine as one an agent started there is. What the caller may do with it is what it may do here: an agent
+ * closes only what it started (`yoursOn`), whichever machine it is on.
+ */
+async function targetAway(s: Setup, o: Opened, name: string, away: Away): Promise<Target> {
+ const pending = askedNamed(o, name, away.machineId)
+ const daemon = await s.open(o.where, away.machineId)
+ try {
+ const live = named(await list(daemon, false))
+ if (pending && !live.some(exactly(name))) throw notStarted(s.env, pending, away)
+ let found = matching(name, live)
+ if (!found.length) found = matching(name, named(await list(daemon, true)))
+ const frame = oneOf(name, found)
+ if (frame) return { daemon, frame, machineId: away.machineId, machine: away.label, yours: yoursOn(o, away.machineId, frame.id), remote: true }
+ throw new AgentClientError('UNKNOWN_HARNESS', `No harness named "${name}" on ${away.label}. \`${step(s.env, 'ps', machineOption(away.word))}\` lists them.`)
+ } catch (error) { daemon.close(); throw error }
}
type Screen = 'working' | 'needs-input' | 'idle' | 'draft'
@@ -328,24 +403,34 @@ async function readLastTurn(t: { daemon: Daemon; frame: Frame }, pages = 4) {
return lastTurn(events)
}
-function words(argv: readonly string[], known: Record<string, 'flag' | 'value'>): { names: string[]; flags: Map<string, string | true> } {
+/** `harness new claude @office`, the old way to name a machine, said as it is now typed. */
+export const atMachineRefusal = (word: string): string =>
+ `Name the machine with ${word.length > 1 ? machineOption(word.slice(1)) : '--machine <name>'}.`
+
+/** The words and options of a verb. Every verb takes `--machine <name>`, which is returned apart. */
+function words(argv: readonly string[], known: Record<string, 'flag' | 'value'>): { names: string[]; flags: Map<string, string | true>; machine: string | null } {
const names: string[] = [], flags = new Map<string, string | true>()
+ let machine: string | null = null
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]
+ const kind = key === '--machine' ? 'value' : 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)
+ if (value === undefined || (key === '--machine' && (!value || value.startsWith('-')))) throw new UsageError(`${key} needs a value.`)
+ if (key !== '--machine') flags.set(key, value)
+ else if (machine !== null) throw new UsageError('Name one machine.')
+ else machine = value
}
- } else names.push(word)
+ // `@office` named a machine in `harness new` once; read as a harness's name, it would only be not found.
+ } else if (word.startsWith('@')) throw new UsageError(atMachineRefusal(word))
+ else names.push(word)
}
- return { names, flags }
+ return { names, flags, machine }
}
export function parseDuration(value: string): number {
@@ -383,8 +468,8 @@ 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.'
+export function formatRows(rows: Row[], caller: Caller | null, now: number, on = 'this machine'): string {
+ if (!rows.length) return `No harnesses on ${on}.`
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) => {
@@ -399,14 +484,22 @@ export function formatRows(rows: Row[], caller: Caller | null, now: number): str
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'))
+ const { names, flags, machine } = words(argv, { '--all': 'flag', '--json': 'flag' })
+ const away = await machineOf(s, s.where(), machine)
+ if (names.length) throw new UsageError(`harness ps takes no names. To read one: harness show ${onAway(names[0], away)}`)
+ const all = flags.has('--all')
+ const o = await opened(s, all)
+ let line: Daemon | null = null
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') })
+ // With `--machine`, that machine's harnesses, through it; who started each is still this machine's ledger's to say.
+ const on = away
+ ? { daemon: line = await s.open(o.where, away.machineId), machineId: away.machineId, machine: away.label }
+ : { daemon: o.daemon, machineId: o.where.machineId, machine: o.machine }
+ const frames = line ? await list(line, all) : o.frames
+ const rows = rowsOf(frames, { machineId: on.machineId, machine: on.machine, caller: o.caller, ledger: o.ledger, now: s.now(), 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)
+ const recent = await on.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>> : [])
@@ -416,22 +509,22 @@ export function psCommand(argv: readonly string[], deps: ClientDeps = {}): Promi
if (about.length) row.about = about.join(' / ')
}))
// Asked for and not started yet: listed by the name it was given, and what it waits for.
- rows.unshift(...o.asked.map((a): Row => ({
+ rows.unshift(...o.asked.filter((a) => !away || a.row.creation.machineId === away.machineId).map((a): Row => ({
name: askedName(a), id: a.row.creation.creationId, agent: engineName(a.row.creation.engine),
- machine: a.row.creation.machineId === o.where.machineId ? o.machine : a.row.creation.machineId.slice(0, 8), state: a.state,
- folder: null, branch: null, startedBy: 'you', yours: true, self: false, lastActive: new Date(a.row.at).toISOString(), about: askedLine(s.env, a),
+ machine: away ? away.label : a.row.creation.machineId === o.where.machineId ? o.machine : a.row.creation.machineId.slice(0, 8), state: a.state,
+ folder: null, branch: null, startedBy: 'you', yours: true, self: false, lastActive: new Date(a.row.at).toISOString(), about: askedLine(s.env, a, away),
})))
const note = o.caller ? openNote(s.env, rows) : null
- 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()), note].filter(Boolean).join('\n'))
+ s.out(flags.has('--json') ? JSON.stringify({ you: o.caller ? o.caller.name : null, machine: on.machine, harnesses: rows }, null, 1)
+ : [formatRows(rows, o.caller, s.now(), away ? away.label : undefined), note].filter(Boolean).join('\n'))
return EXIT.ok
- } finally { o.daemon.close() }
+ } finally { line?.close(); o.daemon.close() }
})
}
/** What `show` ends with for an idle harness of the caller's. */
-export const closeHint = (env: NodeJS.ProcessEnv, frame: Frame): string =>
- `Close it once you have what you need: ${step(env, 'close', addressOf({ machineId: '', agentId: frame.id, name: frame.name ?? '', engine: '' }))}`
+export const closeHint = (env: NodeJS.ProcessEnv, frame: Frame, away: Away | null = null): string =>
+ `Close it once you have what you need: ${step(env, 'close', onAway(addressOf({ machineId: '', agentId: frame.id, name: frame.name ?? '', engine: '' }), away))}`
/** What `ps` ends with for an agent with harnesses of its own open: how many, and how many sit idle. */
export function openNote(env: NodeJS.ProcessEnv, rows: readonly Row[]): string | null {
@@ -446,14 +539,15 @@ export function openNote(env: NodeJS.ProcessEnv, rows: readonly Row[]): string |
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' })
+ const { names, flags, machine } = 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 away = await machineOf(s, s.where(), machine)
const o = await opened(s)
let t: Target | null = null
try {
- t = await target(s, o, names[0])
+ t = await target(s, o, names[0], away)
const listed = stateOf(t.frame)
const screen = listed === 'stopped' || listed === 'offline' ? null : await inspect(t)
const state: State = screen === 'draft' ? 'idle' : screen ?? listed
@@ -475,11 +569,11 @@ export function showCommand(argv: readonly string[], deps: ClientDeps = {}): Pro
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: ${step(s.env, 'show', result.name, { flag: `--chars ${answer.length}`, arg: `chars: ${answer.length}` })}`)
+ if (result.truncated) s.out(`… ${answer.length - chars} more characters: ${step(s.env, 'show', onAway(result.name ?? t.frame.id, away), { flag: `--chars ${answer.length}`, arg: `chars: ${answer.length}` })}`)
}
if (state === 'needs-input') s.out(`It is waiting for the person (a question or a permission). Only the person answers it.`)
// Idle and the caller's: a harness left open after its answer is read sits there for nobody (owner, October 12).
- if (state === 'idle' && t.yours) s.out(closeHint(s.env, t.frame))
+ if (state === 'idle' && t.yours) s.out(closeHint(s.env, t.frame, away))
}
return EXIT.ok
} finally { if (t?.remote) t.daemon.close(); o.daemon.close() }
@@ -496,10 +590,12 @@ type Settled = 'idle' | 'needs-input' | 'stopped' | 'gone' | 'closed' | '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 { names, flags, machine } = 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
+ // Every name on the one machine `--machine` names.
+ const away = await machineOf(s, s.where(), machine)
const o = await opened(s)
const targets: Target[] = []
/** Harnesses asked for that have not started (`Asked`): followed by their creation until they start, then waited on
@@ -509,14 +605,17 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Pro
try {
for (const name of wanted) {
let t: Target
- try { t = await target(s, o, name) } catch (error) {
- const asked = error instanceof AgentClientError && (error.code === 'NOT_STARTED' || error.code === 'NEVER_STARTED') ? askedNamed(o, name) : undefined
+ try { t = await target(s, o, name, away) } catch (error) {
+ const asked = error instanceof AgentClientError && (error.code === 'NOT_STARTED' || error.code === 'NEVER_STARTED') ? askedNamed(o, name, away?.machineId) : undefined
if (!asked) throw error
if (!following.includes(asked)) following.push(asked)
if (asked.state === 'failed') gave.set(asked, 'failed')
continue
}
if (!targets.some((x) => x.machineId === t.machineId && x.frame.id === t.frame.id)) targets.push(t)
+ // Two names for one harness on another machine (`a,a`, a name and its prefix): each opened a connection there,
+ // and the one not kept would hold the process open after it printed (review of #1333).
+ else if (t.remote) t.daemon.close()
}
/** Asks a creation how it stands: made, it joins the harnesses waited on, recorded as the caller's. */
const follow = async (a: Asked): Promise<void> => {
@@ -529,7 +628,7 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Pro
if (status.state === 'created' && typeof frame.id === 'string' && frame.id) {
await recordMade(s, o.where, o.ledger, a.row, frame)
targets.push({ daemon: line, frame: { ...frame, name: frame.name || a.row.creation.name }, machineId: a.row.creation.machineId,
- machine: here ? o.machine : a.row.creation.machineId.slice(0, 8), yours: true, remote: !here })
+ machine: here ? o.machine : away?.label ?? a.row.creation.machineId.slice(0, 8), yours: true, remote: !here })
following.splice(following.indexOf(a), 1)
kept = true
return
@@ -586,7 +685,7 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Pro
throw error
})
}
- // One list per machine a round, however many harnesses are waited on there.
+ // One list per connection a round: every harness on this machine shares one; each named on another has its own.
const lists = new Map<Daemon, Promise<Frame[]>>()
for (const t of targets) {
if (settled.has(t)) continue
@@ -621,14 +720,15 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Pro
if (flags.has('--json')) s.out(JSON.stringify({ harnesses: results }, null, 1))
else for (const r of results) {
if (r.state === 'closed') { s.out(`${r.name}: closed (you closed it)`); continue }
- const next = r.state === 'idle' ? `read it: ${step(s.env, 'show', r.name)}`
+ const read = step(s.env, 'show', onAway(r.name, away))
+ const next = r.state === 'idle' ? `read it: ${read}`
: r.state === 'needs-input' ? 'it waits for the person (a question or a permission); only the person answers it'
- : r.state === 'timeout' ? `still working; wait again or read it: ${step(s.env, 'show', r.name)}`
- : r.state === 'installing' || r.state === 'starting' ? `${askedLine(s.env, following.find((a) => a.row.creation.creationId === r.id)!)}`
+ : r.state === 'timeout' ? `still working; wait again or read it: ${read}`
+ : r.state === 'installing' || r.state === 'starting' ? `${askedLine(s.env, following.find((a) => a.row.creation.creationId === r.id)!, away)}`
: r.state === 'failed' ? `it never started: ${r.detail || 'its machine refused it'}`
// Harness closes one another agent started once it has sat idle half an hour (services/agentCleanup.ts): its
// answer is still there to read.
- : r.state === 'stopped' ? `it was stopped; its answer is kept: ${step(s.env, 'show', r.name)}` : 'it is gone'
+ : r.state === 'stopped' ? `it was stopped; its answer is kept: ${read}` : 'it is gone'
s.out(`${r.name}: ${r.state} · ${next}`)
}
const states = results.map((r) => r.state)
@@ -645,15 +745,16 @@ export function waitCommand(argv: readonly string[], deps: ClientDeps = {}): Pro
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' })
+ const { names, flags, machine } = 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 away = await machineOf(s, s.where(), machine)
const o = await opened(s)
let t: Target | null = null
try {
- try { t = await target(s, o, names[0]) } catch (error) {
+ try { t = await target(s, o, names[0], away) } catch (error) {
// Asked for and not started: closing it is not starting it. Cancelled by its creation, which its machine takes only
// before the launch is claimed (lib/agentCreationReceipt.ts `cancelIntent`).
- const asked = error instanceof AgentClientError && error.code === 'NOT_STARTED' ? askedNamed(o, names[0]) : undefined
+ const asked = error instanceof AgentClientError && error.code === 'NOT_STARTED' ? askedNamed(o, names[0], away?.machineId) : undefined
if (!asked) throw error
const name = askedName(asked), here = asked.row.creation.machineId === o.where.machineId
const line = here ? o.daemon : await s.open(o.where, asked.row.creation.machineId)
@@ -661,11 +762,11 @@ export function closeCommand(argv: readonly string[], deps: ClientDeps = {}): Pr
const reply = await line.request('agent_create_cancel', { creationId: asked.row.creation.creationId }, 20_000)
const refused = askedOf(asked.row, reply)
if (reply.state === 'created' || reply.state === 'unconfirmed') {
- throw new AgentClientError('STARTING', `${name} is starting now, so it was not cancelled. Close it once it has: ${step(s.env, 'close', name)}.`)
+ throw new AgentClientError('STARTING', `${name} is starting now, so it was not cancelled. Close it once it has: ${step(s.env, 'close', onAway(name, away))}.`)
}
if (refused?.state === 'failed') throw new AgentClientError('NEVER_STARTED', `${name} never started: ${refused.detail || 'its machine refused it'}. Nothing to close.`)
if (reply.state !== 'cancelled') {
- throw new AgentClientError(typeof reply.error === 'string' ? reply.error : 'NOT_CANCELLED', `${name} could not be cancelled${typeof reply.error === 'string' ? ` (${reply.error})` : ''}. Check it with ${step(s.env, 'ps')}.`)
+ throw new AgentClientError(typeof reply.error === 'string' ? reply.error : 'NOT_CANCELLED', `${name} could not be cancelled${typeof reply.error === 'string' ? ` (${reply.error})` : ''}. Check it with ${step(s.env, 'ps', away ? machineOption(away.word) : '')}.`)
}
} finally { if (!here) line.close() }
s.out(flags.has('--json') ? JSON.stringify({ name, id: asked.row.creation.creationId, cancelled: true }) : `Cancelled ${name} before it started.`)
@@ -682,9 +783,9 @@ export function closeCommand(argv: readonly string[], deps: ClientDeps = {}): Pr
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 (${step(s.env, 'wait', name)}), or close it anyway with ${s.env[VIA_MCP_ENV] === '1' ? 'now: true' : '--now'}.`)
+ throw new AgentClientError('WORKING', `${name} is ${reply.activity === 'needs_input' ? 'waiting for the person' : 'working'}. Wait for it (${step(s.env, 'wait', onAway(name, away))}), or close it anyway with ${s.env[VIA_MCP_ENV] === '1' ? 'now: true' : '--now'}.`)
}
- if (reply.error === 'AGENT_CHANGED') throw new AgentClientError('AGENT_CHANGED', `${name} changed while closing. Check it with ${step(s.env, 'show', name)}, then try again.`)
+ if (reply.error === 'AGENT_CHANGED') throw new AgentClientError('AGENT_CHANGED', `${name} changed while closing. Check it with ${step(s.env, 'show', onAway(name, away))}, then try again.`)
// Its machine cannot read which conversation it is in just now, and closing it would lose that conversation. The
// machine's own reason ("the native control descriptor type is unavailable") means nothing to the agent asking.
if (reply.error === 'IDENTITY_UNAVAILABLE') {
diff --git a/cli/src/agentClient/mcp.spec.ts b/cli/src/agentClient/mcp.spec.ts
index 559e5449a..ca61bf468 100644
--- a/cli/src/agentClient/mcp.spec.ts
+++ b/cli/src/agentClient/mcp.spec.ts
@@ -80,7 +80,7 @@ describe('harness mcp', () => {
expect(r.calls.map((c) => c.argv)).toEqual([
['ps'], ['ps', '--all'],
['new', 'claude', '/work/here/app', '--name', 'reviewer', '--task', 'review it\nall of it'],
- ['new', 'codex', '@mini', '/abs', '--name', 'gpu', '--task', 'train'],
+ ['new', 'codex', '--machine', 'mini', '/abs', '--name', 'gpu', '--task', 'train'],
['new', 'claude', '~/p', '--name', 'n', '--task', 'x'],
['wait', 'a,b', '--timeout', '45s'], ['wait', 'a', '--any', '--timeout', '600s'], ['wait', 'a', '--timeout', '2s'],
['show', 'a'], ['show', 'a', '--chars', '99'],
@@ -104,7 +104,7 @@ describe('harness mcp', () => {
await answer(call('harness_start', { task: 'go', name: 'both', folder: 'app', project: 'p' }), d)
expect(r.calls.map((c) => c.argv)).toEqual([
['new', 'claude', '--new', 'opinion', '--name', 'opinion', '--task', 'a second opinion'],
- ['new', 'codex', '@mini', '--new', '--name', 'quick', '--task', 'go'],
+ ['new', 'codex', '--machine', 'mini', '--new', '--name', 'quick', '--task', 'go'],
['new', 'claude', '/work/here/app', '--new', 'p', '--name', 'both', '--task', 'go'],
])
// As `harness new` reads them: a new project, one named by the clock, and a refusal to guess between the two.
diff --git a/cli/src/agentClient/mcp.ts b/cli/src/agentClient/mcp.ts
index 64d3d2014..c0a76108d 100644
--- a/cli/src/agentClient/mcp.ts
+++ b/cli/src/agentClient/mcp.ts
@@ -78,7 +78,7 @@ export const TOOLS: Tool[] = [
// (a clean VM, CLI 0.3.75, 2026-10-11). Both given, `harness new` says to name one.
const folder = str(a.folder), project = str(a.project)
const where = folder ? [isAbsolute(folder) || folder.startsWith('~') ? folder : resolve(cwd, folder)] : []
- return ['new', str(a.agent) || 'claude', ...(str(a.machine) ? [`@${str(a.machine)}`] : []), ...where,
+ return ['new', str(a.agent) || 'claude', ...(str(a.machine) ? ['--machine', str(a.machine)] : []), ...where,
...(project || !folder ? ['--new', ...(project ? [project] : [])] : []),
'--name', str(a.name), '--task', typeof a.task === 'string' ? a.task : '']
},
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index ba1620f0a..b1357c291 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -63,7 +63,7 @@ import { apiCommand, apiUsage } from './lib/apiCommand.js'
import { connectionsCommand, connectionsUsage } from './lib/connectors/command.js'
import { remoteCommand } from './remoteCommand.js'
import { tuiCommand } from './tui/index.js'
-import { newCommand } from './lib/newCommand.js'
+import { newCommand, type NewMachine } from './lib/newCommand.js'
import { gridSetupCommand } from './lib/gridSetupCommand.js'
import { WebSocket as NewCommandSocket } from 'ws'
import { describeMasterStatus, readStatusFile } from './harnessd/master.js'
@@ -138,7 +138,7 @@ Machine:
harness service status what launchd or systemd has registered, and whether it runs (--json)
harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktop
harness tui all of Harness in this terminal: swarms, panes, every machine (⌥O ⌥P ⌥N)
- harness new [agent] [@machine] [folder|name] [-- task]
+ harness new [agent] [--machine <name>] [folder|name] [-- task]
make a harness from a shell: \`harness new\` is claude here; see \`harness new -h\`
harness machines list the machines on this account (this computer's is marked)
harness search <words> find the conversation on this computer that said them: every turn of
@@ -149,6 +149,8 @@ Machine:
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
+ new, ps, show, wait and close take --machine <name> for another of your
+ machines: \`harness show --machine office x\`
harness mcp the agent verbs as an MCP server on stdin/stdout, for agents that use MCP
harness settings [<name> on|off] what agents may do (agents-start-agents, pull-request-line, agent-messages): your account's experiments in Settings ▸ Experimental, each off by default
harness machines delete <id> remove ANOTHER machine (refuses this one; use \`harness logout\`)
@@ -2277,6 +2279,17 @@ function machineLabel(machine: OwnerMachineRow): string {
return machine.name?.trim() || machine.hostname?.trim() || '(unnamed)'
}
+/** The account's machines as `--machine` resolves them (`harness new`, `ps`, `show`, `wait`, `close`), and `remote` lists them. */
+async function ownedMachines(): Promise<NewMachine[]> {
+ const { session, headers } = await controlPlaneAuth()
+ return (await fetchMachines(headers)).map((machine) => ({
+ machineId: machine.machineId,
+ label: machineLabel(machine),
+ status: machine.status || 'unknown',
+ current: machine.machineId === session.machineId,
+ }))
+}
+
/** True when `id` names this machine — accepts the short prefix the list prints, not just the full id. */
function matchesMachineId(machineId: string, id: string): boolean {
return machineId === id || machineId.startsWith(id)
@@ -2527,7 +2540,7 @@ switch (cmd) {
openUrlCommand(rest).then(code => { process.exitCode = code }).catch(() => { process.exitCode = 1 })
break
case 'ps':
- psCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ psCommand(rest, { machines: ownedMachines }).then(code => { process.exitCode = code }).catch(onError)
break
case 'settings':
settingsCommand(rest, { port: daemonPort() }).then(code => { process.exitCode = code }).catch(onError)
@@ -2538,13 +2551,13 @@ switch (cmd) {
break
}
case 'show':
- showCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ showCommand(rest, { machines: ownedMachines }).then(code => { process.exitCode = code }).catch(onError)
break
case 'wait':
- waitCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ waitCommand(rest, { machines: ownedMachines }).then(code => { process.exitCode = code }).catch(onError)
break
case 'close':
- closeCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ closeCommand(rest, { machines: ownedMachines }).then(code => { process.exitCode = code }).catch(onError)
break
case 'orchestrator':
orchestratorCommand(rest).then(code => { process.exitCode = code }).catch(onError)
@@ -2655,15 +2668,7 @@ switch (cmd) {
port: daemonPort(),
localMachineId: wantedDaemonIdentity(),
daemonRunning: isDaemonRunning, unreachable: () => daemonUnreachableText(),
- listMachines: async () => {
- const { session, headers } = await controlPlaneAuth()
- return (await fetchMachines(headers)).map((machine) => ({
- machineId: machine.machineId,
- label: machineLabel(machine),
- status: machine.status || 'unknown',
- current: machine.machineId === session.machineId,
- }))
- },
+ listMachines: ownedMachines,
connect: (url) => new NewCommandSocket(url),
output: (line) => console.log(line),
error: (line) => console.error(line),
@@ -2682,15 +2687,7 @@ switch (cmd) {
localMachineId: wantedDaemonIdentity(),
port: daemonPort(),
daemonRunning: isDaemonRunning, unreachable: () => daemonUnreachableText(),
- listMachines: async () => {
- const { session, headers } = await controlPlaneAuth()
- return (await fetchMachines(headers)).map((machine) => ({
- machineId: machine.machineId,
- label: machineLabel(machine),
- status: machine.status || 'unknown',
- current: machine.machineId === session.machineId,
- }))
- },
+ listMachines: ownedMachines,
isLinked: (machineId) => new MachinePeerStore().get(machineId) !== null,
link: (machineId, password) => linkMachineWithPassword(machineId, password),
promptPassword,
diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.ts
index c09d96508..f37242533 100644
--- a/cli/src/lib/newCommand.spec.ts
+++ b/cli/src/lib/newCommand.spec.ts
@@ -15,10 +15,11 @@ describe('harness new: the words', () => {
})
})
- it('reads agent, @machine and a folder in any order', () => {
- const typed = parseNewArgs(['codex', '@mini', '~/code/auth'], env)
+ it('reads agent, --machine and a folder in any order', () => {
+ const typed = parseNewArgs(['codex', '--machine', 'mini', '~/code/auth'], env)
expect(typed).toMatchObject({ agent: 'codex', machine: 'mini', cwd: '~/code/auth', projectName: null })
- expect(parseNewArgs(['~/code/auth', '@mini', 'codex'], env)).toEqual(typed)
+ expect(parseNewArgs(['~/code/auth', '--machine', 'mini', 'codex'], env)).toEqual(typed)
+ expect(parseNewArgs(['codex', '--machine', 'Mac mini'], env)).toMatchObject({ machine: 'Mac mini' })
// On this machine ~ and relative paths are resolved here, from where it was run.
expect(parseNewArgs(['codex', '~/code/auth'], env).cwd).toBe('/home/me/code/auth')
expect(parseNewArgs(['codex', './api'], env).cwd).toBe('/work/repo/api')
@@ -30,27 +31,36 @@ describe('harness new: the words', () => {
expect(parseNewArgs(['codex', '--new'], env)).toMatchObject({ cwd: null, projectName: '' })
expect(parseNewArgs(['--new', 'my game', 'codex'], env)).toMatchObject({ agent: 'codex', projectName: 'my game' })
// Another machine has no "here": with nothing named it is a new project there.
- expect(parseNewArgs(['codex', '@mini'], env)).toMatchObject({ machine: 'mini', cwd: null, projectName: '' })
+ expect(parseNewArgs(['codex', '--machine', 'mini'], env)).toMatchObject({ machine: 'mini', cwd: null, projectName: '' })
+ })
+
+ it('refuses the old @machine, saying what to type, rather than making a project called "@office" here', () => {
+ // `harness new claude @office lamp-first-task` named office until 2026-10-14; read as a word now, it would be this
+ // machine and a project of that name.
+ expect(() => parseNewArgs(['claude', '@office', 'lamp-first-task'], env)).toThrow(new NewUsageError('Name the machine with --machine office.'))
+ expect(() => parseNewArgs(['claude', '@Mac mini'], env)).toThrow(new NewUsageError('Name the machine with --machine "Mac mini".'))
+ expect(() => parseNewArgs(['@'], env)).toThrow(new NewUsageError('Name the machine with --machine <name>.'))
+ expect(() => parseNewArgs(['codex', '--new', '@office'], env)).toThrow(new NewUsageError('Name the machine with --machine office.'))
})
it('takes the task after --, or as --task, with nothing to quote', () => {
expect(parseNewArgs(['codex', '--', 'fix', 'the', 'flaky', 'login', 'test'], env)).toMatchObject({ agent: 'codex', prompt: 'fix the flaky login test', cwd: '/work/repo' })
expect(parseNewArgs(['--task', 'write the README'], env).prompt).toBe('write the README')
// Words after -- are never read as an agent, a machine or a folder.
- expect(parseNewArgs(['--', '@mini', '~/x'], env)).toMatchObject({ agent: 'claude', machine: null, prompt: '@mini ~/x' })
+ expect(parseNewArgs(['--', '@mini', '--machine', '~/x'], env)).toMatchObject({ agent: 'claude', machine: null, prompt: '@mini --machine ~/x' })
})
it('reads a path the shell already expanded as the other machine\'s home', () => {
- // `harness new codex @mini ~/code/auth`, unquoted: zsh hands over /home/me/code/auth.
- expect(parseNewArgs(['codex', '@mini', '/home/me/code/auth'], env).cwd).toBe('~/code/auth')
- expect(parseNewArgs(['codex', '@mini', '/home/me'], env).cwd).toBe('~')
- expect(parseNewArgs(['codex', '@mini', '/srv/app'], env).cwd).toBe('/srv/app')
+ // `harness new codex --machine mini ~/code/auth`, unquoted: zsh hands over /home/me/code/auth.
+ expect(parseNewArgs(['codex', '--machine', 'mini', '/home/me/code/auth'], env).cwd).toBe('~/code/auth')
+ expect(parseNewArgs(['codex', '--machine', 'mini', '/home/me'], env).cwd).toBe('~')
+ expect(parseNewArgs(['codex', '--machine', 'mini', '/srv/app'], env).cwd).toBe('/srv/app')
// On this machine an absolute path is just that.
expect(parseNewArgs(['codex', '/home/me/code/auth'], env).cwd).toBe('/home/me/code/auth')
})
it('says what is wrong instead of guessing', () => {
- for (const argv of [['a', 'b', 'c'], ['@'], ['@a', '@b'], ['/x', '/y'], ['codex', 'game', '/x'], ['--mode', 'yolo'], ['--prompt'], ['--wat'], ['-x'], ['codex', '..'], ['codex', '@mini', './rel']]) {
+ for (const argv of [['a', 'b', 'c'], ['--machine'], ['--machine', '--json'], ['--machine', ' '], ['--machine', 'a', '--machine', 'b'], ['/x', '/y'], ['codex', 'game', '/x'], ['--mode', 'yolo'], ['--prompt'], ['--wat'], ['-x'], ['codex', '..'], ['codex', '--machine', 'mini', './rel']]) {
// `codex ..` is a folder, not an error; every other row must throw.
if (argv.join(' ') === 'codex ..') { expect(parseNewArgs(argv, env).cwd).toBe('/work'); continue }
expect(() => parseNewArgs(argv, env), argv.join(' ')).toThrow(NewUsageError)
@@ -65,8 +75,8 @@ describe('harness new: the words', () => {
// Here, in a folder, or on another machine (its home): as before.
expect(parseNewArgs(['terminal'], env)).toMatchObject({ agent: 'terminal', cwd: env.cwd, projectName: null })
expect(parseNewArgs(['terminal', '~/code'], env)).toMatchObject({ cwd: `${env.home}/code`, projectName: null })
- expect(parseNewArgs(['terminal', '@mini'], env)).toMatchObject({ machine: 'mini', cwd: null, projectName: '' })
- expect(newAgentPayload(parseNewArgs(['terminal', '@mini'], env), null)).not.toHaveProperty('projectSource')
+ expect(parseNewArgs(['terminal', '--machine', 'mini'], env)).toMatchObject({ machine: 'mini', cwd: null, projectName: '' })
+ expect(newAgentPayload(parseNewArgs(['terminal', '--machine', 'mini'], env), null)).not.toHaveProperty('projectSource')
})
it('sends what the app sends', () => {
@@ -198,7 +208,7 @@ describe('harness new: the daemon', () => {
it('asks another machine where its home is before using ~', async () => {
const socket = new FakeSocket((frame) => frame.type === 'fs_list_dir' ? { path: '/Users/mini', entries: [] }
: frame.type === 'agent_create' ? { state: 'created', agent: { id: 'a2', name: 'auth' } } : null)
- const d = deps(['codex', '@mini', '~/code/auth', '--json'], socket)
+ const d = deps(['codex', '--machine', 'mini', '~/code/auth', '--json'], socket)
expect(await newCommand(d)).toBe(0)
expect(socket.sent[0]!.payload.machineId).toBe('m1')
expect(socket.sent.map((frame) => frame.type)).toEqual(['machine_select', 'fs_list_dir', 'agent_create'])
@@ -206,6 +216,35 @@ describe('harness new: the daemon', () => {
expect(JSON.parse(d.out[0]!)).toMatchObject({ ok: true, machineId: 'm1', agent: { id: 'a2' } })
})
+ it('tells a person or a program that started one on another machine how to read it and wait for it from here', async () => {
+ // The lamp (lamp-4ace, 2026-10-14 21:36), a program outside Harness: `harness new claude @office lamp-first-task`
+ // told it only ⌘O, and `show` and `wait` without the machine looked on the lamp alone.
+ const created = (agent: Record<string, unknown>) => new FakeSocket((frame) => frame.type === 'agent_create' ? { state: 'created', agent } : null)
+ const lamp = deps(['claude', '--machine', 'mini', 'lamp-first-task', '--', 'What is 2+2?'], created({ id: 'a9b8c7d6e5', name: 'lamp-first-task' }))
+ expect(await newCommand(lamp)).toBe(0)
+ expect(lamp.out).toEqual([
+ 'Created lamp-first-task on Mac mini.',
+ 'Open it in Harness with ⌘O.',
+ 'Read it: harness show --machine mini lamp-first-task · wait for it: harness wait --machine mini lamp-first-task',
+ ])
+ // A machine named with a space is quoted; a harness whose name is a sentence is called by its id.
+ const spaced = deps(['claude', '--machine', 'Mac mini', 'scratch'], created({ id: 'a9b8c7d6e5', name: 'Claude harness 10-14 9:36' }))
+ expect(await newCommand(spaced)).toBe(0)
+ expect(spaced.out.at(-1)).toBe('Read it: harness show --machine "Mac mini" a9b8c7d6 · wait for it: harness wait --machine "Mac mini" a9b8c7d6')
+ // This computer, named or not, is read without one, as before.
+ const here = deps(['claude', '--machine', 'MacBook'], created({ id: 'h1', name: 'here' }))
+ expect(await newCommand(here)).toBe(0)
+ expect(here.out.at(-1)).toBe('Open it in Harness with ⌘O.')
+ })
+
+ it('refuses the old @machine before asking anything of a machine, and says what to type', async () => {
+ const socket = new FakeSocket(() => null)
+ const old = deps(['claude', '@office', 'lamp-first-task', '--', 'What is 2+2?'], socket)
+ expect(await newCommand(old)).toBe(2)
+ expect(old.err[0]).toBe('Name the machine with --machine office.')
+ expect(socket.sent).toEqual([])
+ })
+
it('reads a store harness\'s engine off the machine, and will not create one that is not installed', async () => {
const catalog = [{ id: 'acme/blender', engine: 'codex', installed: true }, { id: 'acme/typst', engine: 'claude', installed: false }]
const socket = new FakeSocket((frame) => frame.type === 'dsh_list' ? { dsh: catalog }
@@ -334,6 +373,20 @@ describe('harness new: the daemon', () => {
expect(older.err).toEqual([])
})
+ // Review of #1333: a start left pending on another machine was to be checked with `harness ps`, which lists this one.
+ it('names the machine in what to check, for a start left pending on another one', async () => {
+ const answer = (cancel: Record<string, unknown> | null) => new FakeSocket((frame) =>
+ frame.type === 'agent_create' || frame.type === 'agent_create_status' ? { state: 'pending' }
+ : frame.type === 'agent_create_cancel' ? cancel : null)
+ const older = deps(['codex', '--machine', 'mini'], answer(null), { sleep: async () => {} })
+ expect(await newCommand(older)).toBe(1)
+ expect(older.err.at(-1)).toBe('Harness did not start the harness within a minute. '
+ + 'It is still saved and may start later by itself: check with `harness ps --machine mini` before starting another.')
+ const claimed = deps(['codex', '--machine', 'Mac mini'], answer({ state: 'unconfirmed' }), { sleep: async () => {} })
+ expect(await newCommand(claimed)).toBe(1)
+ expect(claimed.err.at(-1)).toBe('Harness could not confirm the harness started (unconfirmed). Check with `harness ps --machine "Mac mini"` before starting another.')
+ })
+
it('says why the machine refused an engine that cannot run, in the machine\'s words', async () => {
const d = deps(['codex'], new FakeSocket((frame) => frame.type === 'agent_create' ? { creationId: 'c1', state: 'failed',
failure: { code: 'ENGINE_CANNOT_RUN', detail: 'Codex is installed but cannot run: /usr/bin/env: ‘node’: No such file or directory' } } : null))
@@ -505,13 +558,13 @@ describe('harness new: the daemon', () => {
const here = created('kid')
expect(await newCommand(deps(['codex', '--', 'review it'], here, { origin: async () => origin }))).toBe(0)
expect(here.sent[1]!.payload).toMatchObject({ startedBy: 'agent', parentAgentId: 'lead-agent' })
- // `@this computer` is still here.
+ // `--machine <this computer>` is still here.
const named = created('kid2')
- expect(await newCommand(deps(['codex', '@MacBook', '--', 'go'], named, { origin: async () => origin }))).toBe(0)
+ expect(await newCommand(deps(['codex', '--machine', 'MacBook', '--', 'go'], named, { origin: async () => origin }))).toBe(0)
expect(named.sent.find((frame) => frame.type === 'agent_create')!.payload.parentAgentId).toBe('lead-agent')
// Another machine has no harness by that id: it records only that an agent started it.
const far = created('far')
- expect(await newCommand(deps(['codex', '@mini', '~/w', '--', 'go'], far, { origin: async () => origin }))).toBe(0)
+ expect(await newCommand(deps(['codex', '--machine', 'mini', '~/w', '--', 'go'], far, { origin: async () => origin }))).toBe(0)
const farCreate = far.sent.find((frame) => frame.type === 'agent_create')!.payload
expect(farCreate.startedBy).toBe('agent')
expect(farCreate).not.toHaveProperty('parentAgentId')
@@ -699,7 +752,7 @@ describe('harness new: a folder the engine would ask about', () => {
expect(await newCommand(person)).toBe(0)
expect(person.out).toEqual([`Created mine on this computer in ${scratch}.`, 'Open it in Harness with ⌘O.'])
// Another machine's folders and settings are not here to read.
- const far = deps(['claude', '@mini', scratch], creating({ id: 'f1', name: 'far' }), { origin: async () => origin, env: c.env, home: c.home })
+ const far = deps(['claude', '--machine', 'mini', scratch], creating({ id: 'f1', name: 'far' }), { origin: async () => origin, env: c.env, home: c.home })
expect(await newCommand(far)).toBe(0)
expect(far.out).toEqual([`Created far on Mac mini in ${scratch}.`, 'Read it: harness show it'])
// A store harness lays its template into an empty folder, which is then trusted; one with content is still asked about.
diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.ts
index 2b5d5cec0..4027d9ff1 100644
--- a/cli/src/lib/newCommand.ts
+++ b/cli/src/lib/newCommand.ts
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto'
import { readdir, readFile, realpath } from 'node:fs/promises'
import { dirname, isAbsolute, join, resolve } from 'node:path'
-import { step, VIA_MCP_ENV } from '../agentClient/commands.js'
+import { addressOf, atMachineRefusal, machineOption, step, VIA_MCP_ENV } from '../agentClient/commands.js'
import { folderTrust } from '../engines/launchPrep.js'
import { ENGINES, type AgentEngine } from '../engines/types.js'
import { engineName } from '../messages/model.js'
@@ -18,19 +18,19 @@ const ENGINE_NAMES: ReadonlySet<string> = new Set(ENGINES)
*
* harness new claude, here
* harness new codex codex, here
- * harness new codex @mini ~/code/auth codex, on mini, in that folder
- * harness new codex my-game codex, in a new project ~/harnesses/my-game
- * harness new --new a new project named after the agent and the time
+ * harness new codex --machine mini ~/code/auth codex, on mini, in that folder
+ * harness new codex my-game codex, in a new project ~/harnesses/my-game
+ * harness new --new a new project named after the agent and the time
*
* A new terminal tab asks nothing and opens where you were; so does this. With no folder named it
* works in the directory it was run from, which is what `cd repo && harness new` means to anyone who
* has typed `code .` — and the one thing the app's box cannot know. The order of the words is free:
- * `@` marks the machine, a path looks like a path, the first other word is the agent and the second
- * names a new project.
+ * `--machine` names the machine, a path looks like a path, the first other word is the agent and the
+ * second names a new project.
*/
export interface NewArgs {
agent: string
- /** A machine's label or id as typed after `@`, or null for this one. */
+ /** A machine's label or id as given to `--machine`, or null for this one. */
machine: string | null
/** The folder to work in, absolute; null when a new project is asked for instead. */
cwd: string | null
@@ -50,12 +50,12 @@ export class NewUsageError extends Error {}
export class NewHelpRequested extends Error {}
export const NEW_USAGE = [
- 'Usage: harness new [agent] [@machine] [folder | project-name] [options]',
+ 'Usage: harness new [agent] [--machine <name>] [folder | project-name] [options]',
'',
' agent claude (default), codex, opencode, …, or a store harness like owner/name',
- ' @machine a machine\'s name or id; this one when left out',
+ ' --machine <m> a machine\'s name or id; this one when left out',
' folder a path (/abs, ~/x, ./x, .): work there. Left out: the current directory.',
- ' With @machine, a path under THIS home is read as the same path under its home,',
+ ' With --machine, a path under THIS home is read as the same path under its home,',
' because the shell has already turned ~/x into /Users/you/x by the time it gets here',
' project-name any other second word: a new project ~/harnesses/<name> on that machine.',
' For scratch or new work give one (harness new codex review -- …), not a folder',
@@ -104,18 +104,23 @@ export function parseNewArgs(argv: string[], env: { cwd: string; home: string })
else if (word === '--mode') { mode = value(word, i); modeGiven = true; i++ }
else if (word === '--prompt' || word === '--task') { prompt = value(word, i); i++ }
else if (word === '--name') { name = value(word, i); i++ }
+ else if (word === '--machine') {
+ if (machine !== null) throw new NewUsageError('Name one machine.')
+ machine = value(word, i).trim()
+ if (!machine) throw new NewUsageError('--machine needs a value.')
+ i++
+ }
else if (word === '--new') {
+ // `--new @office`: the old machine word is refused below, never taken for the project's name.
const next = argv[i + 1]
if (next !== undefined && !next.startsWith('-') && !next.startsWith('@') && !looksLikePath(next)) { projectName = next; i++ }
else projectName = ''
}
// Any dash: `-x` read as an agent called "-x" turns a typo into a confusing refusal from the machine.
else if (word.startsWith('-')) throw new NewUsageError(`Unknown option ${word}.`)
- else if (word.startsWith('@')) {
- if (word.length === 1) throw new NewUsageError('Name a machine after @.')
- if (machine !== null) throw new NewUsageError('Name one machine.')
- machine = word.slice(1)
- }
+ // `@office` named the machine until every command took `--machine`. Taken as a word now, it would quietly be a new
+ // project called "@office" on this machine: refused, with what to type instead.
+ else if (word.startsWith('@')) throw new NewUsageError(atMachineRefusal(word))
else if (looksLikePath(word)) {
if (folder !== null) throw new NewUsageError('Name one folder.')
folder = word
@@ -195,12 +200,12 @@ export function newAgentPayload(args: NewArgs, cwd: string | null, baseEngine =
export interface NewMachine { machineId: string; label: string; status: string; current: boolean }
-/** The machine `@word` means: an exact id, else a label, case-blind; ambiguity is an error, not a guess. */
+/** The machine `--machine <word>` means: an exact id, else a label, case-blind; ambiguity is an error, not a guess. */
export function resolveNewMachine(word: string, machines: NewMachine[]): NewMachine {
const byId = machines.find((machine) => machine.machineId === word)
if (byId) return byId
const wanted = word.toLowerCase()
- // The whole name, else its start, else a word in it: `@mini` is "Mac mini" to the person typing.
+ // The whole name, else its start, else a word in it: `--machine mini` is "Mac mini" to the person typing.
const tiers = [
(label: string) => label === wanted,
(label: string) => label.startsWith(wanted),
@@ -448,6 +453,9 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {
machineLabel = machine.current ? 'this computer' : machine.label
local = machine.current
}
+ // A start left pending on another machine is looked for there: `harness ps` alone lists this one, which is how
+ // the lamp lost its harness on office (review of #1333).
+ const psThere = local || args.machine === null ? 'harness ps' : `harness ps ${machineOption(args.machine)}`
if (!machineId) {
deps.error('This computer is not signed in to Harness. Run `harness login`.')
return 1
@@ -566,7 +574,7 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {
}
// No answer (a daemon that predates the cancel): the request is still saved, and may start later.
if (typeof cancelled?.state !== 'string' || cancelled.state === 'pending') {
- throw new Error(`${why} It is still saved and may start later by itself: check with \`harness ps\` before starting another.`)
+ throw new Error(`${why} It is still saved and may start later by itself: check with \`${psThere}\` before starting another.`)
}
// Too late to cancel: what became of it (created, refused, or claimed and starting now) is the answer.
result = cancelled
@@ -580,7 +588,7 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {
throw new Error(result.state === 'failed'
// A code this has no words for is shown by the daemon's own detail, which names the engine and why.
? (ERRORS[code] ? `${ERRORS[code]}${detail ? ` (${detail})` : ''}` : detail || code || 'The harness could not be started.')
- : `Harness could not confirm the harness started (${String(result.state)}). Check with \`harness ps\` before starting another.`)
+ : `Harness could not confirm the harness started (${String(result.state)}). Check with \`${psThere}\` before starting another.`)
}
const agent = (result.agent ?? {}) as Record<string, unknown>
const warning = await origin?.created(machineId, agent, creationId)
@@ -593,6 +601,13 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {
deps.output(`Created ${name} on ${machineLabel}${where}.`)
if (trustNote) deps.output(trustNote)
deps.output(origin ? origin.next(agent) : 'Open it in Harness with ⌘O.')
+ // Started on another machine by a person or a program, it is read and waited for through that machine, named as
+ // it was here. The lamp (lamp-4ace, 2026-10-14 21:36), a program outside Harness, started `lamp-first-task` on
+ // office this way and was told only ⌘O, which it has not got.
+ if (!origin && !local && args.machine !== null) {
+ const at = `${machineOption(args.machine)} ${addressOf({ machineId: '', agentId: String(agent.id ?? ''), name: String(agent.name ?? ''), engine: '' })}`
+ deps.output(`Read it: ${step(env, 'show', at)} · wait for it: ${step(env, 'wait', at)}`)
+ }
}
return 0
} finally { session.close() }
diff --git a/cli/src/messages/service.ts b/cli/src/messages/service.ts
index 2563bf29c..b4ebab865 100644
--- a/cli/src/messages/service.ts
+++ b/cli/src/messages/service.ts
@@ -335,7 +335,7 @@ export function startAgentMessages(core: CoreApi, options: MessagesOptions = {})
}
/**
- * Another of the owner's machines started a harness here for one of its agents (`harness new @this-machine`): kept
+ * Another of the owner's machines started a harness here for one of its agents (`harness new --machine <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> {
diff --git a/docs/cli.md b/docs/cli.md
index c79a142f4..a02764e54 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -93,17 +93,22 @@ the hook it installs.
`harness new` makes a session from a shell, in the words the app's box uses, over this same socket:
```
-harness new claude, in the current directory
-harness new codex @mini ~/code/auth codex, on the machine called mini, in that folder
-harness new codex my-game codex, in a new project ~/harnesses/my-game
+harness new claude, in the current directory
+harness new codex --machine mini ~/code/auth codex, on the machine called mini, in that folder
+harness new codex my-game codex, in a new project ~/harnesses/my-game
harness new --plan --prompt "fix the flaky login test"
```
-Words may come in any order: `@` marks the machine (id, name, or an unambiguous start of a word in
-it), a path looks like a path, the first other word is the agent and a second names a new project.
-`--mode auto|ask|plan|full`, `--name`, `--new [name]` and `--json` are the rest. There is still no
+Words may come in any order: a path looks like a path, the first other word is the agent and a
+second names a new project. `--machine <name>` picks the machine (id, name, or an unambiguous start
+of a word in it); `@mini`, the old way, is refused with what to type instead. `--mode
+auto|ask|plan|full`, `--name`, `--new [name]` and `--json` are the rest. There is still no
`harness split`: panes are arranged in the app.
+`harness ps`, `show`, `wait` and `close` take `--machine <name>` too, to read, wait for or close a
+harness on another of your machines: `harness new claude --machine office --name check -- …`, then
+`harness wait --machine office check` and `harness show --machine office check`.
+
## Your devices
Signing in is what makes a device trusted: every computer and app signed in to the account adds its
diff --git a/docs/design/2026-10-11-agent-client.md b/docs/design/2026-10-11-agent-client.md
index 98fa3e6e6..aaea22811 100644
--- a/docs/design/2026-10-11-agent-client.md
+++ b/docs/design/2026-10-11-agent-client.md
@@ -44,7 +44,7 @@ and the person's view of it.
```
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 new [agent] [--machine <name>] [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): teammates in its tab, while it is on, only
@@ -407,8 +407,12 @@ No core change, no new service.
Two starts at the same moment from one harness can both pass the limits: they count what was recorded before.
- **`send`**: nothing of its own. A harness messages another only in a tab the two share, while Agent Messages are
on, like any teammate (`harness send` also takes the start of an id there).
-- **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.
+- **Another machine.** `new --machine mini` (it was `new @mini` until 2026-10-14); `show`, `wait` and `close` find a
+ harness the caller started there through its record and reach it over the paired relay. Anyone, a person or a
+ program outside Harness, names the machine for the rest: `ps`, `show`, `wait` and `close` take `--machine <name>`
+ too. A program on the lamp started `lamp-first-task` on office and could not read its answer, since only an
+ agent's starts are recorded (2026-10-14). `@mini` is refused with what to type instead, so a script that still
+ says it fails rather than starting a project called "@mini" here.
### Agent Messages off means off (owner, October 11, 2026)
diff --git a/plugins/harness/skills/harness/SKILL.md b/plugins/harness/skills/harness/SKILL.md
index 1c31a2fc0..2d0ced647 100644
--- a/plugins/harness/skills/harness/SKILL.md
+++ b/plugins/harness/skills/harness/SKILL.md
@@ -67,8 +67,8 @@ the person can watch and step in.
## The verbs
```
-harness ps [--all] # the harnesses here
-harness new [agent] [@machine] [folder | project] --name <name> -- <task>
+harness ps [--all] [--machine <name>] # the harnesses here, or on another machine
+harness new [agent] [--machine <name>] [folder | project] --name <name> -- <task>
harness wait <name>[,<name>…] [--any] [--timeout 30m]
harness show <name> [--chars N] # its state, the last ask and its answer
harness send <name> "text" # a teammate in this tab, while Agent Messages are on
@@ -78,7 +78,8 @@ harness close <name> [--now] # when you are done with one
- **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.
- `agent` is `claude` (the default), `codex`, or another agent installed on that machine. The folder defaults
- to the current directory.
+ to the current directory. `--machine <name>` starts it on another of the person's machines (`harness machines`
+ lists them); `show`, `wait` and `close` then find it by its name.
- For scratch or new work, give a project name (`harness new codex review -- …`, which makes `~/harnesses/review`)
rather than a folder of your own: Claude Code and Codex ask the person to trust a folder Harness did not make.
- Put the whole task in `-- <task>`: what to do, where, what done looks like, and what to answer with. A task
diff --git a/website/public/agents/index.html b/website/public/agents/index.html
index f77294941..3ffe31554 100644
--- a/website/public/agents/index.html
+++ b/website/public/agents/index.html
@@ -123,7 +123,7 @@ curl -fsSL https://raw.githubusercontent.com/autonomous-ai/openharness/main/plug
<tr><td><code>harness ps [--all]</code></td><td>The harnesses on this machine: name, agent, state, who started it,
when it was last active, its folder and what it is about. <code>--all</code> adds the ones stopped in the
last week.</td></tr>
- <tr><td><code>harness new [agent] [@machine] [folder | project] --name NAME -- TASK</code></td><td>Start a harness and give
+ <tr><td><code>harness new [agent] [--machine NAME] [folder | project] --name NAME -- TASK</code></td><td>Start a harness and give
it a task. <code>agent</code> is <code>claude</code> (the default), <code>codex</code>, or another agent
installed there. The folder is the current directory when left out. For scratch or new work, give a project
name (<code>harness new codex review -- …</code>) rather than a folder of your own: Claude Code and Codex ask
@@ -209,9 +209,10 @@ harness wait reviewer &amp;&amp; harness show reviewer</code></pre>
<h2 id="machines">Run on another machine</h2>
<pre><code>harness machines
-harness new codex @mini ~/code/app --name train -- "Run the training script and report the final loss."</code></pre>
+harness new codex --machine mini ~/code/app --name train -- "Run the training script and report the final loss."</code></pre>
<p>Needs the person signed in to Harness on both computers (<code>harness login</code>). <code>harness ps</code>
- lists this machine.</p>
+ lists this machine; <code>harness ps --machine mini</code>, <code>harness show --machine mini train</code> and
+ <code>harness wait --machine mini train</code> reach the other.</p>
<h2 id="where">Inside a harness, or outside Harness</h2>
<ul>
diff --git a/website/public/llms.txt b/website/public/llms.txt
index ba935120c..ef8218799 100644
--- a/website/public/llms.txt
+++ b/website/public/llms.txt
@@ -17,13 +17,15 @@ The commands an agent uses:
```
harness ps [--all] # the harnesses here: state, who started each, what each is about
-harness new [agent] [@machine] [folder | project] --name NAME -- TASK
+harness new [agent] [--machine NAME] [folder | project] --name NAME -- TASK
harness wait NAME[,NAME…] [--any] [--timeout 30m] # exits 0 idle, 3 needs the person, 4 stopped or gone, 124 timed out
harness show NAME [--chars N] # its state, the last ask and its answer
harness send NAME "text" # a teammate in this tab, while Agent Messages are on
harness close NAME [--now] # save its screen and stop it; the conversation is kept
```
+`ps`, `show`, `wait` and `close` take `--machine NAME` too, for a harness on another of the person's machines.
+
Once Harness runs on a computer, Claude Code and Codex there run these commands and Harness's MCP tools without asking: Harness adds them to their permission rules, and Codex runs them outside its sandbox. Run each `harness` command by itself or join them with `&&`; piped or joined with other commands, the rule no longer matches. Where Harness has not set an agent up, run `harness` outside its sandbox, which cannot reach Harness's local daemon.
`harness mcp` serves the same as MCP tools over stdio (command `harness`, arguments `["mcp"]`): `harness_list`, `harness_start`, `harness_wait`, `harness_read`, `harness_close`, and `harness_send` inside a harness (teammates in its tab only, while Agent Messages are on: Settings ▸ Experimental, off by default). For clients that start servers with npx, `npx -y @autonomous-ai/harness-mcp` runs `harness mcp`, or, where Harness is not installed, offers one tool, `harness_setup`, that says how to install it.