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.

In a sandbox, "Harness is running" only when its process is there (#1215)

Dee649aaa9356e4
diff --git a/cli/e2e/sandbox.e2e.ts b/cli/e2e/sandbox.e2e.ts
new file mode 100644
index 000000000..dbfbb4180
--- /dev/null
+++ b/cli/e2e/sandbox.e2e.ts
@@ -0,0 +1,101 @@
+/**
+ * `harness` in an agent's sandbox, with a daemon that runs and with none (lib/unreachable.ts).
+ *
+ * Codex runs an agent's commands under seatbelt, marked CODEX_SANDBOX=seatbelt and CODEX_SANDBOX_NETWORK_DISABLED=1. In
+ * a clean-VM test of CLI 0.3.75 a Codex harness was told by `harness new` that Harness was not running, ran `harness
+ * start` (mkdir EPERM), and asked the person "May I start Harness?" for a Harness that was running (#1213). The sandbox
+ * here is sandbox-exec with the refusals `codex sandbox` 0.162.1 was measured making on 2026-10-11: a signal to the
+ * daemon (kill EPERM), a connect to its socket or its port, or to a port nobody listens on (EPERM), a write in its data
+ * folder (mkdir EPERM). With nothing running, the same sandbox must not be told Harness runs. macOS only.
+ */
+import { spawn } from 'node:child_process'
+import { existsSync, mkdirSync, readFileSync, realpathSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { NOT_RUNNING, SANDBOXED, START_OUTSIDE } from '../src/lib/unreachable.js'
+import { CLI_ROOT, IsolatedDaemon } from './harness/daemon.js'
+
+const SANDBOX_EXEC = '/usr/bin/sandbox-exec'
+
+/** Codex's seatbelt, as far as `harness` meets it: no signal outside the sandbox, no network, no writes in the data folder. */
+const policy = (dataDir: string) => [
+ '(version 1)',
+ '(allow default)',
+ '(deny network-outbound (remote ip) (remote unix-socket))',
+ '(deny signal)',
+ '(allow signal (target same-sandbox))',
+ `(deny file-write* (subpath ${JSON.stringify(realpathSync(dataDir))}))`,
+].join('')
+
+/** `harness <args>` as Codex runs it from its shell tool: sandboxed unless [outside], marked as Codex marks it. */
+function harness(d: IsolatedDaemon, args: string[], outside = false): Promise<{ code: number; out: string; err: string }> {
+ const cli = [process.execPath, '--import', 'tsx', 'src/cli.ts', ...args]
+ const [command, ...argv] = outside ? cli : [SANDBOX_EXEC, '-p', policy(d.dataDir), ...cli]
+ return new Promise((done) => {
+ const child = spawn(command, argv, {
+ cwd: CLI_ROOT,
+ env: { ...d.env, TMUX_PANE: '', CODEX_THREAD_ID: 'e2e-codex-thread', ...(outside ? {} : { CODEX_SANDBOX: 'seatbelt', CODEX_SANDBOX_NETWORK_DISABLED: '1' }) },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let out = '', err = ''
+ child.stdout.on('data', (chunk) => { out += chunk })
+ child.stderr.on('data', (chunk) => { err += chunk })
+ child.on('close', (code) => done({ code: code ?? -1, out, err }))
+ })
+}
+
+const pidIn = (d: IsolatedDaemon): string => existsSync(join(d.dataDir, 'adapter.pid')) ? readFileSync(join(d.dataDir, 'adapter.pid'), 'utf8').trim() : ''
+
+describe.skipIf(process.platform !== 'darwin' || !existsSync(SANDBOX_EXEC))('harness in an agent\'s sandbox', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+ it('says Harness runs and the sandbox is in the way, and never starts a second one; says not running only when it is not', 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 folder = join(d.projectsDir, 'opinion')
+ mkdirSync(folder, { recursive: true })
+
+ // Outside the sandbox (escalated), the verbs reach it.
+ const escalated = await harness(d, ['ps'], true)
+ expect(escalated.code, escalated.err).toBe(0)
+
+ // Sandboxed: running, and out of reach.
+ const ps = await harness(d, ['ps'])
+ expect(ps.code).toBe(1)
+ expect(ps.err.trim()).toBe(SANDBOXED)
+ const made = await harness(d, ['new', 'claude', folder, '--name', 'python-indent-opinion', '--json', '--', 'A second opinion, please.'])
+ expect(made.code).toBe(1)
+ expect(made.err.trim()).toBe(SANDBOXED)
+ const pid = pidIn(d)
+ const start = await harness(d, ['start'])
+ expect(start.code).toBe(1)
+ expect(start.err).toContain(SANDBOXED)
+ expect(start.err).not.toContain('EPERM')
+ // The daemon that runs is the one there was.
+ expect(pidIn(d)).toBe(pid)
+ const status = await harness(d, ['status'])
+ expect(status.out).toContain('out of reach')
+
+ // Nothing running: not "Harness is running", in the sandbox or out of it; start it, outside the sandbox.
+ await d.stop()
+ const outside = await harness(d, ['ps'], true)
+ expect(outside.err.trim()).toBe(NOT_RUNNING)
+ const down = await harness(d, ['ps'])
+ expect(down.code).toBe(1)
+ expect(down.err.trim()).toBe(START_OUTSIDE)
+ const downNew = await harness(d, ['new', 'claude', folder, '--name', 'python-indent-opinion', '--', 'A second opinion, please.'])
+ expect(downNew.code).toBe(1)
+ expect(downNew.err.trim()).toBe(START_OUTSIDE)
+ const downStart = await harness(d, ['start'])
+ expect(downStart.code).toBe(1)
+ expect(downStart.err).toContain(START_OUTSIDE)
+ expect(downStart.err).not.toContain('EPERM')
+ const status2 = await harness(d, ['status'])
+ expect(status2.out).toContain('○ stopped')
+ // No daemon was started from inside the sandbox.
+ expect(IsolatedDaemon.alive(Number(pidIn(d)) || null)).toBe(false)
+ })
+})
diff --git a/cli/src/agentClient/commands.spec.ts b/cli/src/agentClient/commands.spec.ts
index a963baa29..24762cb22 100644
--- a/cli/src/agentClient/commands.spec.ts
+++ b/cli/src/agentClient/commands.spec.ts
@@ -557,6 +557,16 @@ describe('harness new, run by an agent', () => {
await expect(unknown.check()).rejects.toThrow(/could not tell who is starting this/)
})
+ it('says the daemon is out of reach rather than "try again", which an agent did in the same sandbox', async () => {
+ const message = 'Harness is running, but a sandbox keeps this shell from reaching it.'
+ const unreachable = async () => { throw new AgentClientError('DAEMON_UNREACHABLE', message) }
+ // Codex outside Harness, and Codex in a pane Harness made: both run `harness new` sandboxed.
+ for (const over of [{ pane: undefined, env: { CODEX_THREAD_ID: 't' } }, { where: () => ({ ...where, harnessPane: true }) }]) {
+ const origin = (await agentOrigin(harness(new FakeDaemon(), { open: unreachable, ...over }).deps))!
+ await expect(origin.check()).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE', message })
+ }
+ })
+
it('refuses every agent when the person has turned agents starting agents off, and never the person', 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 b136de9ec..93d7a598a 100644
--- a/cli/src/agentClient/commands.ts
+++ b/cli/src/agentClient/commands.ts
@@ -563,7 +563,10 @@ export async function agentOrigin(deps: ClientDeps = {}, record: Rpc = messagesR
const agentOutside = !!outsideCaller(s.env, '')
if (!s.pane && !agentOutside) return null
let o: Opened
- try { o = await opened(s) } catch {
+ try { o = await opened(s) } catch (error) {
+ // Out of reach is said as it is (a sandbox, or nothing running): "try again in a moment" was tried again in the
+ // same sandbox.
+ if (error instanceof AgentClientError && error.code === 'DAEMON_UNREACHABLE') return refusing(error.code, error.message)
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()
diff --git a/cli/src/agentClient/daemon.spec.ts b/cli/src/agentClient/daemon.spec.ts
index 94119bce6..15aae7c37 100644
--- a/cli/src/agentClient/daemon.spec.ts
+++ b/cli/src/agentClient/daemon.spec.ts
@@ -1,6 +1,11 @@
import { EventEmitter } from 'node:events'
-import { describe, expect, it } from 'vitest'
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { openDaemon, type ClientSocket } from './daemon.js'
+import { localSocketPath } from '../lib/localSocket.js'
import { NOT_RUNNING, SANDBOXED } from '../lib/unreachable.js'
/** A socket whose connection fails with [code], as Codex's sandbox refuses the daemon's (2026-10-12). */
@@ -11,19 +16,46 @@ function failing(code: string): ClientSocket {
}
describe('a line to the daemon that cannot open', () => {
- const where = { port: 18473, dataDir: '/nowhere', machineId: 'm1' }
+ let dataDir: string
+ let saved: Record<string, string | undefined>
+ beforeEach(() => {
+ dataDir = mkdtempSync(join(tmpdir(), 'agent-daemon-'))
+ // The suite may itself run in Codex's sandbox; these cases are about the error and the pid file alone.
+ saved = { CODEX_SANDBOX: process.env.CODEX_SANDBOX, CODEX_SANDBOX_NETWORK_DISABLED: process.env.CODEX_SANDBOX_NETWORK_DISABLED }
+ delete process.env.CODEX_SANDBOX
+ delete process.env.CODEX_SANDBOX_NETWORK_DISABLED
+ })
+ afterEach(() => {
+ rmSync(dataDir, { recursive: true, force: true })
+ for (const [name, value] of Object.entries(saved)) if (value !== undefined) process.env[name] = value
+ })
+ const where = () => ({ port: 1, dataDir, machineId: 'm1' })
+ /** The pid file of the daemon the line is to: this test's own process, which exists. */
+ const running = () => writeFileSync(join(dataDir, 'adapter.pid'), `${process.pid}\n`)
it('says a sandbox keeps it out when the connection was not permitted, and never to start Harness', async () => {
- await expect(openDaemon(where, 'm1', () => failing('EPERM'))).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE', message: SANDBOXED })
+ running()
+ await expect(openDaemon(where(), 'm1', () => failing('EPERM'))).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE', message: SANDBOXED })
})
- it('says to start Harness when nothing answers', async () => {
- const saved = process.env.CODEX_SANDBOX
- delete process.env.CODEX_SANDBOX
+ it('says to start Harness when nothing answers, or when nothing is there behind a refusal', async () => {
+ running()
+ await expect(openDaemon(where(), 'm1', () => failing('ECONNREFUSED'))).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE', message: NOT_RUNNING })
+ // The pid file of the daemon the line is to decides: seatbelt refuses a port nobody listens on with EPERM too.
+ rmSync(join(dataDir, 'adapter.pid'))
+ await expect(openDaemon(where(), 'm1', () => failing('EPERM'))).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE', message: NOT_RUNNING })
+ })
+
+ // Root opens a socket whatever its mode, so the refusal cannot be made there.
+ it.skipIf(process.getuid?.() === 0)('reads a real refused socket as a sandbox\'s, through the real connect', async () => {
+ running()
+ const path = localSocketPath(dataDir, 1)!
+ const server = createServer((socket) => socket.end())
+ await new Promise<void>((done) => server.listen(path, done))
try {
- const error = await openDaemon(where, 'm1', () => failing('ECONNREFUSED')).catch((e: unknown) => e)
- expect([NOT_RUNNING, SANDBOXED]).toContain((error as Error).message)
- expect(error).toMatchObject({ code: 'DAEMON_UNREACHABLE' })
- } finally { if (saved !== undefined) process.env.CODEX_SANDBOX = saved }
+ // A socket this process may not open answers EACCES, as one a sandbox refuses does.
+ chmodSync(path, 0)
+ await expect(openDaemon(where())).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE', message: SANDBOXED })
+ } finally { await new Promise((done) => server.close(done)) }
})
})
diff --git a/cli/src/agentClient/daemon.ts b/cli/src/agentClient/daemon.ts
index 8d9aafaf3..46b7ef814 100644
--- a/cli/src/agentClient/daemon.ts
+++ b/cli/src/agentClient/daemon.ts
@@ -76,7 +76,7 @@ export function openDaemon(where: Where, machineId: string = where.machineId, co
waiting.clear()
if (!ready) rejectOpen(error)
}
- socket.on('error', (error) => failAll(new AgentClientError('DAEMON_UNREACHABLE', daemonUnreachableText(error))))
+ socket.on('error', (error) => failAll(new AgentClientError('DAEMON_UNREACHABLE', daemonUnreachableText(error, where.dataDir))))
socket.on('close', (code) => failAll(code === 4404
? new AgentClientError('NO_PEER_LINK', 'That machine is not linked to this one. Run `harness link` first.')
: new AgentClientError('DISCONNECTED', 'The connection to Harness closed.')))
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 9eb0e8fef..976df95c5 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -30,7 +30,7 @@ import { runCoreInForeground } from './core/main.js'
import { startCoreProcess } from './coreProcess.js'
import { GRID_MINT_TIMEOUT_MS, backendHttpBase, requestJson, postJson, controlPlaneAuth } from './lib/controlPlane.js'
import { LEGACY_LOG_FILE, MACHINE_NAME_FILE, tildify, computerId, thisDeviceLabel, DAEMON_LOG_FILE, HARNESSD_STATUS_FILE, daemonPort, isAlive, isDaemonRunning, readPid, daemonUnreachableText } from './lib/daemonState.js'
-import { SANDBOXED, sandboxed } from './lib/unreachable.js'
+import { sandboxed, startRefusalText } from './lib/unreachable.js'
import { onError, BIND_WAIT_MS, connectFailure, defaultLaunchDeps, waitForBind } from './lib/daemonLaunch.js'
import { ensureUtf8Locale } from './lib/childLocale.js'
import { buildLogBundle, bundleFileName, redactSecretsInText } from './lib/logBundle.js'
@@ -1034,8 +1034,10 @@ async function startCommand(foreground: boolean, repair: boolean = false): Promi
onWaiting: (owner) => console.log(` the daemon is ${describeSpawnLockOwner(owner)} — waiting for it to finish…`),
}).catch((error: unknown) => {
// A sandbox refuses the spawn lock (EPERM): Harness may well be running, out of this shell's reach, and an
- // agent that read a stack trace here asked the person to let it start Harness (lib/unreachable.ts).
- if (sandboxed({ error })) { console.error(`\n✗ ${SANDBOXED}\n`); process.exit(1) }
+ // agent that read a stack trace here asked the person to let it start Harness (lib/unreachable.ts). With none
+ // running, it is told to start Harness outside the sandbox rather than that Harness runs.
+ const refusal = startRefusalText({ error, pid: readPid() })
+ if (refusal) { console.error(`\n✗ ${refusal}\n`); process.exit(1) }
if (!(error instanceof SpawnLockBusyError)) throw error
console.error(`\n✗ Could not start: the daemon spawn lock is ${describeSpawnLockFailure(error)}.`)
console.error(' check harness status · stop it harness stop')
diff --git a/cli/src/lib/daemonState.ts b/cli/src/lib/daemonState.ts
index d67a5f829..4bb204794 100644
--- a/cli/src/lib/daemonState.ts
+++ b/cli/src/lib/daemonState.ts
@@ -13,7 +13,7 @@ import { env } from '../config/env.js'
import { hasAuthSession } from './authSession.js'
import { readOrMintComputerId } from './computerIdentity.js'
import { savedDaemonPort } from './daemonEndpoint.js'
-import { unreachableText } from './unreachable.js'
+import { pidIn, unreachableText } from './unreachable.js'
export const PID_FILE = join(env.ADAPTER_DATA_DIR, 'adapter.pid')
/** The daemon's console: the master's and its core's stdout and stderr. Capped (lib/log.ts). */
@@ -42,9 +42,10 @@ export function isAlive(pid: number): boolean {
/** Whether a durable SSO session exists for this computer. */
export function hasSavedAuthSession(): boolean { return hasAuthSession() }
-/** What to say when this shell cannot reach the daemon: stopped, or out of reach in a sandbox (lib/unreachable.ts). */
-export function daemonUnreachableText(error?: unknown): string {
- return unreachableText({ error, pid: readPid() })
+/** What to say when this shell cannot reach the daemon of [dataDir]: stopped, or out of reach in a sandbox
+ * (lib/unreachable.ts). The agent verbs reach the daemon that made their pane, whose folder may not be this CLI's. */
+export function daemonUnreachableText(error?: unknown, dataDir: string = env.ADAPTER_DATA_DIR): string {
+ return unreachableText({ error, pid: pidIn(dataDir) })
}
/** Is the background daemon process alive right now? (pid file present AND that pid still exists) */
diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.ts
index 55cc380eb..3ed364025 100644
--- a/cli/src/lib/newCommand.spec.ts
+++ b/cli/src/lib/newCommand.spec.ts
@@ -4,6 +4,7 @@ import { mkdirSync, mkdtempSync, realpathSync, symlinkSync, writeFileSync } from
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { newAgentPayload, newCommand, NewUsageError, parseNewArgs, resolveNewMachine, trustAsked, type NewCommandDeps, type NewSocket } from './newCommand.js'
+import { SANDBOXED } from './unreachable.js'
const env = { cwd: '/work/repo', home: '/home/me' }
@@ -140,7 +141,37 @@ function deps(argv: string[], socket: FakeSocket, over: Partial<NewCommandDeps>
}
}
+/** A connect that fails with [code], as `ws` reports it: one 'error', then 'close'. */
+class RefusedSocket extends EventEmitter implements NewSocket {
+ constructor(private code: string) { super() }
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ override on(event: string, listener: (...args: any[]) => void): this {
+ super.on(event, listener)
+ if (event === 'error') queueMicrotask(() => {
+ this.emit('error', Object.assign(new Error(`connect ${this.code} 127.0.0.1:1`), { code: this.code }))
+ this.emit('close', 1006, '')
+ })
+ return this
+ }
+ send(): void {}
+ close(): void {}
+}
+
describe('harness new: the daemon', () => {
+ it('says a sandbox is in the way when the daemon runs but its port is refused, and passes on anything else', async () => {
+ // Linux: the signal reaches the daemon, so it runs, and the sandbox refuses the connect (lib/unreachable.ts).
+ const sandboxed = deps(['claude', '--name', 'opinion', '--', 'a second opinion'], new FakeSocket(() => null), { connect: () => new RefusedSocket('EPERM') })
+ expect(await newCommand(sandboxed)).toBe(1)
+ expect(sandboxed.err).toEqual([SANDBOXED])
+ const json = deps(['claude', '--json'], new FakeSocket(() => null), { connect: () => new RefusedSocket('EACCES') })
+ expect(await newCommand(json)).toBe(1)
+ expect(JSON.parse(json.out[0]!)).toEqual({ ok: false, error: SANDBOXED })
+ // Nothing listening is not a sandbox's doing: said as the connection said it.
+ const refused = deps(['claude'], new FakeSocket(() => null), { connect: () => new RefusedSocket('ECONNREFUSED') })
+ expect(await newCommand(refused)).toBe(1)
+ expect(refused.err).toEqual(['connect ECONNREFUSED 127.0.0.1:1'])
+ })
+
it('selects this machine, creates here and says where', async () => {
const socket = new FakeSocket((frame) => frame.type === 'agent_create'
? { state: 'created', agent: { id: 'a1', name: 'Codex harness 9-19 10:02', cwd: '/work/repo' } } : null)
diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.ts
index 0794997ba..170474d25 100644
--- a/cli/src/lib/newCommand.ts
+++ b/cli/src/lib/newCommand.ts
@@ -8,7 +8,7 @@ import { engineName } from '../messages/model.js'
import { projectFolderSlug } from './agentNames.js'
import { permissionModeFlags } from './engineLaunch.js'
import { projectsRoot } from './projectFolder.js'
-import { NOT_RUNNING } from './unreachable.js'
+import { NOT_RUNNING, SANDBOXED, refused } from './unreachable.js'
/** Engine names, so an unknown word is judged rather than cast (the shape `registry.ts` uses). */
const ENGINE_NAMES: ReadonlySet<string> = new Set(ENGINES)
@@ -345,7 +345,9 @@ export function daemonSession(deps: Pick<NewCommandDeps, 'port' | 'connect' | 't
}
// A tool, not a window: a window's registration turns on the question watcher and counts as someone looking.
socket.on('open', () => socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1, tool: true } })))
- socket.on('error', (error) => failAll(error))
+ // `daemonRunning` saw the daemon's process, so a connect refused on the way is a sandbox's: Linux's lets the signal
+ // through and refuses the connect (lib/unreachable.ts).
+ socket.on('error', (error) => failAll(refused(error) ? new Error(SANDBOXED) : error))
socket.on('close', (code, reason) => failAll(new Error(
code === 4404 ? 'That machine is not linked to this one yet. Run `harness link` first.'
: `The connection to Harness closed (${code}${reason.toString() ? `: ${reason.toString()}` : ''}).`)))
diff --git a/cli/src/lib/unreachable.spec.ts b/cli/src/lib/unreachable.spec.ts
index 4962d78bd..5c1424eff 100644
--- a/cli/src/lib/unreachable.spec.ts
+++ b/cli/src/lib/unreachable.spec.ts
@@ -1,34 +1,82 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
-import { NOT_RUNNING, SANDBOXED, sandboxed, unreachableText } from './unreachable.js'
+import { NOT_RUNNING, pidIn, refused, SANDBOXED, sandboxed, START_OUTSIDE, startRefusalText, unreachableText } from './unreachable.js'
const errno = (code: string) => Object.assign(new Error(code), { code })
-const refused = (code: string) => () => { throw errno(code) }
+const failing = (code: string) => () => { throw errno(code) }
+/** kill(pid, 0) as Codex's seatbelt answers it (`codex sandbox` 0.162.1, 2026-10-11): EPERM for the daemon, which is
+ * there, and ESRCH for a pid that is gone, as anywhere. */
+const daemon = { here: () => {}, sandboxed: failing('EPERM'), gone: failing('ESRCH') }
+const CODEX = { CODEX_SANDBOX: 'seatbelt', CODEX_SANDBOX_NETWORK_DISABLED: '1' }
/** A sandbox (Codex's on macOS) kept a running Harness out of reach, and an agent was told to start it (2026-10-12). */
describe('a daemon this shell cannot reach', () => {
- it('is out of a sandbox\'s reach when the connection or the file was not permitted', () => {
- expect(sandboxed({ error: errno('EPERM'), env: {} })).toBe(true)
- expect(sandboxed({ error: errno('EACCES'), env: {} })).toBe(true)
- expect(sandboxed({ error: errno('ECONNREFUSED'), env: {} })).toBe(false)
- expect(sandboxed({ error: 'not an error', env: {} })).toBe(false)
+ it('is out of a sandbox\'s reach when the connection or the file was not permitted and the daemon is there', () => {
+ expect(sandboxed({ error: errno('EPERM'), env: {}, pid: 42, signal: daemon.here })).toBe(true)
+ expect(sandboxed({ error: errno('EACCES'), env: {}, pid: 42, signal: daemon.here })).toBe(true)
+ expect(sandboxed({ error: errno('ECONNREFUSED'), env: {}, pid: 42, signal: daemon.here })).toBe(false)
+ expect(sandboxed({ error: 'not an error', env: {}, pid: 42, signal: daemon.here })).toBe(false)
})
it('is in a sandbox when Codex says so, or when even asking whether its process lives is not permitted', () => {
- expect(sandboxed({ env: { CODEX_SANDBOX: 'seatbelt' } })).toBe(true)
- expect(sandboxed({ env: {}, pid: 42, signal: refused('EPERM') })).toBe(true)
+ expect(sandboxed({ env: CODEX, pid: 42, signal: daemon.sandboxed })).toBe(true)
+ expect(sandboxed({ env: { CODEX_SANDBOX: 'seatbelt' }, pid: 42, signal: daemon.here })).toBe(true)
+ expect(sandboxed({ env: { CODEX_SANDBOX_NETWORK_DISABLED: '1' }, pid: 42, signal: daemon.here })).toBe(true)
+ expect(sandboxed({ env: {}, pid: 42, signal: daemon.sandboxed })).toBe(true)
// No such process: stopped, as before.
- expect(sandboxed({ env: {}, pid: 42, signal: refused('ESRCH') })).toBe(false)
- expect(sandboxed({ env: {}, pid: 42, signal: () => {} })).toBe(false)
+ expect(sandboxed({ env: {}, pid: 42, signal: daemon.gone })).toBe(false)
+ expect(sandboxed({ env: {}, pid: 42, signal: daemon.here })).toBe(false)
expect(sandboxed({ env: {}, pid: null })).toBe(false)
// Asked of this process itself, which is alive and may be signalled.
expect(sandboxed({ env: {}, pid: process.pid })).toBe(false)
})
+ it('never says Harness runs when its process is gone: seatbelt refuses a port nobody listens on, and marks every command', () => {
+ for (const pid of [42, null]) {
+ const signal = daemon.gone
+ expect(sandboxed({ error: errno('EPERM'), env: CODEX, pid, signal })).toBe(false)
+ expect(unreachableText({ error: errno('EPERM'), env: CODEX, pid, signal })).toBe(START_OUTSIDE)
+ expect(unreachableText({ env: CODEX, pid, signal })).toBe(START_OUTSIDE)
+ // No sandbox Harness knows of: start it, as before.
+ expect(unreachableText({ error: errno('EPERM'), env: {}, pid, signal })).toBe(NOT_RUNNING)
+ }
+ expect(START_OUTSIDE).toBe('Harness is not running here, and this sandbox keeps it from starting. Run `harness start` outside the sandbox (with escalated permissions).')
+ })
+
it('is told to run its command outside the sandbox, never to start Harness', () => {
- expect(unreachableText({ error: errno('EPERM'), env: {} })).toBe(SANDBOXED)
+ expect(unreachableText({ error: errno('EPERM'), env: {}, pid: 42, signal: daemon.sandboxed })).toBe(SANDBOXED)
+ expect(unreachableText({ env: CODEX, pid: 42, signal: daemon.sandboxed })).toBe(SANDBOXED)
expect(SANDBOXED).not.toMatch(/harness start/)
- expect(unreachableText({ error: errno('ECONNREFUSED'), env: {} })).toBe(NOT_RUNNING)
+ expect(unreachableText({ error: errno('ECONNREFUSED'), env: {}, pid: 42, signal: daemon.gone })).toBe(NOT_RUNNING)
expect(NOT_RUNNING).toMatch(/harness start/)
- expect(unreachableText({ env: { ...process.env, CODEX_SANDBOX: '' } })).toBe(NOT_RUNNING)
+ expect(unreachableText({ env: { ...process.env, CODEX_SANDBOX: '', CODEX_SANDBOX_NETWORK_DISABLED: '' } })).toBe(NOT_RUNNING)
+ })
+
+ it('has `harness start` say why the sandbox refused it, and leaves any other failure as it was', () => {
+ const mkdir = errno('EPERM')
+ expect(startRefusalText({ error: mkdir, env: CODEX, pid: 42, signal: daemon.sandboxed })).toBe(SANDBOXED)
+ expect(startRefusalText({ error: mkdir, env: CODEX, pid: null })).toBe(START_OUTSIDE)
+ // Outside a sandbox, EPERM on the data folder is a permissions problem, shown as it is.
+ expect(startRefusalText({ error: mkdir, env: {}, pid: null })).toBeNull()
+ expect(startRefusalText({ error: new Error('busy'), env: CODEX, pid: 42, signal: daemon.sandboxed })).toBeNull()
+ })
+
+ it('reads the pid file of the daemon it is asked about, and knows a refusal from an absent daemon', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'unreachable-'))
+ try {
+ expect(pidIn(dir)).toBeNull()
+ writeFileSync(join(dir, 'adapter.pid'), '4242\n')
+ expect(pidIn(dir)).toBe(4242)
+ // 0 and below name process groups: kill(0, 0) always succeeds.
+ for (const text of ['0', '-1', 'nope']) {
+ writeFileSync(join(dir, 'adapter.pid'), text)
+ expect(pidIn(dir), text).toBeNull()
+ }
+ } finally { rmSync(dir, { recursive: true, force: true }) }
+ for (const code of ['EPERM', 'EACCES']) expect(refused(errno(code))).toBe(true)
+ for (const code of ['ECONNREFUSED', 'ENOENT']) expect(refused(errno(code))).toBe(false)
+ expect(refused(undefined)).toBe(false)
})
})
diff --git a/cli/src/lib/unreachable.ts b/cli/src/lib/unreachable.ts
index d1698cdcc..8ff3924f6 100644
--- a/cli/src/lib/unreachable.ts
+++ b/cli/src/lib/unreachable.ts
@@ -5,11 +5,21 @@
* process is alive (EPERM). Codex runs an agent's commands in one on macOS. Harness told such an agent "Harness is
* not running here. Start it with `harness start`": it ran `harness start`, which crashed on the spawn lock, then
* asked the person "May I start the Harness adapter?" while Harness was running all along (a fresh Mac, 2026-10-12).
+ *
+ * "Harness is running" needs the daemon's process as well as a sandbox. Measured with `codex sandbox` 0.162.1
+ * (2026-10-11): seatbelt refuses a connect to a loopback port nobody listens on with EPERM too, and Codex marks every
+ * command it sandboxes whether or not Harness runs; but kill(pid, 0) still answers ESRCH for a pid that is gone. With a
+ * sandbox and no daemon, the agent is told to start Harness outside the sandbox, where `harness start` can write.
*/
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
export const NOT_RUNNING = 'Harness is not running here. Start it with `harness start`.'
export const SANDBOXED = 'Harness is running, but a sandbox keeps this shell from reaching it (Codex runs commands in one). '
+ 'Run this harness command outside the sandbox. Harness needs no starting.'
+/** Nothing running, and the sandbox refuses `harness start` its data folder as well (mkdir EPERM). */
+export const START_OUTSIDE = 'Harness is not running here, and this sandbox keeps it from starting. '
+ + 'Run `harness start` outside the sandbox (with escalated permissions).'
export interface SandboxEvidence {
/** What failed: a connection's or a file's error. */
@@ -20,17 +30,45 @@ export interface SandboxEvidence {
signal?: (pid: number, signal: 0) => void
}
-/** Whether a sandbox, not a stopped daemon, is what this shell runs into. */
-export function sandboxed({ error, pid = null, env = process.env, signal = (p, s) => { process.kill(p, s) } }: SandboxEvidence = {}): boolean {
+/** The daemon's pid, as the pid file in [dataDir] names it (lib/daemonState.ts `PID_FILE`). */
+export function pidIn(dataDir: string): number | null {
+ try {
+ const pid = parseInt(readFileSync(join(dataDir, 'adapter.pid'), 'utf8').trim(), 10)
+ return pid > 0 ? pid : null
+ } catch { return null }
+}
+
+/** A connection or a file refused by a policy on the way, not by a daemon that is not there (ECONNREFUSED, ENOENT). */
+export function refused(error: unknown): boolean {
const code = (error as NodeJS.ErrnoException | undefined)?.code
- if (code === 'EPERM' || code === 'EACCES') return true
- // Codex marks every command it runs in its sandbox.
- if (env.CODEX_SANDBOX) return true
+ return code === 'EPERM' || code === 'EACCES'
+}
+
+/** Codex marks every command it runs in its sandbox: CODEX_SANDBOX=seatbelt on macOS, and CODEX_SANDBOX_NETWORK_DISABLED
+ * wherever the network is off. */
+const codexSandbox = (env: NodeJS.ProcessEnv): boolean => !!env.CODEX_SANDBOX || !!env.CODEX_SANDBOX_NETWORK_DISABLED
+
+/** Whether a sandbox, not a stopped daemon, is what this shell runs into: the daemon's process is there, and a sandbox
+ * is in the way. */
+export function sandboxed({ error, pid = null, env = process.env, signal = (p, s) => { process.kill(p, s) } }: SandboxEvidence = {}): boolean {
if (pid === null) return false
- try { signal(pid, 0); return false } catch (failure) { return (failure as NodeJS.ErrnoException).code === 'EPERM' }
+ try { signal(pid, 0) } catch (failure) {
+ // Gone. Refused, it is there, and asking was not permitted: a sandbox.
+ return (failure as NodeJS.ErrnoException).code === 'EPERM'
+ }
+ return refused(error) || codexSandbox(env)
}
/** What to say when the daemon cannot be reached. */
export function unreachableText(evidence: SandboxEvidence = {}): string {
- return sandboxed(evidence) ? SANDBOXED : NOT_RUNNING
+ if (sandboxed(evidence)) return SANDBOXED
+ return codexSandbox(evidence.env ?? process.env) ? START_OUTSIDE : NOT_RUNNING
+}
+
+/** What `harness start` says for [evidence.error] in place of the error itself, or null when it is no sandbox's doing:
+ * outside a sandbox, EPERM on the data folder is a permissions problem, shown as it is. */
+export function startRefusalText(evidence: SandboxEvidence): string | null {
+ if (!refused(evidence.error)) return null
+ const text = unreachableText(evidence)
+ return text === NOT_RUNNING ? null : text
}
diff --git a/cli/src/messages/rpc.spec.ts b/cli/src/messages/rpc.spec.ts
index 590c3e190..3903df23c 100644
--- a/cli/src/messages/rpc.spec.ts
+++ b/cli/src/messages/rpc.spec.ts
@@ -1,10 +1,11 @@
import { createServer, type Server } from 'node:http'
-import { mkdtempSync, rmSync } from 'node:fs'
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { WebSocketServer, type WebSocket } from 'ws'
import { localSocketPath } from '../lib/localSocket.js'
+import { NOT_RUNNING, SANDBOXED } from '../lib/unreachable.js'
import { messagesRpc } from './rpc.js'
type Behave = (ws: WebSocket, frame: { type: string; payload: Record<string, unknown> }) => void
@@ -93,4 +94,19 @@ describe('one Agent Messages request through the daemon', () => {
await expect(messagesRpc({ port: 1, machineId: 'm', dataDir: join(dir, 'none') }, {}, 2_000)).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE' })
await expect(messagesRpc({ port: 1, machineId: 'm' }, {}, 2_000)).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE' })
})
+
+ // Root opens a socket whatever its mode, so the refusal cannot be made there.
+ it.skipIf(process.getuid?.() === 0)('says a sandbox is in the way only when the daemon it was refused is there', async () => {
+ const env = { CODEX_SANDBOX: process.env.CODEX_SANDBOX, CODEX_SANDBOX_NETWORK_DISABLED: process.env.CODEX_SANDBOX_NETWORK_DISABLED }
+ delete process.env.CODEX_SANDBOX
+ delete process.env.CODEX_SANDBOX_NETWORK_DISABLED
+ try {
+ // A socket this process may not open answers EACCES, as one a sandbox refuses does.
+ chmodSync(localSocketPath(dir, PORT)!, 0)
+ // No pid file in the daemon's folder: nothing to reach, whatever refused the connect.
+ await expect(messagesRpc(target(), {}, 2_000)).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE', message: NOT_RUNNING })
+ writeFileSync(join(dir, 'adapter.pid'), `${process.pid}\n`)
+ await expect(messagesRpc(target(), {}, 2_000)).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE', message: SANDBOXED })
+ } finally { for (const [name, value] of Object.entries(env)) if (value !== undefined) process.env[name] = value }
+ })
})
diff --git a/cli/src/messages/rpc.ts b/cli/src/messages/rpc.ts
index 59fb81a81..fd539551f 100644
--- a/cli/src/messages/rpc.ts
+++ b/cli/src/messages/rpc.ts
@@ -7,7 +7,7 @@ import { randomBytes } from 'node:crypto'
import { existsSync } from 'node:fs'
import { WebSocket } from 'ws'
import { localSocketPath } from '../lib/localSocket.js'
-import { NOT_RUNNING, SANDBOXED, sandboxed } from '../lib/unreachable.js'
+import { NOT_RUNNING, pidIn, unreachableText } from '../lib/unreachable.js'
import { MessageError } from './model.js'
export interface RpcTarget { port: number; machineId: string; dataDir?: string; signal?: AbortSignal }
@@ -30,7 +30,7 @@ export const messagesRpc: Rpc = (target, payload, timeoutMs = 20_000) => new Pro
}
const timer = setTimeout(() => finish(new MessageError('UNCONFIRMED', 'The daemon did not answer in time.')), timeoutMs)
const abort = () => finish(new MessageError('CANCELLED', 'Cancelled.'))
- ws.on('error', (error) => finish(new MessageError('DAEMON_UNREACHABLE', sandboxed({ error }) ? SANDBOXED : NOT_RUNNING)))
+ ws.on('error', (error) => finish(new MessageError('DAEMON_UNREACHABLE', target.dataDir ? unreachableText({ error, pid: pidIn(target.dataDir) }) : NOT_RUNNING)))
ws.on('close', (code) => finish(new MessageError(code === 4404 ? 'NO_PEER_LINK' : 'DISCONNECTED', code === 4404
? 'That machine is not paired with this one.' : 'The daemon connection closed.')))
ws.on('open', () => ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId: target.machineId, localProtocolVersion: 1 } })))
diff --git a/plugins/harness/skills/harness/SKILL.md b/plugins/harness/skills/harness/SKILL.md
index 236a55d09..3b3ada9a3 100644
--- a/plugins/harness/skills/harness/SKILL.md
+++ b/plugins/harness/skills/harness/SKILL.md
@@ -25,6 +25,10 @@ these verbs: `harness update`. The agent you start must be installed as well (`c
for Codex) and signed in to its own provider. On Linux the installer installs tmux and curl with apt-get, which
asks for the person's password; without one, ask the person to run `sudo apt-get install -y tmux curl` first.
+In Codex, run `harness` commands outside your sandbox: they talk to Harness's local daemon, which the sandbox
+blocks, so ask for escalated permissions the first time. A sandbox in the way is not a stopped Harness: do not run
+`harness start` unless a command run outside the sandbox says Harness is not running.
+
## When to start a harness
Start one for work that:
diff --git a/website/public/agents/index.html b/website/public/agents/index.html
index 9aa1257d8..9cb59f1de 100644
--- a/website/public/agents/index.html
+++ b/website/public/agents/index.html
@@ -275,6 +275,10 @@ claude mcp add harness -- npx -y @autonomous-ai/harness-mcp</code></pre>
<ul>
<li><code>harness: command not found</code>: Harness is not installed; see <a href="#install">Install</a>.</li>
<li><code>Harness is not running here. Start it with `harness start`.</code></li>
+ <li><code>Harness is running, but a sandbox keeps this shell from reaching it.</code> Codex runs commands in a
+ sandbox, and <code>harness</code> talks to Harness's local daemon, which the sandbox blocks: run
+ <code>harness</code> commands outside it, asking for escalated permissions the first time. Do not run
+ <code>harness start</code> for it.</li>
<li><code>That machine is not reachable now. `harness machines` lists which are online.</code></li>
</ul>