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.

An agent outside Harness is an agent, not the person (#1184)

Dee3e82ca5c141f
diff --git a/cli/e2e/agentClient.e2e.ts b/cli/e2e/agentClient.e2e.ts
index 5b3b7193f..462f219eb 100644
--- a/cli/e2e/agentClient.e2e.ts
+++ b/cli/e2e/agentClient.e2e.ts
@@ -21,10 +21,10 @@ const signIn = (d: IsolatedDaemon) => writeFileSync(join(d.root, 'auth', 'sessio
}), { 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 }> {
+function harness(d: IsolatedDaemon, pane: string, args: string[], extra: Record<string, 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'],
+ cwd: CLI_ROOT, env: { ...d.env, TMUX_PANE: pane, ...extra }, stdio: ['ignore', 'pipe', 'pipe'],
})
let out = '', err = ''
child.stdout.on('data', (chunk) => { out += chunk })
@@ -143,4 +143,48 @@ describe('Harness for agents, end to end', () => {
const closed = await run('close', 'solo')
expect(closed.code, closed.err).toBe(0)
})
+
+ it('an agent outside Harness starts, reads and closes a harness of its own, and may not close the person\'s', async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const personDir = join(d.projectsDir, 'person')
+ mkdirSync(personDir, { recursive: true })
+ const theirs = await client.request('agent_create', { engine: 'claude', cwd: personDir, bypassPermission: true, name: 'theirs' }, 90_000)
+ expect(theirs.error, JSON.stringify(theirs)).toBeUndefined()
+ // Claude Code in a terminal app: no pane, and the session its shell names.
+ const run = (...args: string[]) => harness(d, '', args, { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 'outside-session' })
+
+ const ps = await run('ps')
+ expect(ps.code, ps.err).toBe(0)
+ expect(ps.out.split('\n')[0]).toBe('You are Claude Code, outside Harness.')
+ const dir = join(d.projectsDir, 'helper')
+ mkdirSync(dir, { recursive: true })
+ const started = await run('new', 'claude', dir, '--name', 'helper', '--', 'check it')
+ expect(started.code, started.out + started.err).toBe(0)
+ // Nothing can message an agent with no pane: no `send` in what to do next.
+ expect(started.out).toContain('Read it: harness show helper · wait for it: harness wait helper')
+ expect(started.out).not.toContain('harness send')
+ 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: 'claude-code:outside-session', name: 'Claude Code' }), child: expect.objectContaining({ name: 'helper' }) })])
+
+ const waited = await run('wait', 'helper', '--timeout', '2m')
+ expect(waited.code, waited.out + waited.err).toBe(0)
+ const shown = await run('show', 'helper')
+ expect(shown.out).toContain('asked: [from Claude Code outside Harness · ')
+ expect(shown.out).toContain('the agent that started you. It reads your answer itself.]')
+ expect(shown.out).toContain('check it')
+
+ const person = await run('close', 'theirs')
+ expect(person.code).toBe(1)
+ expect(person.err).toContain('You did not start theirs')
+ // Another session of the same agent did not start it either.
+ const other = await harness(d, '', ['close', 'helper'], { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 'another-session' })
+ expect(other.code).toBe(1)
+ const closed = await run('close', 'helper')
+ expect(closed.code, closed.err).toBe(0)
+ client.close()
+ })
})
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 671f56292..e6ab0b43e 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -25,7 +25,7 @@
// (Claude Code) works on after its first stop because the /goal hook refused it (`!goalpause <condition>`:
// refused, and the goal paused with no further output), `!compactmid` compacts in the
// middle of a turn as an automatic compaction does, `!version` answers with the version this
-// process is, `!env <prefix>` with the names of the variables in its environment that start with the
+// process is, `!env <prefix>[,<prefix>…]` with the names of the variables in its environment that start with a
// prefix (never their values), as an agent that reads its own environment can, `!goal` and `!goal done`
// (Codex) start and achieve a goal the way Codex 0.160 shows one under its composer, `!browse` (Codex) leaves Codex browsing its transcript in its default fullscreen
// mode, and `!browse scrollback` in its scrollback mode, `!transcript` (Claude Code) leaves it in its
@@ -1452,7 +1452,8 @@ export async function run(engine, config = {}, { native = false } = {}) {
}
if (directive?.[1] === 'version') { await finish(versionLine); return }
if (directive?.[1] === 'env') {
- const names = Object.keys(process.env).filter((name) => name.startsWith(directive[2])).sort()
+ const prefixes = directive[2].split(',').filter(Boolean)
+ const names = Object.keys(process.env).filter((name) => prefixes.some((prefix) => name.startsWith(prefix))).sort()
await finish(`env ${directive[2]}: ${names.join(',') || '(none)'}`)
return
}
diff --git a/cli/e2e/paneEnv.e2e.ts b/cli/e2e/paneEnv.e2e.ts
index cd6a6496c..13314f98c 100644
--- a/cli/e2e/paneEnv.e2e.ts
+++ b/cli/e2e/paneEnv.e2e.ts
@@ -1,5 +1,6 @@
/**
- * What a pane is started with, end to end: never harnessd's own variables. The master gives the core and
+ * What a pane is started with, end to end: never harnessd's own variables, nor the session of an agent whose shell
+ * started the daemon (lib/agentSessionEnv.ts). The master gives the core and
* each service the `HARNESSD_*` they run by, the service token among them. The tmux server the core
* started copied them into every pane it made, so every agent, terminal tile and hook had them all (found
* 2026-10-11: `env` in an agent's pane listed every one). The core now takes them out of its
@@ -40,28 +41,37 @@ async function create(d: IsolatedDaemon, client: LocalClient, engine: Engine | '
}, 60_000, 500)
}
-/** The `HARNESSD_*` names an agent's engine has, asked as an agent reads its environment (fakeEngine `!env`). */
-async function engineHas(client: LocalClient, agentId: string): Promise<string> {
+/** An agent's own session, as Claude Code and Codex set it in the shells they run commands in: made-up values. */
+const AGENT_SESSION = {
+ AI_AGENT: 'claude-code_2-1-296_agent', CLAUDECODE: '1', CLAUDE_CODE_MESSAGING_TOKEN: 'agent-token', CLAUDE_CODE_SESSION_ID: 'agent-session',
+ CODEX_THREAD_ID: 'agent-thread',
+}
+const HARNESSD = 'HARNESSD_'
+const SESSION = 'AI_AGENT,CLAUDECODE,CLAUDE_CODE_MESSAGING,CLAUDE_CODE_SESSION,CODEX_THREAD'
+
+/** The names an agent's engine has that start with [prefixes], asked as an agent reads its environment (fakeEngine `!env`). */
+async function engineHas(client: LocalClient, agentId: string, prefixes = HARNESSD): Promise<string> {
const ended = client.next(isTurn('turn_ended', agentId), 45_000, 'turn_ended (!env)')
- client.send('message', { agentId, content: '!env HARNESSD_' })
+ client.send('message', { agentId, content: `!env ${prefixes}` })
await ended
const { sessionId } = (await row(client, agentId))!
return until('the !env answer in the thread', async () => {
const page = await client.request<{ events?: Array<{ type: string; payload: Record<string, any> }> }>('session_get', { sessionId, limit: 200 }, 30_000)
const answer = (page.events ?? []).filter((event) => event.type === 'text_delta').map((event) => String(event.payload.content))
- .find((text) => text.startsWith('env HARNESSD_: '))
- return answer?.slice('env HARNESSD_: '.length) ?? null
+ .find((text) => text.startsWith(`env ${prefixes}: `))
+ return answer?.slice(`env ${prefixes}: `.length) ?? null
}, 15_000, 250)
}
-/** The `HARNESSD_*` names in the environment of the shell a pane runs, written to a file by that shell. */
-async function shellHas(d: IsolatedDaemon, pane: string, name: string): Promise<string[]> {
+/** The names starting with [prefixes] in the environment of the shell a pane runs, written to a file by that shell. */
+async function shellHas(d: IsolatedDaemon, pane: string, name: string, prefixes = HARNESSD): Promise<string[]> {
const file = join(d.root, `${name}.env`)
await d.tmux.run('send-keys', '-t', pane, `env > ${file}.tmp && mv ${file}.tmp ${file}`, 'Enter')
await until(`${name}'s shell to write its environment`, () => existsSync(file) || null, 20_000, 100)
- return names(readFileSync(file, 'utf8'))
+ return names(readFileSync(file, 'utf8'), prefixes)
}
-const names = (env: string): string[] => env.split('\n').map((line) => line.split('=')[0]).filter((name) => name.startsWith('HARNESSD_')).sort()
+const names = (env: string, prefixes = HARNESSD): string[] =>
+ env.split('\n').map((line) => line.split('=')[0]).filter((name) => prefixes.split(',').some((prefix) => name.startsWith(prefix))).sort()
describe('a pane\'s environment', () => {
let daemon: IsolatedDaemon | undefined
@@ -74,14 +84,14 @@ describe('a pane\'s environment', () => {
return d
}
- /** Every kind of pane the daemon makes: Claude Code, Codex and a terminal tile, each without harnessd's variables. */
- const expectNoneIn = async (d: IsolatedDaemon, client: LocalClient): Promise<void> => {
+ /** Every kind of pane the daemon makes: Claude Code, Codex and a terminal tile, each without the variables. */
+ const expectNoneIn = async (d: IsolatedDaemon, client: LocalClient, prefixes = HARNESSD): Promise<void> => {
for (const engine of ['claude', 'codex'] as const) {
const agent = await create(d, client, engine, `pane-${engine}`)
- expect(await engineHas(client, agent.id), engine).toBe('(none)')
+ expect(await engineHas(client, agent.id, prefixes), engine).toBe('(none)')
}
const tile = await create(d, client, 'terminal', 'pane-terminal')
- expect(await shellHas(d, tile.tmuxPane, 'terminal')).toEqual([])
+ expect(await shellHas(d, tile.tmuxPane, 'terminal', prefixes)).toEqual([])
}
it('has none of harnessd\'s variables when the daemon started the tmux server, under a master that gave the core them', async () => {
@@ -109,4 +119,18 @@ describe('a pane\'s environment', () => {
await expectNoneIn(d, client)
client.close()
}, 300_000)
+
+ it('has none of an agent\'s session when that agent\'s shell started the daemon and the tmux server', async () => {
+ // An agent that installs Harness runs `harness start` from its shell: the master, and a tmux server started
+ // from that shell, have that agent's session, and every pane would have looked like that agent's.
+ const d = await IsolatedDaemon.create({ env: AGENT_SESSION })
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ await exec('tmux', ['-S', d.tmux.socket, 'new-session', '-d', '-s', 'agent-shell', '/bin/sh', '-c', 'sleep 600'], { env: d.env, timeout: 10_000 })
+ await d.start()
+ expect(d.log()).toContain(`[terminal] tmux: removed ${Object.keys(AGENT_SESSION).sort().join(', ')} from the environment new panes start with`)
+ const client = await LocalClient.connect(d)
+ await expectNoneIn(d, client, SESSION)
+ client.close()
+ }, 300_000)
})
diff --git a/cli/src/agentClient/commands.spec.ts b/cli/src/agentClient/commands.spec.ts
index e02be7e69..60fdda250 100644
--- a/cli/src/agentClient/commands.spec.ts
+++ b/cli/src/agentClient/commands.spec.ts
@@ -62,7 +62,7 @@ function harness(daemon: FakeDaemon, over: Partial<ClientDeps> & { others?: Reco
const out: string[] = [], err: string[] = []
let clock = NOW
const deps: ClientDeps = {
- pane: '%lead', where: () => where,
+ pane: '%lead', env: {}, where: () => where,
open: async (_w, machineId) => {
if (!machineId || machineId === 'm') return daemon
const other = over.others?.[machineId]
@@ -98,6 +98,16 @@ describe('harness ps', () => {
expect(d.closed).toBe(true)
})
+ it('tells an agent outside Harness that it is one', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('kid')]
+ const h = harness(d, { pane: undefined, env: { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 'S1' } })
+ h.ledger.append({ at: NOW, depth: 1, by: { machineId: 'm', agentId: 'claude-code:S1', name: 'Claude Code', engine: 'claude' }, child: { machineId: 'm', agentId: 'kid', name: 'kid' } })
+ expect(await psCommand([], h.deps)).toBe(EXIT.ok)
+ expect(h.out[0].split('\n')[0]).toBe('You are Claude Code, outside Harness.')
+ expect(h.out[0]).toMatch(/\nkid +Codex +\w+ +you /)
+ })
+
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' })]
@@ -489,6 +499,22 @@ describe('harness close', () => {
expect(await closeCommand(['theirs'], harness(d, { pane: '%own' }).deps)).toBe(EXIT.ok)
})
+ it('lets an agent outside Harness close only what its session started', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('mine'), frame('theirs'), frame('sh', { engine: 'terminal', tmuxPane: '%sh' })]
+ const h = harness(d, { pane: undefined, env: { CODEX_THREAD_ID: 'T1' } })
+ h.ledger.append({ at: NOW, depth: 1, by: { machineId: 'm', agentId: 'codex:T1', name: 'Codex', engine: 'codex' }, child: { machineId: 'm', agentId: 'mine', name: 'mine' } })
+ expect(await closeCommand(['theirs'], h.deps)).toBe(EXIT.failed)
+ expect(h.err[0]).toBe('You did not start theirs, so you may not close it. Only the person can.')
+ expect(await closeCommand(['mine'], h.deps)).toBe(EXIT.ok)
+ // Another session of the same agent did not start it.
+ const other = harness(d, { pane: undefined, env: { CODEX_THREAD_ID: 'T2' } })
+ expect(await closeCommand(['mine'], other.deps)).toBe(EXIT.failed)
+ // From a person's terminal in Harness: still the agent its shell names.
+ const inTile = harness(d, { pane: '%sh', env: { AI_AGENT: 'cursor_1-2_agent' }, where: () => ({ ...where, harnessPane: true }) })
+ expect(await closeCommand(['theirs'], inTile.deps)).toBe(EXIT.failed)
+ })
+
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')]
@@ -527,7 +553,7 @@ describe('harness new, run by an agent', () => {
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/)
+ await expect(unknown.check()).rejects.toThrow(/could not tell who is starting this/)
})
it('refuses from what is left of an agent whose harness is gone', async () => {
@@ -568,6 +594,25 @@ describe('harness new, run by an agent', () => {
expect(addressOf({ machineId: 'm', agentId: 'abcdef123456', name: 'x'.repeat(41), engine: 'claude' })).toBe('abcdef12')
})
+ it('gives an agent outside Harness its limits and a header, records it by its session, and leaves out the reply', async () => {
+ const d = new FakeDaemon()
+ d.frames = [frame('sh', { engine: 'terminal', tmuxPane: '%9' })]
+ const claude = { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 'S1' }
+ const h = harness(d, { pane: undefined, env: claude })
+ const origin = (await agentOrigin(h.deps))!
+ await expect(origin.check()).resolves.toBeUndefined()
+ expect(origin.prompt('review it', 'm')).toBe('[from Claude Code outside Harness · studio, the agent that started you. It reads your answer itself.]\n\nreview it')
+ expect(await origin.created('m', { id: 'kid', name: 'reviewer' })).toBeNull()
+ expect(h.ledger.all()).toEqual([{ at: NOW, depth: 1, by: { machineId: 'm', agentId: 'claude-code:S1', name: 'Claude Code', engine: 'claude' }, child: { machineId: 'm', agentId: 'kid', name: 'reviewer' } }])
+ // Nothing can message it: it has no pane.
+ expect(origin.next({ id: 'kid', name: 'reviewer' })).toBe('Read it: harness show reviewer · wait for it: harness wait reviewer')
+ // In a person's terminal in Harness, it is still that agent.
+ expect(await agentOrigin(harness(d, { pane: '%9', env: claude, where: () => ({ ...where, harnessPane: true }) }).deps)).not.toBeNull()
+ // The daemon did not answer: refused, never the person.
+ const down = (await agentOrigin(harness(d, { pane: undefined, env: claude, open: async () => { throw new Error('down') } }).deps))!
+ await expect(down.check()).rejects.toThrow(/could not tell who is starting this/)
+ })
+
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' })]
diff --git a/cli/src/agentClient/commands.ts b/cli/src/agentClient/commands.ts
index d89affe0e..eded45e87 100644
--- a/cli/src/agentClient/commands.ts
+++ b/cli/src/agentClient/commands.ts
@@ -22,10 +22,12 @@ 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'
+import { callerOf, clip, isAgent, lastTurn, matching, outsideCaller, rowsOf, stateOf, STOPPED_WITHIN_MS, type Caller, type Frame, type HistoryEvent, type Row, type State } from './model.js'
export interface ClientDeps {
pane?: string | undefined
+ /** The caller's environment: an agent outside Harness is told by what it sets there (`outsideCaller`). */
+ env?: NodeJS.ProcessEnv
where?: () => Where
open?: (where: Where, machineId?: string) => Promise<Daemon>
ledger?: (dataDir: string) => Ledger
@@ -83,6 +85,7 @@ interface Opened {
function setup(deps: ClientDeps) {
return {
pane: 'pane' in deps ? deps.pane : process.env.TMUX_PANE,
+ env: deps.env ?? process.env,
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))),
@@ -120,11 +123,13 @@ async function opened(s: Setup, includeStopped = false): Promise<Opened> {
const daemon = await s.open(where)
try {
const frames = await list(daemon, includeStopped)
- const caller = callerOf(frames, s.pane, where.machineId)
+ const inPane = 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
+ const orphan = !!s.pane && !!where.harnessPane && !inPane && !terminal
+ // Not a harness: an agent outside Harness when its shell says so, even in a terminal of Harness's own.
+ const caller = inPane ?? (orphan ? null : outsideCaller(s.env, where.machineId))
return { where, daemon, frames, caller, orphan, stopped: includeStopped, ledger: s.ledger(where.dataDir), machine: machineNameOf(where.dataDir) }
} catch (error) { daemon.close(); throw error }
}
@@ -271,7 +276,8 @@ export function formatRows(rows: Row[], caller: Caller | null, now: number): str
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')
+ const you = !caller ? null : caller.outside ? `You are ${caller.name}, outside Harness.` : `You are "${caller.name}" (${caller.agentId.slice(0, 8)}).`
+ return [you, head, ...lines].filter((l) => l !== null).join('\n')
}
export function psCommand(argv: readonly string[], deps: ClientDeps = {}): Promise<number> {
@@ -530,16 +536,17 @@ const refusing = (code: string, message: string): NewOrigin => ({
})
/**
- * 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).
+ * When an agent runs `harness new`, from its pane or from outside Harness: 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
+ const agentOutside = !!outsideCaller(s.env, '')
+ if (!s.pane && !agentOutside) 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
+ return s.where().harnessPane || agentOutside ? refusing('UNKNOWN_CALLER', 'Harness could not tell who is starting this. Try again in a moment.') : null
}
o.daemon.close()
if (o.orphan) return refusing('NOT_YOURS', ORPHAN)
@@ -555,9 +562,12 @@ export async function agentOrigin(deps: ClientDeps = {}, record: Rpc = messagesR
// 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`
+ // back as a message as well, which would land in the middle of the starter's own turn. An agent outside Harness
+ // has no pane for a message to reach.
+ const reply = here && !caller.outside ? ` It reads your answer itself; to ask it something while you work: harness send ${addressOf(caller)} "…"` : ' It reads your answer itself.'
+ const header = caller.outside
+ ? `[from ${caller.name} outside Harness · ${o.machine}, the agent that started you.${reply}]\n\n`
+ : `[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.
@@ -594,7 +604,7 @@ export async function agentOrigin(deps: ClientDeps = {}, record: Rpc = messagesR
},
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} "…"`
+ return `Read it: harness show ${at} · wait for it: harness wait ${at}${caller.outside ? '' : ` · message it: harness send ${at} "…"`}`
},
}
}
diff --git a/cli/src/agentClient/model.spec.ts b/cli/src/agentClient/model.spec.ts
index 750c954a8..aafaec464 100644
--- a/cli/src/agentClient/model.spec.ts
+++ b/cli/src/agentClient/model.spec.ts
@@ -3,7 +3,7 @@ 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'
+import { callerOf, clip, lastTurn, matching, outsideCaller, rowsOf, stateOf, STOPPED_WITHIN_MS, type Frame } from './model.js'
const dirs: string[] = []
const ledger = (): Ledger => {
@@ -44,6 +44,18 @@ describe('a harness as the agent verbs show it', () => {
expect(callerOf([frame('abcdefghij', { name: '', tmuxPane: '%7' })], '%7', 'm')?.name).toBe('abcdefgh')
})
+ it('knows an agent outside Harness by what it sets in its shell, one caller a session', () => {
+ expect(outsideCaller({}, 'm')).toBeNull()
+ expect(outsideCaller({ CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: ' S1 ', AI_AGENT: 'claude-code_2-1-296_agent' }, 'm'))
+ .toEqual({ machineId: 'm', agentId: 'claude-code:S1', name: 'Claude Code', engine: 'claude', outside: true })
+ expect(outsideCaller({ CODEX_THREAD_ID: 'T1' }, 'm')).toEqual({ machineId: 'm', agentId: 'codex:T1', name: 'Codex', engine: 'codex', outside: true })
+ // An agent that names only itself is one caller for every session of it.
+ expect(outsideCaller({ AI_AGENT: 'cursor_1-2_agent' }, 'm')).toEqual({ machineId: 'm', agentId: 'agent:cursor', name: 'cursor', engine: 'cursor', outside: true })
+ expect(outsideCaller({ CLAUDECODE: '1' }, 'm')).toMatchObject({ agentId: 'agent:claude-code', name: 'Claude Code', engine: 'claude' })
+ expect(outsideCaller({ CLAUDECODE: '0', CLAUDE_CODE_SESSION_ID: 'S1' }, 'm')).toBeNull()
+ expect(outsideCaller({ AI_AGENT: ' ' }, 'm')).toBeNull()
+ })
+
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' } })
diff --git a/cli/src/agentClient/model.ts b/cli/src/agentClient/model.ts
index 13b23ff0a..0b5cdbd56 100644
--- a/cli/src/agentClient/model.ts
+++ b/cli/src/agentClient/model.ts
@@ -20,8 +20,14 @@ export interface Frame {
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 }
+/** The agent running the verb: a harness in its own pane, or an agent outside Harness. Null for a person at a terminal. */
+export interface Caller extends LedgerMember {
+ name: string
+ engine: string
+ /** An agent Harness did not start (in a terminal app, an editor, the person's own tmux): no pane, so nothing can
+ * message it, and it is told apart by the session its shell names. */
+ outside?: boolean
+}
export type State = 'working' | 'idle' | 'needs-input' | 'stopped' | 'offline' | 'unknown'
@@ -71,6 +77,24 @@ export function callerOf(frames: Frame[], pane: string | undefined, machineId: s
return { machineId, agentId: frame.id, name: frame.name || frame.id.slice(0, 8), engine: frame.engine ?? '' }
}
+/**
+ * The agent outside Harness whose shell runs this, as the agent marks the shells it runs commands in: Claude Code sets
+ * CLAUDECODE and its session's id, Codex its thread's id, and others AI_AGENT. Taken for the person, an agent from
+ * outside had no limits and could close every harness on the machine. One session is one caller, so what one Claude
+ * Code session started another may not close; an agent that names only itself (AI_AGENT) is one caller for all its
+ * sessions.
+ */
+export function outsideCaller(env: NodeJS.ProcessEnv, machineId: string): Caller | null {
+ const claude = env.CLAUDECODE === '1' ? env.CLAUDE_CODE_SESSION_ID?.trim() : ''
+ if (claude) return { machineId, agentId: `claude-code:${claude}`, name: 'Claude Code', engine: 'claude', outside: true }
+ const codex = env.CODEX_THREAD_ID?.trim()
+ if (codex) return { machineId, agentId: `codex:${codex}`, name: 'Codex', engine: 'codex', outside: true }
+ // "claude-code_2-1-296_agent": the agent's name, then its version.
+ const named = (env.AI_AGENT?.trim() || (env.CLAUDECODE === '1' ? 'claude-code' : '')).split('_')[0].slice(0, 40)
+ if (!named) return null
+ return { machineId, agentId: `agent:${named}`, name: named === 'claude-code' ? 'Claude Code' : named, engine: named === 'claude-code' ? 'claude' : named, outside: true }
+}
+
export interface RowContext {
machineId: string
machine: string
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 19cb45a8c..71ba736ce 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -57,6 +57,7 @@ import { awakeTimeout } from '../lib/sleepAware.js'
import { removePidFileIf, onError } from '../lib/daemonLaunch.js'
import { ensureTmuxOnPath } from '../lib/tmuxOnPath.js'
import { harnessdEnv, holdHarnessdEnv, isHarnessdVariable } from '../lib/harnessdEnv.js'
+import { dropAgentSessionEnv, isAgentSessionVariable } from '../lib/agentSessionEnv.js'
import { AUTH_DIR, AuthSessionManager, clearAuthSession, ensureSignInEpoch, readAuthSession, signInOf, type AuthSession } from '../lib/authSession.js'
import { ENGINES, enginePathOverride } from '../lib/engineBin.js'
import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
@@ -557,8 +558,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
console.log(`[terminal] renamed tmux session ${adopted.from} → ${adopted.to} (pane ${adopted.paneId}) · named by a build before the harness- prefix`)
}
// Before the first pane this boot makes or restarts: a server an earlier core started still has that
- // core's HARNESSD_* (the service token among them) in the environment it gives every new pane.
- const forgotten = await tmuxBackend.unsetServerEnvironment(isHarnessdVariable)
+ // core's HARNESSD_* (the service token among them) in the environment it gives every new pane, and one
+ // started from an agent's shell that agent's session (lib/agentSessionEnv.ts).
+ const forgotten = await tmuxBackend.unsetServerEnvironment((name) => isHarnessdVariable(name) || isAgentSessionVariable(name))
if (forgotten.length) console.log(`[terminal] tmux: removed ${forgotten.join(', ')} from the environment new panes start with`)
const tmuxStartup = await tmuxBackend.inventory()
console.log(tmuxStartup.state === 'available'
@@ -2771,6 +2773,7 @@ export function runCore(scriptPath: string): void {
// First, before anything this core starts can inherit them: a tmux server, an engine, a shell
// (lib/harnessdEnv.ts).
holdHarnessdEnv()
+ dropAgentSessionEnv()
SCRIPT_PATH = scriptPath
// Inert unless the end-to-end suite asks for its event loop to be held (core/stall.ts).
startStalls(testFaults(harnessdEnv().HARNESSD_TEST_FAULTS))
@@ -2781,6 +2784,7 @@ export function runCore(scriptPath: string): void {
/** `harness start -f` with `HARNESS_NO_MASTER=1`, and a start under tsx: the core alone, in the process of the command that asked for it. */
export function runCoreInForeground(session: AuthSession | null, scriptPath: string): Promise<void> {
holdHarnessdEnv()
+ dropAgentSessionEnv()
SCRIPT_PATH = scriptPath
return runForeground(session)
}
diff --git a/cli/src/lib/agentSessionEnv.spec.ts b/cli/src/lib/agentSessionEnv.spec.ts
new file mode 100644
index 000000000..02f8ae986
--- /dev/null
+++ b/cli/src/lib/agentSessionEnv.spec.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest'
+import { dropAgentSessionEnv, isAgentSessionVariable } from './agentSessionEnv.js'
+
+describe('an agent session\'s variables', () => {
+ it('are the ones naming the session, never a setting the person chose', () => {
+ for (const name of ['CLAUDECODE', 'CLAUDE_CODE_SESSION_ID', 'CLAUDE_CODE_MESSAGING_TOKEN', 'CODEX_THREAD_ID', 'AI_AGENT']) expect(isAgentSessionVariable(name), name).toBe(true)
+ for (const name of ['CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'HARNESSD_SERVICE_TOKEN', 'PATH']) expect(isAgentSessionVariable(name), name).toBe(false)
+ })
+
+ it('are taken out of an environment, which says which', () => {
+ const env: NodeJS.ProcessEnv = { PATH: '/bin', CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's', CODEX_HOME: '/c' }
+ expect(dropAgentSessionEnv(env)).toEqual(['CLAUDECODE', 'CLAUDE_CODE_SESSION_ID'])
+ expect(env).toEqual({ PATH: '/bin', CODEX_HOME: '/c' })
+ expect(dropAgentSessionEnv(env)).toEqual([])
+ })
+})
diff --git a/cli/src/lib/agentSessionEnv.ts b/cli/src/lib/agentSessionEnv.ts
new file mode 100644
index 000000000..19658f10b
--- /dev/null
+++ b/cli/src/lib/agentSessionEnv.ts
@@ -0,0 +1,31 @@
+/**
+ * The variables a coding agent sets in the shells it runs commands in, naming its own session: Claude Code's
+ * CLAUDECODE, session id and messaging socket and token, Codex's thread id and sandbox, and the AI_AGENT others set.
+ *
+ * They belong to that one session. An agent that installs Harness and runs `harness start` from its shell started a
+ * daemon with them all (found 2026-10-11: the core of a daemon restarted from a Claude Code session had four), and a
+ * tmux server that daemon starts hands its environment to every pane: every harness would have looked like that one
+ * agent's session (agentClient/model.ts `outsideCaller`), and had its messaging token. So the master takes them out
+ * of its environment before it starts anything (masterProcess.ts), the core does too, for a core started without a
+ * master, and the core removes them from a tmux server's environment as it removes harnessd's own (core/main.ts).
+ *
+ * A setting the person chose (CLAUDE_CODE_USE_BEDROCK, CODEX_HOME, …) is not a session's, and stays.
+ */
+const AGENT_SESSION_VARIABLES: ReadonlySet<string> = new Set([
+ 'AI_AGENT',
+ 'CLAUDECODE', 'CLAUDE_PID', 'CLAUDE_CODE_ENTRYPOINT', 'CLAUDE_CODE_SESSION_ID', 'CLAUDE_CODE_CHILD_SESSION',
+ 'CLAUDE_CODE_SESSION_ATTENDED', 'CLAUDE_CODE_EXECPATH', 'CLAUDE_CODE_MESSAGING_SOCKET', 'CLAUDE_CODE_MESSAGING_TOKEN',
+ 'CODEX_THREAD_ID', 'CODEX_CI', 'CODEX_SANDBOX', 'CODEX_SANDBOX_NETWORK_DISABLED', 'CODEX_ESCALATE_SOCKET',
+])
+
+/** Whether [name] names an agent's own session, never for a daemon or a pane it makes. */
+export function isAgentSessionVariable(name: string): boolean {
+ return AGENT_SESSION_VARIABLES.has(name)
+}
+
+/** Takes every agent session variable out of [env], this process's own by default. Says which it took. */
+export function dropAgentSessionEnv(env: NodeJS.ProcessEnv = process.env): string[] {
+ const dropped = Object.keys(env).filter(isAgentSessionVariable)
+ for (const name of dropped) delete env[name]
+ return dropped
+}
diff --git a/cli/src/masterProcess.ts b/cli/src/masterProcess.ts
index 46735ef1b..e6cfdbe14 100644
--- a/cli/src/masterProcess.ts
+++ b/cli/src/masterProcess.ts
@@ -16,6 +16,7 @@ import { env } from './config/env.js'
import { processExecve, probeMaster, runMaster, type Execve } from './harnessd/master.js'
import { baseNode, namedNode } from './harnessd/processName.js'
import { PROBE_ANSWER, PROBE_TIMEOUT_MS } from './harnessd/reexec.js'
+import { dropAgentSessionEnv } from './lib/agentSessionEnv.js'
import { ensureUtf8Locale } from './lib/childLocale.js'
import { DAEMON_LOG_FILE, HARNESSD_STATUS_FILE, PID_FILE } from './lib/daemonState.js'
import { isInstalledCopy } from './lib/installedCopy.js'
@@ -70,6 +71,9 @@ export function startMaster(start: MasterStart, exit: (code: number) => void = (
// core and the services inherit this environment (lib/childLocale.ts). launchd and systemd start the
// master with no `harness start` before it to have set it.
ensureUtf8Locale()
+ // And the session of the agent whose shell ran `harness start`, which every pane would otherwise have
+ // (lib/agentSessionEnv.ts).
+ dropAgentSessionEnv()
const { serviceScriptPath } = start
return runMaster({
env: masterEnv(process.env, localSocketPath(env.ADAPTER_DATA_DIR, env.PORT)),
diff --git a/cli/src/testing/daemonEnvironment.spec.ts b/cli/src/testing/daemonEnvironment.spec.ts
index 51d3b4d27..e9a602006 100644
--- a/cli/src/testing/daemonEnvironment.spec.ts
+++ b/cli/src/testing/daemonEnvironment.spec.ts
@@ -14,4 +14,8 @@ describe('a daemon under test', () => {
PATH: '/test/bin', HOME: '/test/home', HARNESSD_SERVICES: 'edge',
})
})
+ it('does not borrow the session of an agent running the tests', () => {
+ expect(daemonEnvironment({ PATH: '/test/bin', CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's', CODEX_THREAD_ID: 't', CLAUDE_CODE_USE_BEDROCK: '1' }, {}))
+ .toEqual({ PATH: '/test/bin', CLAUDE_CODE_USE_BEDROCK: '1' })
+ })
})
diff --git a/cli/src/testing/daemonEnvironment.ts b/cli/src/testing/daemonEnvironment.ts
index 1a4f371b5..e3c076d86 100644
--- a/cli/src/testing/daemonEnvironment.ts
+++ b/cli/src/testing/daemonEnvironment.ts
@@ -1,5 +1,11 @@
-/** A test daemon starts its own supervisor; it must not inherit the host daemon's topology or token. */
+import { isAgentSessionVariable } from '../lib/agentSessionEnv.js'
+
+/**
+ * A test daemon starts its own supervisor; it must not inherit the host daemon's topology or token, nor the session of
+ * an agent running the tests: its harnesses would all look like that agent (agentClient/model.ts `outsideCaller`), and
+ * only on the developer's machine, never in CI.
+ */
export function daemonEnvironment(inherited: NodeJS.ProcessEnv, own: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
- const clean = Object.fromEntries(Object.entries(inherited).filter(([key]) => !key.startsWith('HARNESSD_')))
+ const clean = Object.fromEntries(Object.entries(inherited).filter(([key]) => !key.startsWith('HARNESSD_') && !isAgentSessionVariable(key)))
return { ...clean, ...own }
}
diff --git a/docs/design/2026-10-11-agent-client.md b/docs/design/2026-10-11-agent-client.md
index 9f5ebf228..17fbe732e 100644
--- a/docs/design/2026-10-11-agent-client.md
+++ b/docs/design/2026-10-11-agent-client.md
@@ -102,6 +102,30 @@ The reply address is the name when it is a plain word or two, else the start of
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,").
+### Agents outside Harness
+
+Most agents do not run in a harness: Claude Code or Codex in a terminal app, an editor, or the person's own tmux.
+With no harness pane to tell them by, they were the person, with no limits and the right to close every harness.
+They are told by what they set in the shells they run commands in: `CLAUDECODE=1` and `CLAUDE_CODE_SESSION_ID`
+(Claude Code), `CODEX_THREAD_ID` (Codex), `AI_AGENT` (others; one caller for all of that agent's sessions). One
+session is one caller in the record (`claude-code:<session>`), with the limits and the header a harness gets:
+
+```
+[from Claude Code outside Harness · studio, the agent that started you. It reads your answer itself.]
+```
+
+It may close only what its session started. Nothing can message it, having no pane, so neither the header nor
+`new` tells anyone to. A person who runs `harness` through their agent (Claude Code's `!`) is that agent here; a
+plain terminal is the person.
+
+An agent that installs Harness starts the daemon from its shell, and a tmux server the daemon starts hands its
+environment to every pane: every harness would have been that agent's session, with its messaging token. The
+master and the core drop those variables before they start anything, and the core removes them from a tmux
+server's environment as it removes harnessd's own (`lib/agentSessionEnv.ts`).
+
+Signed out, all of this works: the daemon runs as this computer, and `harness new` now asks for that identity as
+`harness start` does (#1183). It used to read the sign-in file alone and refuse.
+
## Limits
Spawning is cheap, so runaway spawning is the risk (the Jev loops cost $60 at one caller). Every limit refuses