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.

Start the engines a fresh computer has, and say why one cannot start (#1201)

Dee96ffb65c8240
diff --git a/cli/e2e/freshMachineEngines.e2e.ts b/cli/e2e/freshMachineEngines.e2e.ts
new file mode 100644
index 000000000..664d73197
--- /dev/null
+++ b/cli/e2e/freshMachineEngines.e2e.ts
@@ -0,0 +1,143 @@
+/**
+ * Engines as clean computers have them (fresh macOS 26 and Ubuntu 24.04 VMs, signed out, 2026-10-11), started from a
+ * terminal with `harness new`:
+ *
+ * - OpenCode 1.19.0 prints its help to standard error. Read from standard output alone, its permission flag was never
+ * confirmed and every launch of it held for good.
+ * - Codex installed by Harness with its own Node is a `#!/usr/bin/env node` script, and such a computer has no `node`
+ * on its PATH. Its probe failed, so every launch held; its pane would have failed the same way.
+ * - A Codex that cannot run at all is refused at once, with its own reason, instead of being held and said only to be
+ * unconfirmed after a minute.
+ */
+import { spawn } from 'node:child_process'
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { afterEach, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+
+let daemon: IsolatedDaemon | undefined
+afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+/** `harness <args>` from a terminal, not a pane. */
+function harness(d: IsolatedDaemon, args: string[]): Promise<{ code: number; out: string; err: string; ms: number }> {
+ const began = Date.now()
+ return new Promise((done) => {
+ const child = spawn(process.execPath, ['--import', 'tsx', 'src/cli.ts', ...args], {
+ cwd: CLI_ROOT, env: { ...d.env, TMUX_PANE: '' }, stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ let out = '', err = ''
+ child.stdout.on('data', (chunk) => { out += chunk })
+ child.stderr.on('data', (chunk) => { err += chunk })
+ child.on('close', (code) => done({ code: code ?? -1, out, err, ms: Date.now() - began }))
+ })
+}
+
+async function boot(prepare: (d: IsolatedDaemon) => void = () => {}): Promise<IsolatedDaemon> {
+ const d = daemon = await IsolatedDaemon.create()
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ prepare(d)
+ await d.start()
+ return d
+}
+
+const project = (d: IsolatedDaemon, name: string) => { const dir = join(d.projectsDir, name); mkdirSync(dir, { recursive: true }); return dir }
+
+it('starts an OpenCode that prints its help to standard error, with its permission flag', async () => {
+ const d = await boot((d) => {
+ const binary = join(d.root, 'bin', 'opencode'), launches = join(d.root, 'launches.jsonl')
+ d.env.OPENCODE_PATH = binary
+ d.env.OPENCODE_DATA_DIR = join(d.root, 'opencode', 'data')
+ d.env.OPENCODE_PLUGIN_DIR = join(d.root, 'opencode', 'plugin')
+ // OpenCode 1.19.0 as measured: `--help` writes 4,285 bytes to standard error, none to standard output, exits 0.
+ writeFileSync(binary, `#!${process.execPath}
+const fs = require('node:fs'), args = process.argv.slice(2);
+if (args.includes('--version')) { console.log('1.19.0'); process.exit(0) }
+if (args.includes('--help')) { console.error('opencode [project]\\n\\nOptions:\\n --auto approve every action\\n --prompt prompt to use'); process.exit(0) }
+fs.appendFileSync(${JSON.stringify(launches)}, JSON.stringify({ args }) + '\\n');
+process.title = ('opencode --session ses_' + process.pid).padEnd(160);
+console.log('fixture-opencode-ready');
+setInterval(() => {}, 1000);
+`, { mode: 0o755 })
+ })
+ const started = await harness(d, ['new', 'opencode', project(d, 'stderr-help'), '--name', 'helpful', '--', 'hello'])
+ expect(started.code, started.out + started.err).toBe(0)
+ expect(started.out).toContain('Created helpful on this computer')
+ const launch = await until('OpenCode to start', () => {
+ const lines = existsSync(join(d.root, 'launches.jsonl')) ? readFileSync(join(d.root, 'launches.jsonl'), 'utf8').trim().split('\n') : []
+ return lines[0] ? JSON.parse(lines[0]) as { args: string[] } : null
+ }, 30_000, 100)
+ expect(launch.args).toContain('--auto')
+})
+
+it('runs a Codex that npm installed as a Node script on a computer with no Node of its own', async (context) => {
+ // The login shell's PATH below names system folders only; a computer that has a node there is not this case.
+ const system = ['/usr/bin', '/bin', '/usr/sbin', '/sbin']
+ if (system.some((dir) => existsSync(join(dir, 'node')))) context.skip()
+ const d = await boot((d) => {
+ const bin = join(d.root, 'bin')
+ // What `npm install -g @openai/codex` leaves in ~/.local/bin: a script that asks env for a node.
+ const engine = pathToFileURL(join(CLI_ROOT, 'e2e', 'harness', 'fakeEngine.mjs')).href
+ const wrapper = readFileSync(join(bin, 'codex'), 'utf8').split('\n').slice(1).join('\n')
+ expect(wrapper).toContain(engine)
+ writeFileSync(join(bin, 'codex'), `#!/usr/bin/env node\n${wrapper}`, { mode: 0o755 })
+ // After the system's own startup files, as a person's own .zshrc or .bash_profile would: no node anywhere.
+ const path = `export PATH=${[bin, ...system].join(':')}\n`
+ writeFileSync(join(d.env.HOME!, '.zshrc'), path)
+ writeFileSync(join(d.env.HOME!, '.bash_profile'), path)
+ })
+ const started = await harness(d, ['new', 'codex', project(d, 'no-node'), '--name', 'nodeless', '--', 'hello'])
+ expect(started.code, started.out + started.err).toBe(0)
+ expect(started.out).toContain('Created nodeless on this computer')
+ // Its pane ran it too: the engine started and bound its conversation.
+ const client = await LocalClient.connect(d)
+ try {
+ await until('Codex to bind its conversation in its pane', async () => {
+ const row = ((await client.request<{ agents: Array<Record<string, any>> }>('agents_list', {}, 30_000)).agents).find((a) => a.name === 'nodeless')
+ return row?.sessionId && row.status === 'active' ? row : null
+ }, 60_000, 500)
+ } finally { client.close() }
+})
+
+it('refuses at once, with its own reason, a Codex that cannot run, and saves nothing to start later', async () => {
+ const d = await boot((d) => {
+ writeFileSync(join(d.root, 'bin', 'codex'), `#!${process.execPath}
+console.error("node:internal/modules/cjs/loader:1228\\n throw err;\\n\\nError: Cannot find module '@openai/codex-linux-x64'\\n\\nNode.js v22.20.0");
+process.exit(1);
+`, { mode: 0o755 })
+ })
+ const refused = await harness(d, ['new', 'codex', project(d, 'broken'), '--', 'hello'])
+ expect(refused.code, refused.out + refused.err).toBe(1)
+ expect(refused.err.trim()).toBe('Codex is installed but cannot run: Error: Cannot find module \'@openai/codex-linux-x64\'')
+ // Refused, not held for a minute and then called unconfirmed.
+ expect(refused.ms).toBeLessThan(30_000)
+ const client = await LocalClient.connect(d)
+ try {
+ expect((await client.request<{ agents: unknown[] }>('agents_list', { includeStopped: true }, 30_000)).agents).toEqual([])
+ } finally { client.close() }
+})
+
+it('says what a launch still held after a minute waits for, and cancels it so it never starts later', async () => {
+ let fixed = ''
+ const d = await boot((d) => {
+ fixed = join(d.root, 'codex-answers')
+ // A Codex whose help never comes: each probe meets its deadline, and the launch is held, asked again every two seconds.
+ const wrapper = readFileSync(join(d.root, 'bin', 'codex'), 'utf8').split('\n')
+ writeFileSync(join(d.root, 'bin', 'codex'), [wrapper[0],
+ `if (process.argv.includes('--help') && !require('node:fs').existsSync(${JSON.stringify(fixed)})) setInterval(() => {}, 1000)`,
+ `else ${wrapper.slice(1).join('\n')}`].join('\n'), { mode: 0o755 })
+ })
+ const held = await harness(d, ['new', 'codex', project(d, 'held'), '--name', 'later', '--', 'hello'])
+ expect(held.code, held.out + held.err).toBe(1)
+ expect(held.err).toContain('Waiting to confirm the selected executable’s permission flags.')
+ expect(held.err.trim().split('\n').at(-1)).toBe('Harness did not start the harness within a minute: '
+ + 'Waiting to confirm the selected executable’s permission flags. The request is cancelled, so it will not start later.')
+ // Once Codex answers, the cancelled request still does not start.
+ writeFileSync(fixed, '')
+ await new Promise((done) => setTimeout(done, 8_000))
+ const client = await LocalClient.connect(d)
+ try {
+ expect((await client.request<{ agents: unknown[] }>('agents_list', { includeStopped: true }, 30_000)).agents).toEqual([])
+ } finally { client.close() }
+}, 180_000)
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index a10fe110a..a57af20ad 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -292,6 +292,13 @@ describe('creating an agent', () => {
expect(createAndRegisterPane).not.toHaveBeenCalled()
})
+ it('refuses, with the engine\'s own reason, an engine that ran and failed instead of holding the creation', async () => {
+ const detail = 'Codex is installed but cannot run: /usr/bin/env: ‘node’: No such file or directory'
+ const broken = { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail, cannotRun: true } as const
+ expect(await setup({ native: async () => broken }).create(request())).toEqual({ ok: false, error: 'ENGINE_CANNOT_RUN', detail })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ })
+
it.each(['published', 'legacy', 'no retain', 'revoked proof', 'write failed'] as const)('keeps generated native configuration authoritative: %s', async mode => {
const proof = { files: [], current: () => true }
const launch = { current: () => true, environment: { HOME: root }, prepareHooks: async () => true, opencodeMajor: null,
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index 659c479b5..0510c6db8 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -125,7 +125,11 @@ export function createAgentCreator({
bypassPermission = permissionModeApproves(pinnedMode)
}
const inspected = await inspectNative?.(engine, { ...input, permissionMode, bypassPermission }, authority)
- if (inspected && !inspected.ok) return inspected
+ // An engine that ran and failed is refused, with its own reason. Held, a creation retried every two
+ // seconds and could start, task and all, whenever the engine was repaired: a Codex installed with
+ // npm on a computer without Node (fresh Ubuntu VM, 2026-10-11) held for good, and `harness new`
+ // said only that it could not confirm. A relaunch, which nobody is waiting on, still holds.
+ if (inspected && !inspected.ok) return inspected.cannotRun ? { ok: false, error: 'ENGINE_CANNOT_RUN', detail: inspected.detail } : inspected
const native = inspected?.ok ? inspected.launch : undefined
if (engine === 'codex' && native) codexHome = nativeHookLocations(native.environment).CODEX_HOME
const current = () => authority.current() && (!native || native.current())
diff --git a/cli/src/engines/kit/launchExecutable.spec.ts b/cli/src/engines/kit/launchExecutable.spec.ts
index 05fc2bf6f..fb30a8a34 100644
--- a/cli/src/engines/kit/launchExecutable.spec.ts
+++ b/cli/src/engines/kit/launchExecutable.spec.ts
@@ -1,6 +1,6 @@
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync, symlinkSync } from 'node:fs'
import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
let root = ''
afterEach(() => { vi.unstubAllEnvs(); vi.resetModules(); if (root) rmSync(root, { recursive: true, force: true }); root = '' })
@@ -50,3 +50,30 @@ it('permits complete absence through a valid search-directory alias', async () =
const alias = join(root, 'path-alias'); symlinkSync(bin, alias); vi.stubEnv('PATH', alias)
expect(await captureLaunchExecutable('opencode', '')).toMatchObject({ state: 'install' })
})
+
+it('gives an npm engine Harness\'s Node, after the PATH, when the launch PATH has none', async () => {
+ // Codex installed by the daemon with Harness's Node on a computer without one (fresh Ubuntu VM, 2026-10-11):
+ // `#!/usr/bin/env node` found no node, so its probe and its pane both failed.
+ const { bin, captureLaunchExecutable } = await fixture()
+ const { managedNodePath } = await import('../../lib/nodeRuntime.js')
+ writeFileSync(join(bin, 'opencode'), '#!/usr/bin/env node\nrequire("./opencode.js")\n', { mode: 0o700 })
+ const result = await captureLaunchExecutable('opencode', '')
+ expect(result).toMatchObject({ state: 'ready', environment: { PATH: `${bin}:${dirname(managedNodePath())}` } })
+})
+it('leaves the launch PATH alone for a Node the person has, and for an engine that is not a Node script', async () => {
+ const { bin, withNodeForScript } = await fixture()
+ const script = join(bin, 'codex'), node = join(root, 'harness-node', 'bin', 'node')
+ const environment = { HOME: root, PATH: bin }
+ writeFileSync(script, '#!/usr/bin/env -S node --no-warnings\n', { mode: 0o700 })
+ expect(withNodeForScript(script, environment, node).PATH).toBe(`${bin}:${dirname(node)}`)
+ expect(withNodeForScript(script, environment, 'node')).toBe(environment)
+ expect(withNodeForScript(script, { ...environment, PATH: Array(256).fill(bin).join(':') }, node).PATH).toBe(Array(256).fill(bin).join(':'))
+ writeFileSync(join(bin, 'node'), '', { mode: 0o700 })
+ expect(withNodeForScript(script, environment, node)).toBe(environment)
+ rmSync(join(bin, 'node'))
+ for (const head of ['#!/bin/sh\nexec node "$0"\n', '#!/usr/bin/env nodejs\n', '\x7fELF']) {
+ writeFileSync(script, head)
+ expect(withNodeForScript(script, environment, node), head).toBe(environment)
+ }
+ expect(withNodeForScript(join(root, 'absent'), environment, node)).toBe(environment)
+})
diff --git a/cli/src/engines/kit/launchExecutable.ts b/cli/src/engines/kit/launchExecutable.ts
index f69dbd8bf..4801b5d6e 100644
--- a/cli/src/engines/kit/launchExecutable.ts
+++ b/cli/src/engines/kit/launchExecutable.ts
@@ -1,7 +1,7 @@
/** A launch resolves once, then keeps that executable through probes and dispatch. */
import { execFile } from 'node:child_process'
-import { accessSync, constants, statSync } from 'node:fs'
-import { delimiter, isAbsolute, join, resolve } from 'node:path'
+import { accessSync, closeSync, constants, openSync, readSync, statSync } from 'node:fs'
+import { delimiter, dirname, isAbsolute, join, resolve } from 'node:path'
import { engineBin, enginePathOverride } from '../../lib/engineBin.js'
import { engineInstallPaths, engineInstallRecipe, type EngineInstallRecipe } from '../../lib/engineInstall.js'
import { engineShellArgv, interactiveEngineShell } from '../../lib/engineLaunch.js'
@@ -90,7 +90,38 @@ export async function captureLaunchExecutable(engine: AgentEngine, shell?: strin
}
const executable = executableSnapshot(nativeVersionProbe({ args: [], output: /^$/, timeoutMs: 5_000 }, () => path))
if (!executable) return held('Waiting for the selected engine executable to stop changing.')
- return { state: 'ready', executable, environment }
+ return { state: 'ready', executable, environment: withNodeForScript(path, environment) }
}
return recipe ? { state: 'install', recipe, environment: environment as Record<string, string> } : held('Waiting for the configured engine executable to become available.')
}
+
+/**
+ * An engine whose executable is a Node script (`#!/usr/bin/env node`: what `npm install -g` leaves for
+ * Codex, Claude Code and the other npm engines) needs a `node` on its PATH. Harness installs those with its
+ * own Node (lib/engineLaunch.ts `npmRuntimePrelude`; Desktop's setup too, bootstrap/agent_prefetch.dart) and
+ * never adds that Node to the person's PATH, so on a computer without a Node of its own the engine could
+ * not start: in a fresh Ubuntu VM (2026-10-11) Codex installed by the daemon failed its `--help` probe with
+ * "/usr/bin/env: ‘node’: No such file or directory" and every launch of it held for good, and a pane would
+ * have failed the same way. Only for such a script, and only when no directory of the launch PATH has a
+ * `node`, Harness's Node goes at the END of that PATH. The probe runs with this environment and the pane sets
+ * it again after its rc files, so both find the same Node; a Node the person has is never shadowed.
+ */
+export function withNodeForScript(path: string, environment: NodeJS.ProcessEnv, node: string = managedNodePath()): NodeJS.ProcessEnv {
+ const entries = environment.PATH?.split(delimiter) ?? []
+ const bin = dirname(node)
+ if (!isAbsolute(node) || bin.includes(delimiter) || entries.length >= 256 || !runsOnPathNode(path)) return environment
+ const executableFile = (file: string) => { try { accessSync(file, constants.X_OK); return statSync(file).isFile() } catch { return false } }
+ if (entries.some(entry => executableFile(join(entry, 'node')))) return environment
+ return { ...environment, PATH: [...entries, bin].join(delimiter) }
+}
+
+/** The script's first line names `env node` (or `env -S node …`) as its interpreter. */
+function runsOnPathNode(path: string): boolean {
+ let fd: number | undefined
+ try {
+ fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK)
+ const head = Buffer.alloc(256)
+ const line = head.subarray(0, readSync(fd, head, 0, head.length, 0)).toString('utf8').split('\n')[0]!
+ return /^#!\s*\S*\/env(?:\s+-S)?\s+node(?:\s|$)/.test(line)
+ } catch { return false } finally { if (fd !== undefined) closeSync(fd) }
+}
diff --git a/cli/src/engines/nativeLaunch.probe.spec.ts b/cli/src/engines/nativeLaunch.probe.spec.ts
index ab8538c92..5858b6120 100644
--- a/cli/src/engines/nativeLaunch.probe.spec.ts
+++ b/cli/src/engines/nativeLaunch.probe.spec.ts
@@ -4,7 +4,8 @@ import { join } from 'node:path'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { inspectNativeLaunch } from './nativeLaunch.js'
-const fixture = vi.hoisted(() => ({ calls: 0, stall: false, pipes: false, pipeCount: 0, root: '', children: [] as import('node:child_process').ChildProcess[] }))
+const fixture = vi.hoisted(() => ({ calls: 0, stall: false, pipes: false, pipeCount: 0, root: '', children: [] as import('node:child_process').ChildProcess[],
+ help: 'stdout' as 'stdout' | 'stderr' | 'broken' }))
vi.mock('./kit/launchExecutable.js', () => ({
captureLaunchExecutable: async () => ({ state: 'ready',
executable: { command: '/fixture/permission-engine', identity: 'fixture', current: () => true },
@@ -28,7 +29,13 @@ vi.mock('node:child_process', async original => {
const script = fixture.pipes ? `
const child=require('node:child_process').spawn(process.execPath,['-e',${JSON.stringify(inheritedPipe)}],{stdio:['ignore',1,2]});
process.stdout.write('Usage: fixture\\n --permission-mode\\n');process.exit(0);
- ` : 'process.stdout.write("Usage: fixture\\n --permission-mode\\n")'
+ ` : {
+ stdout: 'process.stdout.write("Usage: fixture\\n --permission-mode\\n")',
+ // OpenCode 1.19.0: its whole help on standard error, nothing on standard output, exit 0.
+ stderr: 'process.stderr.write("Usage: fixture\\n --permission-mode\\n")',
+ // An npm engine with no Node to run it: env's own complaint, exit 127.
+ broken: 'process.stderr.write("/usr/bin/env: \\u2018node\\u2019: No such file or directory\\n");process.exit(127)',
+ }[fixture.help]
const child = actual.execFile(process.execPath, ['-e', script], options, done)
fixture.children.push(child)
// Same check-phase stall as e2e/stall.e2e.ts. Node's native timeout loses
@@ -38,7 +45,7 @@ vi.mock('node:child_process', async original => {
} }
})
beforeEach(() => {
- fixture.calls = 0; fixture.stall = false; fixture.pipes = false; fixture.pipeCount = 0; fixture.children = []
+ fixture.calls = 0; fixture.stall = false; fixture.pipes = false; fixture.pipeCount = 0; fixture.children = []; fixture.help = 'stdout'
fixture.root = mkdtempSync(join(tmpdir(), 'native-probe-'))
})
afterEach(async () => {
@@ -77,3 +84,17 @@ it('holds inherited output pipes within a bound and recovers probe capacity afte
expect(await prepared.launch.permission({ permissionMode: 'auto' })).toBe('supported')
expect(fixture.calls).toBe(9)
}, 15_000)
+
+it('reads help an engine prints to standard error, as OpenCode 1.19.0 does', async () => {
+ fixture.help = 'stderr'
+ const prepared = await inspectNativeLaunch('claude', { permissionMode: 'auto' })
+ expect(prepared).toMatchObject({ ok: true })
+ if (!prepared.ok) throw Error(prepared.detail)
+ expect(await prepared.launch.permission({ permissionMode: 'auto' })).toBe('supported')
+}, 15_000)
+
+it('says in the engine\'s own words why an engine that ran and failed cannot run', async () => {
+ fixture.help = 'broken'
+ expect(await inspectNativeLaunch('codex', { permissionMode: 'auto' })).toEqual({ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native',
+ detail: 'Codex is installed but cannot run: /usr/bin/env: ‘node’: No such file or directory', cannotRun: true })
+}, 15_000)
diff --git a/cli/src/engines/nativeLaunch.spec.ts b/cli/src/engines/nativeLaunch.spec.ts
index e3346a887..b9de9f0fb 100644
--- a/cli/src/engines/nativeLaunch.spec.ts
+++ b/cli/src/engines/nativeLaunch.spec.ts
@@ -4,14 +4,15 @@ import { captureLaunchExecutable } from './kit/launchExecutable.js'
import { engineHooks } from './hooks.js'
import * as hooks from './nativeHooks.js'
-const fixture = vi.hoisted(() => ({ current: true, hooks: true, version: '2.0.0', help: '--auto --permission-mode --approve-for-me', calls: [] as string[], pending: [] as (() => void)[], stalled: false, failed: false, environments: [] as NodeJS.ProcessEnv[] }))
+const fixture = vi.hoisted(() => ({ current: true, hooks: true, version: '2.0.0', help: '--auto --permission-mode --approve-for-me', calls: [] as string[], pending: [] as (() => void)[], stalled: false, failed: false, environments: [] as NodeJS.ProcessEnv[], exit: 0, stderr: '' }))
vi.mock('./kit/launchExecutable.js', async original => ({ ...await original<typeof import('./kit/launchExecutable.js')>(), captureLaunchExecutable: vi.fn(async () => ({ state: 'ready',
executable: { command: '/fixture/engine', identity: 'fixture', current: () => fixture.current },
environment: { HOME: '/fixture/home', PATH: '/fixture/bin', CODEX_HOME: '/fixture/codex', CLAUDE_CONFIG_DIR: '/fixture/claude', HERMES_HOME: '/fixture/hermes' },
})) }))
-vi.mock('node:child_process', () => ({ execFile: (command: string, args: string[], _options: { env: NodeJS.ProcessEnv }, done: (error: Error | null, output: string) => void) => {
+vi.mock('node:child_process', () => ({ execFile: (command: string, args: string[], _options: { env: NodeJS.ProcessEnv }, done: (error: Error | null, output: string, errors: string) => void) => {
fixture.calls.push(command); fixture.environments.push(_options.env)
- const settle = () => done(fixture.failed ? Error('Private probe unavailable') : null, args[0] === '--version' ? fixture.version : fixture.help)
+ const settle = () => done(fixture.failed ? Error('Private probe unavailable') : fixture.exit ? Object.assign(Error('Command failed'), { code: fixture.exit }) : null,
+ args[0] === '--version' ? fixture.version : fixture.help, fixture.stderr)
if (fixture.stalled) fixture.pending.push(settle); else queueMicrotask(settle)
return { stdin: { end: vi.fn(), destroy: vi.fn() } }
} }))
@@ -19,7 +20,7 @@ vi.mock('./hooks.js', () => ({ engineHooks: { claude: { installIn: vi.fn(async (
vi.mock('./nativeHooks.js', () => Object.fromEntries(['installOpencodePlugin', 'installHermesHooks', 'installCursorHooks',
'installCommandCodeHooks', 'installDevinHooks', 'installAmpPlugin', 'installKiloPlugin', 'installGrokHooks', 'installAgyHooks', 'installCopilotHooks', 'installPiExtension',
].map(name => [name, vi.fn(async () => fixture.hooks)])))
-beforeEach(() => { fixture.current = true; fixture.hooks = true; fixture.version = '2.0.0'; fixture.help = '--auto --permission-mode --approve-for-me'; fixture.calls = []; fixture.pending = []; fixture.stalled = false; fixture.failed = false; fixture.environments = [] })
+beforeEach(() => { fixture.current = true; fixture.hooks = true; fixture.version = '2.0.0'; fixture.help = '--auto --permission-mode --approve-for-me'; fixture.calls = []; fixture.pending = []; fixture.stalled = false; fixture.failed = false; fixture.environments = []; fixture.exit = 0; fixture.stderr = '' })
afterEach(() => { vi.clearAllMocks(); vi.unstubAllEnvs() })
it('needs no executable, hooks or probes for a terminal', async () => {
@@ -51,6 +52,27 @@ it('holds an unavailable version without caching a permanent unknown', async ()
expect(await inspectNativeLaunch('opencode')).toMatchObject({ ok: true, launch: { opencodeMajor: 1 } })
})
+it('says why an OpenCode that ran and failed cannot run, and waits for one that is changing', async () => {
+ // A Node stack trace: the line naming the failure, not its first or last.
+ fixture.exit = 1; fixture.version = ''
+ fixture.stderr = 'node:internal/modules/cjs/loader:1228\n throw err;\n\nError: Cannot find module \'opencode-linux-x64\'\n\nNode.js v22.20.0\n'
+ expect(await inspectNativeLaunch('opencode')).toMatchObject({ ok: false, cannotRun: true,
+ detail: 'OpenCode is installed but cannot run: Error: Cannot find module \'opencode-linux-x64\'' })
+ fixture.stderr = 'Segmentation fault\n'
+ expect(await inspectNativeLaunch('opencode')).toMatchObject({ detail: 'OpenCode is installed but cannot run: Segmentation fault' })
+ fixture.stderr = ''
+ expect(await inspectNativeLaunch('opencode')).toMatchObject({ detail: 'OpenCode is installed but cannot run: it exited with status 1' })
+ fixture.current = false
+ const changing = await inspectNativeLaunch('opencode')
+ expect(changing).toMatchObject({ ok: false, unavailable: 'native' })
+ expect(changing).not.toHaveProperty('cannotRun')
+})
+it('says Claude Code by its name when it cannot run', async () => {
+ fixture.exit = 127; fixture.stderr = 'env: node: No such file or directory\n'
+ expect(await inspectNativeLaunch('claude', { permissionMode: 'auto' })).toMatchObject({ cannotRun: true,
+ detail: 'Claude Code is installed but cannot run: env: node: No such file or directory' })
+})
+
it('revokes every hook write when a retained configuration loses authority', async () => {
const result = await inspectNativeLaunch('codex')
if (!result.ok) throw Error('fixture held')
diff --git a/cli/src/engines/nativeLaunch.ts b/cli/src/engines/nativeLaunch.ts
index e206df042..de8723c43 100644
--- a/cli/src/engines/nativeLaunch.ts
+++ b/cli/src/engines/nativeLaunch.ts
@@ -2,6 +2,7 @@
import { execFile } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { isAbsolute, join } from 'node:path'
+import { engineLabel } from '../lib/agentNames.js'
import { permissionFlagToVerify, type PermissionLaunchChoice } from '../lib/engineLaunch.js'
import type { EngineInstallRecipe } from '../lib/engineInstall.js'
import { patientDeadline } from '../lib/patientExec.js'
@@ -35,32 +36,43 @@ export interface NativeLaunch {
}
export type NativeLaunchResult =
| { ok: true; launch: NativeLaunch }
- | { ok: false; error: 'NATIVE_LAUNCH_HELD'; unavailable: 'native'; detail: string; install?: EngineInstallRecipe; environment?: Record<string, string> }
+ | { ok: false; error: 'NATIVE_LAUNCH_HELD'; unavailable: 'native'; detail: string; install?: EngineInstallRecipe; environment?: Record<string, string>
+ /** The selected executable ran and exited with a failure. A creation is refused with it rather than
+ * held (core/agents/create.ts); a relaunch, which nobody is waiting on, still holds. */
+ cannotRun?: true }
const waiting = (detail: string): Extract<NativeLaunchResult, { ok: false }> => ({ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail })
+const cannotRun = (engine: AgentEngine, reason: string): Extract<NativeLaunchResult, { ok: false }> =>
+ ({ ...waiting(`${engine === 'claude' ? 'Claude Code' : engineLabel(engine)} is installed but cannot run: ${reason}`), cannotRun: true })
const noNative: NativeLaunch = {
opencodeMajor: null, environment: {}, proofs: [], current: () => true,
prepareHooks: async () => true, permission: async () => 'supported',
}
let probes = 0
+/** What a probe's child said, once it exited by itself. A deadline, a signal, an output limit or a
+ * child that never started is no answer at all: null. */
+interface ProbeOutput { code: number; stdout: string; stderr: string }
/** Slots follow actual subprocess settlement, including deadline and output-limit kills. */
-async function read(executable: string, args: readonly string[], environment: Readonly<Record<string, string>>): Promise<string | null> {
+async function read(executable: string, args: readonly string[], environment: Readonly<Record<string, string>>): Promise<ProbeOutput | null> {
if (probes >= 8) return null
probes++
return new Promise(done => {
let settled = false, expired = false, answered = false
let cancelDeadline = () => {}
let drain: ReturnType<typeof setTimeout> | undefined
- const answer = (output: string | null) => { if (!answered) { answered = true; done(output) } }
+ const answer = (output: ProbeOutput | null) => { if (!answered) { answered = true; done(output) } }
let child: ReturnType<typeof execFile>
try {
// Node's timeout can discard unread output after a core stall, then
// report exit 0. Keep its pipes and use discovery's patient deadline.
child = execFile(executable, [...args], {
env: nativeProcessEnvironment(environment), encoding: 'utf8', killSignal: 'SIGKILL', maxBuffer: 64 * 1024,
- }, (error, output) => {
+ }, (error, stdout, stderr) => {
settled = true; probes--; cancelDeadline(); clearTimeout(drain)
- answer(error || expired ? null : output)
+ // A numeric code is the child's own exit status. A spawn failure, a signal or the output
+ // limit leaves a string or null there, and says nothing about the executable itself.
+ const code = !error ? 0 : typeof (error as { code?: unknown }).code === 'number' ? (error as { code: number }).code : null
+ answer(expired || code === null ? null : { code, stdout: stdout ?? '', stderr: stderr ?? '' })
})
} catch { probes--; answer(null); return }
if (!settled) cancelDeadline = patientDeadline(5_000, () => {
@@ -78,6 +90,18 @@ async function read(executable: string, args: readonly string[], environment: Re
})
}
+/**
+ * Why an executable that exited non-zero cannot run, in its own words: the line that names the
+ * failure, else its first line. A Codex installed with npm on a computer without Node says
+ * "/usr/bin/env: ‘node’: No such file or directory" (fresh Ubuntu VM, 2026-10-11); a Node stack
+ * trace starts with a source location and ends with the Node version, so neither end is the reason.
+ */
+function failureReason(output: ProbeOutput): string {
+ const lines = `${output.stderr}\n${output.stdout}`.split('\n').map(line => line.replace(/[\x00-\x1f\x7f]/g, ' ').trim()).filter(Boolean)
+ const line = lines.find(text => /\b(error|cannot|can't|no such|not found|denied|failed|missing)\b/i.test(text)) ?? lines[0]
+ return line ? line.slice(0, 300) : `it exited with status ${output.code}`
+}
+
/** Probe only. No settings, workspace, model or process mutation occurs here. */
export async function inspectNativeLaunch(engine: AgentEngine, source: NativeLaunchSource = {},
deps: { confirmHome?: (engine: 'claude' | 'codex', home: string) => void } = {},
@@ -104,7 +128,9 @@ export async function inspectNativeLaunch(engine: AgentEngine, source: NativeLau
&& initialHomes.CLAUDE_PROJECTS_DIR === join(initialHomes.CLAUDE_HOME, 'projects') ? initialHomes.CLAUDE_HOME
: engine === 'codex' && !source.codexHome ? initialHomes.CODEX_HOME : null
const output = engine === 'opencode' ? await read(executable.command, OPENCODE_VERSION.args, environment) : null
- const opencodeMajor = output === null ? null : parseMajor(OPENCODE_VERSION, output)
+ // The version is read from standard output only, as it always was; help below reads both streams.
+ const opencodeMajor = output?.code !== 0 ? null : parseMajor(OPENCODE_VERSION, output.stdout)
+ if (output && output.code !== 0 && executable.current()) return cannotRun(engine, failureReason(output))
// Unknown is an observation of this attempt, never a permanent installed-file answer.
if (engine === 'opencode' && opencodeMajor === null) return waiting('Waiting to confirm the selected OpenCode executable’s version.')
if (!executable.current()) return waiting('Waiting for the selected engine executable to stop changing.')
@@ -114,6 +140,8 @@ export async function inspectNativeLaunch(engine: AgentEngine, source: NativeLau
let preparing = false, valid = true, prepared = false, revision = 0
const current = () => valid && !preparing && executable.current() && [...dependencies, ...proofs].every(proof => proof.current())
const permissions = new Map<string, 'supported' | 'unsupported'>()
+ /** Why the latest help probe's executable failed, when it ran and exited non-zero. */
+ let failed: string | null = null
const launch: NativeLaunch = {
token: randomUUID(), executable, opencodeMajor, current, ready: () => prepared && current(),
get environment() { return selectedEnvironment },
@@ -166,15 +194,25 @@ export async function inspectNativeLaunch(engine: AgentEngine, source: NativeLau
const known = permissions.get(flag)
if (known) return known
const observedRevision = revision
- const help = await read(executable.command, ['--help'], selectedEnvironment)
- if (!help?.trim() || !current() || observedRevision !== revision) return 'unknown'
+ failed = null
+ const probe = await read(executable.command, ['--help'], selectedEnvironment)
+ if (!probe || !current() || observedRevision !== revision) return 'unknown'
+ if (probe.code !== 0) { failed = failureReason(probe); return 'unknown' }
+ // Help on either stream, as the shell probe reads it (`2>&1`, lib/engineLaunch.ts). OpenCode
+ // 1.19.0 prints its help to standard error and exits 0 (stdout 0 bytes, stderr 4,285, measured
+ // in clean macOS and Ubuntu VMs, 2026-10-11): read from stdout alone, every launch of it held
+ // for good, waiting to confirm its permission flags.
+ const help = `${probe.stdout}\n${probe.stderr}`
+ if (!help.trim()) return 'unknown'
const escaped = flag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const answer = new RegExp(`(?:^|[^A-Za-z0-9-])${escaped}(?![A-Za-z0-9-])`).test(help) ? 'supported' : 'unsupported'
permissions.set(flag, answer)
return answer
},
}
- if (await launch.permission(source) === 'unknown') return waiting('Waiting to confirm the selected executable’s permission flags.')
+ if (await launch.permission(source) === 'unknown') {
+ return failed ? cannotRun(engine, failed) : waiting('Waiting to confirm the selected executable’s permission flags.')
+ }
return { ok: true, launch }
}
diff --git a/cli/src/engines/prepareNativeLaunch.spec.ts b/cli/src/engines/prepareNativeLaunch.spec.ts
index 53b722dbd..19c478651 100644
--- a/cli/src/engines/prepareNativeLaunch.spec.ts
+++ b/cli/src/engines/prepareNativeLaunch.spec.ts
@@ -52,3 +52,12 @@ it('does not mistake a newly visible executable for its still-running installer
expect(ensure).toHaveBeenCalledOnce()
expect(status).toHaveBeenCalledWith('codex', authority.id, authority.current)
})
+
+it('holds an executable that cannot run while its installer is unsettled, and refuses it only after', async () => {
+ const broken: NativeLaunchResult = { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Codex is installed but cannot run: fixture', cannotRun: true }
+ const status = vi.fn().mockResolvedValueOnce({ complete: false, detail: 'Waiting for the saved installer to settle.' }).mockResolvedValue(null)
+ const prepare = createNativeLaunchPreparer({ installations: { ensure: vi.fn(), status }, inspect: vi.fn(async () => broken) })
+ const authority = { id: 'fixture-request', current: () => true }
+ expect(await prepare('codex', {}, authority)).toEqual({ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting for the saved installer to settle.' })
+ expect(await prepare('codex', {}, authority)).toBe(broken)
+})
diff --git a/cli/src/engines/prepareNativeLaunch.ts b/cli/src/engines/prepareNativeLaunch.ts
index 3d2b7a8ed..c2dd14fad 100644
--- a/cli/src/engines/prepareNativeLaunch.ts
+++ b/cli/src/engines/prepareNativeLaunch.ts
@@ -15,9 +15,11 @@ export function createNativeLaunchPreparer({ installations, inspect = inspectNat
if (!authority.current()) return held('Waiting for the original launch request’s authority.')
const found = await inspect(engine, source)
if (!authority.current()) return held('Waiting for the original launch request’s authority.')
- if (found.ok) {
+ if (found.ok || found.cannotRun) {
// A helper can create the executable before finishing its other writes.
// Consult durable history on every ready path, including after a core crash.
+ // An executable that fails meanwhile may be one such half-written install:
+ // held while its installer is unsettled, refused (cannotRun) only after.
const obligation = await installations.status(engine, authority.id, authority.current)
if (!authority.current()) return held('Waiting for the original launch request’s authority.')
return obligation && !obligation.complete ? held(obligation.detail) : found
diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.ts
index 2e19fbeac..2da7d06f8 100644
--- a/cli/src/lib/newCommand.spec.ts
+++ b/cli/src/lib/newCommand.spec.ts
@@ -205,6 +205,63 @@ describe('harness new: the daemon', () => {
expect(slept).toEqual([2_000, 2_000, 2_000])
})
+ it('says what a held launch waits for and, given up on, cancels it so it never starts later', async () => {
+ const held = (detail: string) => ({ state: 'pending', held: { service: 'native', detail } })
+ let asks = 0
+ const socket = new FakeSocket((frame) => {
+ if (frame.type === 'agent_create') return { creationId: frame.payload.creationId, ...held('Installing the required engine.') }
+ if (frame.type === 'agent_create_status') return ++asks < 5 ? held('Installing the required engine.') : held('Waiting to confirm the selected executable’s permission flags.')
+ if (frame.type === 'agent_create_cancel') return { creationId: frame.payload.creationId, state: 'cancelled' }
+ return null
+ })
+ const d = deps(['opencode', '--', 'fix it'], socket, { sleep: async () => {} })
+ expect(await newCommand(d)).toBe(1)
+ // Each reason once, as it changes, then why it stopped.
+ expect(d.err).toEqual([
+ 'Installing the required engine.',
+ 'Waiting to confirm the selected executable’s permission flags.',
+ 'Harness did not start the harness within a minute: Waiting to confirm the selected executable’s permission flags. '
+ + 'The request is cancelled, so it will not start later.',
+ ])
+ expect(asks).toBe(30)
+ const create = socket.sent.find((f) => f.type === 'agent_create')!
+ expect(socket.sent.filter((f) => f.type === 'agent_create_cancel').map((f) => f.payload.creationId)).toEqual([create.payload.creationId])
+ expect(d.out).toEqual([])
+ })
+
+ it('takes what became of a launch it could no longer cancel, and says so when it cannot cancel at all', 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 started = deps(['codex'], answer({ state: 'created', agent: { id: 'h2', name: 'late' } }), { sleep: async () => {} })
+ expect(await newCommand(started)).toBe(0)
+ expect(started.out[0]).toBe('Created late on this computer in /work/repo.')
+ expect(started.err).toEqual([])
+ const refused = deps(['codex'], answer({ state: 'failed', failure: { code: 'ENGINE_CANNOT_RUN', detail: 'Codex is installed but cannot run: env: node: No such file or directory' } }), { sleep: async () => {} })
+ expect(await newCommand(refused)).toBe(1)
+ expect(refused.err).toEqual(['Codex is installed but cannot run: env: node: No such file or directory'])
+ // Claimed just before the cancel: starting now, not later, and not cancelled.
+ const claimed = deps(['codex'], answer({ state: 'unconfirmed' }), { sleep: async () => {} })
+ expect(await newCommand(claimed)).toBe(1)
+ expect(claimed.err).toEqual(['Harness could not confirm the harness started (unconfirmed). Check with `harness ps` before starting another.'])
+ const held = deps(['codex', 'my-game'], answer({ state: 'failed', failure: { code: 'NATIVE_LAUNCH_HELD', detail: 'Waiting to confirm native engine locations.' } }), { sleep: async () => {} })
+ expect(await newCommand(held)).toBe(1)
+ expect(held.err).toEqual(['The agent\'s engine was not ready to start. (Waiting to confirm native engine locations.)'])
+ // A daemon with no cancel (or no answer): the request is still saved, and that is said plainly.
+ const older = deps(['codex', '--json'], answer(null), { sleep: async () => {} })
+ expect(await newCommand(older)).toBe(1)
+ expect(JSON.parse(older.out[0]!)).toEqual({ ok: false, error: 'Harness did not start the harness within a minute. '
+ + 'It is still saved and may start later by itself: check with `harness ps` before starting another.' })
+ expect(older.err).toEqual([])
+ })
+
+ 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))
+ expect(await newCommand(d)).toBe(1)
+ expect(d.err).toEqual(['Codex is installed but cannot run: /usr/bin/env: ‘node’: No such file or directory'])
+ })
+
it('reads the folder off the harness the machine made', async () => {
const socket = new FakeSocket((frame) => frame.type === 'agent_create'
? { state: 'created', agent: { id: 'a1', name: 'fixer', project: { cwd: '/work/repo/.worktrees/x' } } } : null)
diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.ts
index 1c56ac553..a138d5949 100644
--- a/cli/src/lib/newCommand.ts
+++ b/cli/src/lib/newCommand.ts
@@ -252,6 +252,14 @@ const ERRORS: Record<string, string> = {
PROMPT_UNSUPPORTED: 'That agent cannot be started with a first message.',
PROMPT_TOO_LONG: 'A first message holds at most 2,000 characters. Put the rest in a file and name the file in it.',
SPAWN_FAILED: 'The agent could not be started.',
+ // Recorded as a refusal only where a launch cannot be held (a new project's folder): its detail says what it waited for.
+ NATIVE_LAUNCH_HELD: 'The agent\'s engine was not ready to start.',
+}
+
+/** What a held launch waits for, in the daemon's words (`held.detail` of a pending creation), or ''. */
+function holdReason(result: Record<string, unknown>): string {
+ const held = result.held as { detail?: unknown } | undefined
+ return typeof held?.detail === 'string' ? held.detail.replace(/[\x00-\x1f\x7f]/g, ' ').trim().slice(0, 500) : ''
}
/** One loopback session with the daemon: select the machine, then ask, one request at a time. */
@@ -359,19 +367,43 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {
let result = await session.request('agent_create', payload)
// A launch the daemon holds (a native launch waiting its turn) is still on its way: asked after until it is not,
// for a minute. Given up on at once, it could start later with an agent's task and no record of who started it
- // (the review of #1180).
+ // (the review of #1180). What it waits for is said as it changes: the daemon's own words, which used to stay in
+ // the daemon while this said only "could not confirm" (OpenCode and Codex held for good in clean VMs, 2026-10-11).
+ let said = ''
for (let i = 0; i < 30 && (result.state === 'pending' || result.state === 'unconfirmed'); i++) {
+ const reason = holdReason(result)
+ if (reason && reason !== said && !args.json) deps.error(reason)
+ said = reason || said
await (deps.sleep ?? ((ms: number) => new Promise((done) => setTimeout(done, ms))))(2_000)
result = await session.request('agent_create_status', { creationId: payload.creationId })
}
+ // Still held after a minute: cancelled, so it never starts later, task and all, with nobody waiting for it.
+ // The daemon takes a cancel only before the launch is claimed (lib/agentCreationReceipt.ts `cancelIntent`) and
+ // otherwise answers what became of it, which is then the answer here.
+ if (result.state === 'pending') {
+ const reason = holdReason(result) || said
+ const cancelled = await session.request('agent_create_cancel', { creationId: payload.creationId }).catch(() => null)
+ if (cancelled?.state === 'cancelled') {
+ throw new Error(`Harness did not start the harness within a minute${reason ? `: ${reason}` : '.'} `
+ + 'The request is cancelled, so it will not start later.')
+ }
+ // 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(`Harness did not start the harness within a minute${reason ? `: ${reason}` : '.'} `
+ + 'It is still saved and may start later by itself: check with `harness ps` before starting another.')
+ }
+ // Too late to cancel: what became of it (created, refused, or claimed and starting now) is the answer.
+ result = cancelled
+ }
// With a creation id the daemon answers what became of the launch: only `created` made a harness. A refusal
// it recorded (`failed`) and an outcome it could not confirm used to print "Created" all the same.
if (result.state !== undefined && result.state !== 'created') {
const failure = (result.failure ?? {}) as Record<string, unknown>
const code = typeof failure.code === 'string' ? failure.code : ''
- const detail = typeof failure.detail === 'string' && failure.detail ? ` (${failure.detail})` : ''
+ const detail = typeof failure.detail === 'string' && failure.detail ? failure.detail : ''
throw new Error(result.state === 'failed'
- ? `${ERRORS[code] ?? (code || 'The harness could not be started.')}${detail}`
+ // 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.`)
}
const agent = (result.agent ?? {}) as Record<string, unknown>