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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Wait for an engine Harness installs, and leave no folder when a launch fails (#1214)
Deed7d92aa5a6e3
diff --git a/cli/e2e/freshMachineEngines.e2e.ts b/cli/e2e/freshMachineEngines.e2e.tsindex 664d73197..eeb6a8612 100644--- a/cli/e2e/freshMachineEngines.e2e.ts+++ b/cli/e2e/freshMachineEngines.e2e.ts@@ -8,14 +8,17 @@* 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.+ * - A Codex that is not there at all is installed by Harness for a new project (2026-10-12): `harness new` waits for+ * the install and then starts it, or says why it could not be installed, and leaves no folder behind either way.*/import { spawn } from 'node:child_process'-import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, symlinkSync, 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'+import { resolveBinaryOnPath } from '../src/lib/binaryOnPath.js'let daemon: IsolatedDaemon | undefinedafterEach(async () => { await daemon?.close(); daemon = undefined })@@ -141,3 +144,64 @@ it('says what a launch still held after a minute waits for, and cancels it so itexpect((await client.request<{ agents: unknown[] }>('agents_list', { includeStopped: true }, 30_000)).agents).toEqual([])} finally { client.close() }}, 180_000)++it('installs a missing Codex for a new project and starts it there, or says why it could not, leaving no folder', async (context) => {+ // A computer with nothing: no codex, npm or node in the system folders the login shell's PATH names below.+ const system = ['/usr/bin', '/bin', '/usr/sbin', '/sbin']+ if (system.some((dir) => ['codex', 'npm', 'node'].some((name) => existsSync(join(dir, name))))) context.skip()+ let offline = ''+ const d = await boot((d) => {+ const bin = join(d.root, 'bin'), tools = join(d.root, 'tools'), installed = join(d.root, 'codex-package')+ offline = join(d.root, 'npm-offline')+ // What `npm install -g @openai/codex` puts in the prefix is the fake engine's own wrapper; until then, no codex+ // anywhere, so the daemon installs it with the recipe it would use on a person's computer.+ renameSync(join(bin, 'codex'), installed)+ delete d.env.CODEX_PATH+ symlinkSync(process.execPath, join(bin, 'node'))+ writeFileSync(join(bin, 'npm'), `#!/bin/sh+case "$1" in+ prefix) printf '%s\\n' "\${npm_config_prefix:-$HOME/.local}"; exit 0 ;;+ install) ;;+ *) exit 1 ;;+esac+if [ -f ${JSON.stringify(offline)} ]; then+ echo 'npm error code ENOTFOUND' >&2+ echo 'npm error network request to https://registry.npmjs.org/@openai%2fcodex failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org' >&2+ exit 1+fi+sleep 3+mkdir -p "$npm_config_prefix/bin" && cp ${JSON.stringify(installed)} "$npm_config_prefix/bin/codex" && chmod 755 "$npm_config_prefix/bin/codex"+`, { mode: 0o755 })+ mkdirSync(tools)+ symlinkSync(resolveBinaryOnPath('tmux')!, join(tools, 'tmux'))+ // The daemon's own PATH too: no codex of the developer's may be found and run.+ const path = [bin, tools, ...system].join(':')+ d.env.PATH = path+ writeFileSync(join(d.env.HOME!, '.zshrc'), `export PATH=${path}\n`)+ writeFileSync(join(d.env.HOME!, '.bash_profile'), `export PATH=${path}\n`)+ })+ const home = d.env.HOME!, folder = join(home, 'harnesses', 'scratch1')+ const run = () => harness(d, ['new', 'codex', 'scratch1', '--name', 'cx', '--', 'Reply with pong'])+ // Offline: it says it is installing, then why Codex could not be installed, and no folder blocks the same command.+ writeFileSync(offline, '')+ const refused = await run()+ expect(refused.code, refused.out + refused.err).toBe(1)+ expect(refused.err.trim().split('\n')).toEqual(['Installing Codex. The harness starts once it is installed.',+ 'Codex could not be installed: npm error network request to https://registry.npmjs.org/@openai%2fcodex failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org'])+ expect(existsSync(folder)).toBe(false)+ // Online again: the same command installs it, waits, and starts the harness in its new project.+ rmSync(offline)+ const started = await run()+ expect(started.code, started.out + started.err).toBe(0)+ expect(started.err.trim()).toBe('Installing Codex. The harness starts once it is installed.')+ expect(started.out).toContain(`Created cx on this computer in ${folder}.`)+ expect(existsSync(join(home, '.local', 'bin', 'codex'))).toBe(true)+ const client = await LocalClient.connect(d)+ try {+ const agents = await until('Codex to bind its conversation in its new project', async () => {+ const rows = (await client.request<{ agents: Array<Record<string, any>> }>('agents_list', { includeStopped: true }, 30_000)).agents+ return rows.length === 1 && rows[0]!.sessionId && rows[0]!.status === 'active' ? rows : null+ }, 60_000, 500)+ expect(agents[0]).toMatchObject({ name: 'cx' })+ } finally { client.close() }+}, 180_000)diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex a57af20ad..7ac495341 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -294,7 +294,7 @@ describe('creating an agent', () => {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+ const broken = { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail, refusal: 'ENGINE_CANNOT_RUN' } as constexpect(await setup({ native: async () => broken }).create(request())).toEqual({ ok: false, error: 'ENGINE_CANNOT_RUN', detail })expect(createAndRegisterPane).not.toHaveBeenCalled()})diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex 0510c6db8..010ba4fab 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -125,11 +125,12 @@ export function createAgentCreator({bypassPermission = permissionModeApproves(pinnedMode)}const inspected = await inspectNative?.(engine, { ...input, permissionMode, bypassPermission }, authority)- // 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+ // An engine that ran and failed, or whose install for this request 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.refusal ? { ok: false, error: inspected.refusal, detail: inspected.detail } : inspectedconst native = inspected?.ok ? inspected.launch : undefinedif (engine === 'codex' && native) codexHome = nativeHookLocations(native.environment).CODEX_HOMEconst current = () => authority.current() && (!native || native.current())diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.tsindex 806c7ac3a..935f7e15d 100644--- a/cli/src/core/agents/launches.spec.ts+++ b/cli/src/core/agents/launches.spec.ts@@ -1,4 +1,4 @@-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { homedir, tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -520,6 +520,88 @@ describe('agent_create with a receipt', () => {await vi.waitFor(() => expect(replies).toStrictEqual([{ creationId: CREATION, state: 'failed', preparedFolder: '/projects/prepared', failure: { code: 'ENGINE_MISSING' } }]))})+ it('waits for a new project\'s engine to be installed before making its folder, then launches in it', async () => {+ // A fresh Ubuntu VM (2026-10-12): `harness new codex scratch1` was refused at once, its folder made, saying the+ // launch would continue after the install; nothing did, and the folder then refused the same command.+ const installing = { ok: false as const, error: 'NATIVE_LAUNCH_HELD' as const, unavailable: 'native' as const, installing: true as const,+ detail: 'Installing Codex. The harness starts once it is installed.' }+ const prepareEngine = vi.fn<NonNullable<LaunchRequestDeps['prepareEngine']>>().mockResolvedValueOnce(installing)+ .mockResolvedValue({ ok: true, launch: {} as never })+ const dispatch = vi.fn(async () => ({ ok: true as const, session: session('new-agent') }))+ const prepareCreate = vi.fn<NonNullable<LaunchRequestDeps['prepareCreate']>>(async () => ({ ok: true, dispatch }))+ const { ask, replies, create, deps } = setup({ prepareCreate, prepareEngine })+ const payload = { engine: 'codex', projectSource: 'new', projectName: 'scratch1', creationId: CREATION, prompt: 'Reply with pong' }+ await ask(payload)+ await vi.waitFor(() => expect(replies[0]).toMatchObject({ state: 'pending', held: { service: 'install', detail: installing.detail } }))+ expect(prepareProjectFolder).not.toHaveBeenCalled()+ expect(deps.receipts.pendingIntent(CREATION)!.request).toMatchObject({ projectFolder: { source: 'new', name: 'scratch1' }, input: { cwd: '' } })+ await ask(payload)+ await vi.waitFor(() => expect(replies[1]).toMatchObject({ state: 'created', agent: { id: 'new-agent' } }))+ expect(prepareEngine).toHaveBeenCalledWith('codex', expect.objectContaining({ prompt: 'Reply with pong' }), expect.objectContaining({ id: CREATION }))+ expect(prepareProjectFolder).toHaveBeenCalledOnce()+ expect(prepareCreate).toHaveBeenCalledWith(expect.objectContaining({ cwd: '/projects/prepared', prompt: 'Reply with pong' }),+ expect.objectContaining({ id: CREATION, label: expect.stringMatching(/^harness-codex-/) }), { local: true })+ expect(dispatch).toHaveBeenCalledOnce()+ expect(create).not.toHaveBeenCalled()+ })++ it('makes no folder for a new project cancelled while its engine was being made ready', async () => {+ let prepare!: Parameters<typeof pendingLaunches.createPendingLaunches>[0]['prepare']+ const factory = pendingLaunches.createPendingLaunches+ vi.spyOn(pendingLaunches, 'createPendingLaunches').mockImplementation(deps => { prepare = deps.prepare; return factory(deps) })+ let current = true+ const prepareEngine = vi.fn<NonNullable<LaunchRequestDeps['prepareEngine']>>(async () => { current = false; return { ok: true, launch: {} as never } })+ setup({ prepareCreate: vi.fn(), prepareEngine })+ expect(await prepare({ kind: 'native-create-v1', input: { engine: 'codex', cwd: '' }, projectFolder: { source: 'new', name: 'scratch1' },+ label: 'harness-codex-fixture', local: true }, { id: CREATION, current: () => current, hold: vi.fn() })).toBeNull()+ expect(prepareProjectFolder).not.toHaveBeenCalled()+ })++ it('refuses a new project for a harness it does not have at once, before any engine install or folder', async () => {+ const prepareEngine = vi.fn<NonNullable<LaunchRequestDeps['prepareEngine']>>()+ const prepareCreate = vi.fn<NonNullable<LaunchRequestDeps['prepareCreate']>>()+ const { ask, deps } = setup({ prepareCreate, prepareEngine })+ expect(await ask({ engine: 'codex', projectSource: 'new', projectName: 'scratch1', creationId: CREATION, dsh: 'acme/notes' }))+ .toStrictEqual({ error: 'INVALID_DSH', detail: 'acme/notes is not installed on this machine' })+ expect(deps.receipts.status(CREATION)).toEqual({ state: 'missing' })+ expect(prepareEngine).not.toHaveBeenCalled()+ expect(prepareProjectFolder).not.toHaveBeenCalled()+ })++ it('refuses a new project whose engine could not be installed, before any folder exists', async () => {+ const prepareEngine = vi.fn<NonNullable<LaunchRequestDeps['prepareEngine']>>(async () => ({ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native',+ refusal: 'ENGINE_INSTALL_FAILED', detail: 'Codex could not be installed: getaddrinfo ENOTFOUND registry.npmjs.org' }))+ const prepareCreate = vi.fn<NonNullable<LaunchRequestDeps['prepareCreate']>>()+ const { ask, replies } = setup({ prepareCreate, prepareEngine })+ await ask({ engine: 'codex', projectSource: 'new', projectName: 'scratch1', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toStrictEqual([{ creationId: CREATION, state: 'failed',+ failure: { code: 'ENGINE_INSTALL_FAILED', detail: 'Codex could not be installed: getaddrinfo ENOTFOUND registry.npmjs.org' } }]))+ expect(prepareProjectFolder).not.toHaveBeenCalled()+ expect(prepareCreate).not.toHaveBeenCalled()+ })++ it('removes the empty folder a new project made when nothing starts in it, and keeps one that has anything', async () => {+ const made = join(root.projects, 'scratch1')+ vi.mocked(prepareProjectFolder).mockImplementation(async () => { mkdirSync(made); return made })+ const prepareCreate = vi.fn<NonNullable<LaunchRequestDeps['prepareCreate']>>(async () => ({ ok: false, error: 'CODEX_CLI_TOO_OLD', detail: 'Update codex.' }))+ const { ask, replies } = setup({ prepareCreate })+ await ask({ engine: 'codex', projectSource: 'new', projectName: 'scratch1', creationId: CREATION })+ await vi.waitFor(() => expect(replies).toStrictEqual([{ creationId: CREATION, state: 'failed', failure: { code: 'CODEX_CLI_TOO_OLD', detail: 'Update codex.' } }]))+ expect(existsSync(made)).toBe(false)+ prepareCreate.mockImplementationOnce(async () => { writeFileSync(join(made, 'notes.md'), 'kept'); return { ok: false, error: 'CODEX_CLI_TOO_OLD' } })+ await ask({ engine: 'codex', projectSource: 'new', projectName: 'scratch1', creationId: `${CREATION}-2` })+ await vi.waitFor(() => expect(replies[1]).toStrictEqual({ creationId: `${CREATION}-2`, state: 'failed', preparedFolder: made, failure: { code: 'CODEX_CLI_TOO_OLD' } }))+ expect(existsSync(join(made, 'notes.md'))).toBe(true)+ })++ it('holds a launch whose engine Harness is installing under install', async () => {+ const prepareCreate = vi.fn<NonNullable<LaunchRequestDeps['prepareCreate']>>(async () => ({ ok: false, error: 'NATIVE_LAUNCH_HELD',+ unavailable: 'native', installing: true, detail: 'Installing Codex. The harness starts once it is installed.' }))+ const { ask, replies } = setup({ prepareCreate })+ await ask({ engine: 'codex', cwd: '/fixture/work', creationId: CREATION })+ await vi.waitFor(() => expect(replies[0]).toMatchObject({ state: 'pending', held: { service: 'install', detail: 'Installing Codex. The harness starts once it is installed.' } }))+ })+it('trusts only a folder it just made empty, or a worktree of a repository the engine already trusts', async () => {vi.spyOn(console, 'warn').mockImplementation(() => {})const { ask, replies } = setup()@@ -647,7 +729,8 @@ describe('durable model request validation', () => {const prepareCreate = vi.fn<NonNullable<LaunchRequestDeps['prepareCreate']>>()const { deps, requests, create } = setup({ prepareCreate })const records = [{ kind: 'future-kind' }, { kind: 'model-create-v1', local: true, input: {}, selection: {} },- { kind: 'native-create-v1' }, { kind: 'native-create-v1', local: true, input: {}, label: 'harness-claude-fixture' }]+ { kind: 'native-create-v1' }, { kind: 'native-create-v1', local: true, input: {}, label: 'harness-claude-fixture' },+ { kind: 'native-create-v1', local: true, input: { engine: 'claude', cwd: '' }, label: 'harness-claude-fixture', projectFolder: { source: 7 } }]const held = { service: 'models', detail: 'Waiting for the model.' }for (const [n, request] of records.entries()) {await deps.receipts.runIntent(`${CREATION}-${n}`, creationFingerprint(request), request, held, async () => null)diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsindex 112bb728e..c273a4e74 100644--- a/cli/src/core/agents/launches.ts+++ b/cli/src/core/agents/launches.ts@@ -8,16 +8,17 @@* Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md), with the* receipts the socket used to hold.*/-import { readdir } from 'node:fs/promises'+import { readdir, rmdir } from 'node:fs/promises'import { homedir } from 'node:os'import { dirname, isAbsolute } from 'node:path'import type { BackendSocket } from '../../backendSocket.js'import { installedDsh } from '../../dsh/installed.js'import { DSH_ID_RE, dshSupportedEngines } from '../../dsh/manifest.js'import { folderTrust } from '../../engines/launchPrep.js'+import type { NativeLaunchResult, NativeLaunchSource } from '../../engines/nativeLaunch.js'import * as opencodeLaunch from '../../engines/launchControl.js'import { ENGINES, isTerminalEngine, type AgentEngine } from '../../engines/types.js'-import { AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationOutcome, type AgentCreationReceipts, type AgentCreationStatus } from '../../lib/agentCreationReceipt.js'+import { AgentCreationReceiptError, creationFingerprint, validCreationId, type AgentCreationOutcome, type AgentCreationReceipts, type AgentCreationStatus, type CreationAuthority } from '../../lib/agentCreationReceipt.js'import type { AgentFrame } from '../../lib/agentFrame.js'import { engineLabel } from '../../lib/agentNames.js'import {@@ -55,6 +56,9 @@ export interface LaunchRequestDeps {/** Each launch, read when a request comes in: null on a machine that cannot launch agents. */createAgent: () => CreateAgent | nullprepareCreate?: (input: Parameters<CreateAgent>[0], authority: LaunchAuthority, context?: { local: boolean }) => Promise<LaunchPreparation<Awaited<ReturnType<CreateAgent>>>>+ /** The engine itself made ready, installed first when it is missing (engines/prepareNativeLaunch.ts): what a new+ * project waits for before its folder is made. */+ prepareEngine?: (engine: CreateInput['engine'], source: NativeLaunchSource, authority: Pick<CreationAuthority, 'id' | 'current'>) => Promise<NativeLaunchResult>forkAgent: () => ForkAgent | nullresumeAgent: () => ResumeAgent | nullrestartAgent: () => RestartAgent | null@@ -68,9 +72,9 @@ export interface LaunchRequestDeps {}type Reply = (result: Record<string, unknown>) => void+type CreateInput = Parameters<CreateAgent>[0]-export function createLaunchRequests({ receipts, createAgent, prepareCreate, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget }: LaunchRequestDeps) {- type CreateInput = Parameters<CreateAgent>[0]+export function createLaunchRequests({ receipts, createAgent, prepareCreate, prepareEngine, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget }: LaunchRequestDeps) {const validateInstalled = async (input: CreateInput, known?: ReturnType<typeof installedDsh>): Promise<{ error: string; detail: string } | null> => {if (input.dsh) {const installed = known ?? installedDsh(input.dsh)@@ -92,11 +96,14 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, for}const { dsh, resumeSessionId } = inputlet preparedFolder: string | undefined+ /** A new project's folder, which this made empty: removed again if nothing starts in it. */+ let made: string | undefinedlet scmLaunchRecord: ScmLaunchRecord | null = nullif (projectFolder) {try {preparedFolder = await prepareProjectFolder(projectFolder, { label: (dsh ? installedDsh(dsh)?.manifest.name : null) ?? engineLabel(input.engine),onPrepared: prepared => { scmLaunchRecord = prepared.scmLaunchRecord } })+ if (projectFolder.source === 'new') made = preparedFolder}catch (error) {return { state: 'failed', error: error instanceof ProjectFolderError ? error.code : 'PROJECT_PREPARATION_FAILED',@@ -138,6 +145,10 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, for// tmux may have executed before a timeout; registration cleanup is best-effort.// Neither can prove that no process started, so never encourage another launch.if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }+ // A new project's folder that nothing started in goes again while it is still empty: left, it made the same+ // `harness new codex scratch1` refuse its own name ("already exists", a fresh Ubuntu VM, 2026-10-12). rmdir+ // removes only an empty folder, so anything put there meanwhile stays, and the folder is then reported.+ if (made && await rmdir(made).then(() => true, () => false)) preparedFolder = undefinedreturn { state: 'failed', error: result.error, ...(preparedFolder ? { preparedFolder } : {}), ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }}@@ -148,7 +159,10 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, forif (!prepareCreate || typeof saved.local !== 'boolean' || !saved.input || typeof saved.input !== 'object'|| typeof saved.label !== 'string' || !/^harness-[a-z0-9-]+$/.test(saved.label)) return nullconst input = structuredClone(saved.input) as CreateInput- if (!ENGINES.includes(input.engine) || typeof input.cwd !== 'string' || input.resumeSessionId) return null+ const projectFolder = (saved.projectFolder ?? null) as ProjectFolder | null+ if (!ENGINES.includes(input.engine) || typeof input.cwd !== 'string' || input.resumeSessionId+ || (projectFolder !== null && typeof projectFolder.source !== 'string')) return null+ const { local, label } = savedif (saved.selection) {authority.hold(modelHold)const target = await modelTarget(saved.selection as NewAgentModel)@@ -157,11 +171,35 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, forinput.grid = targetauthority.hold(launchHold)}- const ready = await prepareCreate(input, { ...authority, label: saved.label }, { local: saved.local })+ // An engine Harness is installing for this launch holds it under `install`, which `harness new` waits longer+ // for than any other hold (lib/newCommand.ts): installs take a minute on a fresh computer.+ const held = (ready: { installing?: boolean; unavailable?: string; detail?: string }) =>+ authority.hold({ service: ready.installing ? 'install' : ready.unavailable!, detail: ready.detail ?? 'Waiting for launch preparation.' })+ const refused = (ready: { error: string; detail?: string }) => async (): Promise<AgentCreationOutcome> =>+ ({ state: 'failed', error: ready.error, ...(ready.detail ? { detail: ready.detail.slice(0, 2000) } : {}) })+ if (projectFolder) {+ // A new project waits for its engine before its folder is made, so a launch still waiting for an install leaves+ // nothing behind when it is cancelled or the install fails. It used to be refused at once, folder made, saying+ // "the saved launch continues after installation" of a launch that was over (a fresh Ubuntu VM, 2026-10-12).+ // The folder, the engine's final preparation and the launch are then one claimed effect, as they always were+ // for a project: a refusal there is its outcome, never a hold.+ const engine = prepareEngine ? await prepareEngine(input.engine, input, authority) : null+ if (!authority.current()) return null+ if (engine && !engine.ok) {+ if (engine.refusal) return refused({ error: engine.refusal, detail: engine.detail })+ held(engine); return null+ }+ const invoke: CreateAgent = async (prepared) => {+ const ready = await prepareCreate(prepared, { ...authority, label }, { local })+ return ready.ok ? ready.dispatch() : { ok: false, error: ready.error, ...(ready.detail ? { detail: ready.detail } : {}) }+ }+ return () => executeCreate(input, projectFolder, local, invoke)+ }+ const ready = await prepareCreate(input, { ...authority, label }, { local })if (!authority.current()) return nullif (!ready.ok) {- if (ready.unavailable) { authority.hold({ service: ready.unavailable, detail: ready.detail ?? 'Waiting for launch preparation.' }); return null }- return async () => ({ state: 'failed', error: ready.error, ...(ready.detail ? { detail: ready.detail.slice(0, 2000) } : {}) })+ if (ready.unavailable) { held(ready); return null }+ return refused(ready)}return async () => {if (!authority.current()) return { state: 'unconfirmed' }@@ -366,13 +404,16 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, forconst create = onCreateAgenttry {const fingerprint = creationFingerprint(projectFolder ? { ...fingerprintInput, projectFolder } : fingerprintInput)- const durableNative = !!prepareCreate && !projectFolder && !resumeSessionId- if (!durableNative && model.state !== 'ok' && !receipts.has(creationId, fingerprint)) {+ // A new project too, which waits for its engine as any other create does (above).+ const durableNative = !!prepareCreate && !resumeSessionId+ // A new project is refused at once for a harness or named agent it cannot have, as it always was, rather than+ // after its engine is installed and its folder made.+ if ((!durableNative || projectFolder) && model.state !== 'ok' && !receipts.has(creationId, fingerprint)) {const refusal = await validateInstalled(input, installed)if (refusal) { reply(refusal); return }}const operation = durableNative- ? pending.start(creationId, fingerprint, { kind: 'native-create-v1', input,+ ? pending.start(creationId, fingerprint, { kind: 'native-create-v1', input, ...(projectFolder ? { projectFolder } : {}),selection: model.state === 'ok' ? model.selection : null, label: buildHarnessSessionLabel(engine), local: asker.local }, model.state === 'ok' ? modelHold : launchHold): model.state === 'ok'? pending.start(creationId, fingerprint, { kind: 'model-create-v1', input, selection: model.selection, projectFolder, local: asker.local }, modelHold)diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex eb8e4dac5..ad93413a4 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -2468,7 +2468,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {const launches = createLaunchRequests({receipts: new AgentCreationReceipts(join(env.ADAPTER_DATA_DIR, 'agent-creations')),createAgent: () => backend.onCreateAgent, forkAgent: () => backend.onForkAgent,- prepareCreate: creator.prepare,+ prepareCreate: creator.prepare, prepareEngine: prepareNativeLaunch,resumeAgent: () => lifecycle.resumeAgent, restartAgent: () => restartAgent,byAgent: (id) => registry.byAgent(id), toProject: (s) => backend.toProject(s),modelTarget: (selection) => (ports.models ?? MODELS_OFF).launchTarget(selection),diff --git a/cli/src/engines/kit/nativeInstall.spec.ts b/cli/src/engines/kit/nativeInstall.spec.tsindex 3c74b21b7..dc3de8f07 100644--- a/cli/src/engines/kit/nativeInstall.spec.ts+++ b/cli/src/engines/kit/nativeInstall.spec.ts@@ -1,6 +1,6 @@import { spawn } from 'node:child_process'import { createHash } from 'node:crypto'-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, expect, it, vi } from 'vitest'@@ -103,16 +103,55 @@ it('does not treat a dangling authority leaf as missing through a parent alias',expect(install.dispatch).not.toHaveBeenCalled()})-it('holds a failed installation across different request IDs and a reconstructed core', async () => {+it('refuses a failed installation to its own request in its output\'s words, and installs again for a new one', async () => {const install = controller()await install.ensure('opencode', recipe, environment, 'failed-request', () => true)- complete(undefined, 1)- expect(await controller().status('opencode', 'new-request', () => true)).toMatchObject({ complete: false })- expect(await controller().ensure('opencode', recipe, environment, 'new-request', () => true)).toMatchObject({ complete: false })+ // What npm printed when a fresh computer could not reach its registry: the line that says what failed.+ const file = join(directory, '00000000.json'), text = readFileSync(file, 'utf8'), claim = JSON.parse(text)+ writeFileSync(`${file}.result`, JSON.stringify({ token: claim.token, claim: hash(text), code: 1, signal: null, detail: [+ 'harness: engine is missing — installing it in this terminal', 'npm error code ENOTFOUND',+ 'npm error network request to https://registry.npmjs.org/opencode-ai failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org',+ 'npm error A complete log of this run can be found in: /fixture/_logs/debug-0.log',+ 'harness: the install failed, so the agent was not started. The command is above; fix it and create the agent again.',+ ].join('\n') }), { mode: 0o600 })+ const failed = { complete: false, failed: true,+ detail: 'npm error network request to https://registry.npmjs.org/opencode-ai failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org' }+ // Never run again for that request, across a reconstructed core, whether or not an executable appeared.+ expect(await controller().ensure('opencode', recipe, environment, 'failed-request', () => true)).toEqual(failed)+ expect(await controller().status('opencode', 'failed-request', () => true)).toEqual(failed)+ // A new request is a new attempt: an executable that is there is used, and one that is not is installed again.+ expect(await controller().status('opencode', 'new-request', () => true)).toBeNull()+ const again = controller()+ expect(await again.ensure('opencode', recipe, environment, 'new-request', () => true)).toMatchObject({ complete: false, running: true })+ expect(again.dispatch).toHaveBeenCalledOnce()expect(await controller().status('codex', 'unrelated-request', () => true)).toBeNull()expect(install.dispatch).toHaveBeenCalledOnce()})+it('stops saying an installer whose helper never settled is installing, without ever replaying it', async () => {+ const install = controller()+ expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ running: true })+ expect(await controller().ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ running: true })+ expect(await controller().status('opencode', 'other', () => true)).toMatchObject({ running: true })+ // A reboot during the install: no result, ever, and the dispatch older than the helper's 20 minutes.+ const witness = `${directory}.00000000.dispatch`, past = new Date(Date.now() - 30 * 60_000)+ utimesSync(witness, past, past)+ const stale = await controller().ensure('opencode', recipe, environment, 'request', () => true)+ expect(stale).toEqual({ complete: false, detail: 'Waiting for the dispatched installer result. An uncertain dispatch is never repeated.' })+ expect(await controller().status('opencode', 'other', () => true)).not.toHaveProperty('running')+ expect(install.dispatch).toHaveBeenCalledOnce()+})++it('says how an installer that printed nothing ended', async () => {+ const install = controller()+ await install.ensure('opencode', recipe, environment, 'request', () => true)+ const file = join(directory, '00000000.json'), text = readFileSync(file, 'utf8'), claim = JSON.parse(text)+ writeFileSync(`${file}.result`, JSON.stringify({ token: claim.token, claim: hash(text), code: null, signal: 'SIGKILL' }), { mode: 0o600 })+ expect(await controller().ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ failed: true, detail: 'its installer was stopped (SIGKILL)' })+ writeFileSync(`${file}.result`, JSON.stringify({ token: claim.token, claim: hash(text), code: 2, signal: null }), { mode: 0o600 })+ expect(await controller().ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ failed: true, detail: 'its installer exited with status 2' })+})+it('retains one durable installation across duplicate requests and a reconstructed core', async () => {const install = controller()expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })diff --git a/cli/src/engines/kit/nativeInstall.ts b/cli/src/engines/kit/nativeInstall.tsindex da20f4ed8..3278d97e7 100644--- a/cli/src/engines/kit/nativeInstall.ts+++ b/cli/src/engines/kit/nativeInstall.ts@@ -5,6 +5,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type Biimport { basename, dirname, isAbsolute, join } from 'node:path'import { buildEngineInstallationArgv } from '../../lib/engineLaunch.js'import type { EngineInstallRecipe } from '../../lib/engineInstall.js'+import { failureReason } from '../../lib/failureReason.js'import { managedNodePath } from '../../lib/nodeRuntime.js'import { secureStateDirectory } from '../../lib/secureState.js'import type { AgentEngine } from '../types.js'@@ -33,8 +34,19 @@ interface Claim {}interface Dispatch { token: string; claim: string; kind: 'run' | 'cancelled' }interface Result { token: string; claim: string; code: number | null; signal: string | null; notDispatched?: true; detail?: string }-export type NativeInstallation = { complete: true } | { complete: false; detail: string }+/** `running`: an installer is dispatched and has not settled. `failed`: this request's own installer settled with a+ * failure, and `detail` is why, in its output's words; it is never run again for this request. */+export type NativeInstallation = { complete: true } | { complete: false; detail: string; running?: true; failed?: true }const hold = (detail: string): NativeInstallation => ({ complete: false, detail })+const running = (detail: string): NativeInstallation => ({ complete: false, detail, running: true })+// The helper ends its installer at 20 minutes and then records the result. A dispatch older than that with no result+// is a helper that died (a reboot during an install): it is never replayed, and no longer said to be installing, which+// `harness new` would otherwise wait on for minutes at every attempt.+const INSTALLER_SETTLES_MS = 1_200_000 + 60_000+const installing = (dispatched: { file: string } | undefined, detail: string): NativeInstallation => {+ try { if (dispatched && Date.now() - lstatSync(dispatched.file).mtimeMs < INSTALLER_SETTLES_MS) return running(detail) } catch { /* A vanished record is not a live installer. */ }+ return hold(detail)+}/** Never read a growing journal file without a bound, or tighten foreign permissions to trust it. */function readRecord(file: string): { text: string; file: string; stamp: string; facts: NativePathFact[]; verify(): void } {@@ -234,11 +246,16 @@ export function createNativeInstallations({ directory, node = managedNodePath, d|| (result.notDispatched !== true && (result.code === null) === (result.signal === null))|| (result.notDispatched !== undefined && (result.notDispatched !== true || result.code !== null || result.signal !== null))|| (marker.kind === 'cancelled' && result.notDispatched !== true)) throw Error('Invalid installation result')- if (claim.engine === engine && !result.notDispatched && (result.code !== 0 || result.signal !== null)) {- return hold('The engine installer stopped before it was ready. Its saved result requires repair confirmation before any launch of this engine.')- }+ // A settled failure is certain, not an uncertain dispatch. This request's own is never run again: its+ // launch is refused with the installer's words. Another request's no longer holds every later launch of+ // the engine, as it did with nothing that could release it: a person asking again is a new attempt, with+ // an installer of its own (a fresh Ubuntu VM, 2026-10-12, where one failed install would have ended+ // every later `harness new` of that engine).if (claim.request === request && !result.notDispatched) {- if (result.code !== 0 || result.signal !== null) return hold('The engine installer stopped before it was ready. Its saved result prevents an uncertain replay; repair the installation before continuing.')+ if (result.code !== 0 || result.signal !== null) {+ return { complete: false, failed: true, detail: failureReason(typeof result.detail === 'string' ? result.detail : '',+ result.signal ? `its installer was stopped (${result.signal})` : `its installer exited with status ${result.code}`) }+ }complete = true}lastResult = { file: `${file}.result`, record: resultRecord }@@ -283,7 +300,7 @@ export function createNativeInstallations({ directory, node = managedNodePath, d}if (complete && !pending) return { complete: true }if (query) return pending && (pending.claim.engine === engine || pending.claim.request === request)- ? hold('Waiting for the saved installer to settle. An executable appearing before completion is not installation authority.')+ ? installing(pending.slot, 'Waiting for the saved installer to settle. An executable appearing before completion is not installation authority.'): complete ? { complete: true } : nullif (!pending && names.length >= MAX_INSTALLATIONS) return hold('The engine installation history is full. Its saved records need review before another installation.')// HOME gets a fresh budget after history enumeration and yields.@@ -302,7 +319,7 @@ export function createNativeInstallations({ directory, node = managedNodePath, dconst claimCurrent = () => { try { authority!.verify(); claimed.verify(); verifyNativePathFacts(claim.routes); return physical() } catch { return false } }const result = JSON.stringify({ token: claim.token, claim: hash, code: null, signal: null, notDispatched: true } satisfies Result)if (pending?.slot) {- return hold('Waiting for the dispatched installer result. An uncertain dispatch is never repeated.')+ return installing(pending.slot, 'Waiting for the dispatched installer result. An uncertain dispatch is never repeated.')}// A missing outside witness with an inside sentinel is a lost history, not a new dispatch.if (maybe(`${file}.dispatch`)) return hold('The installer dispatch witness is missing; its previous worker may still own the installation.')@@ -320,7 +337,7 @@ export function createNativeInstallations({ directory, node = managedNodePath, d}if (!dispatchCurrent()) return hold('Waiting to confirm the installer claim.')dispatch(runtime, file, hash)- return hold('Installing the required engine. The saved launch continues after installation is confirmed.')+ return running('Installing the required engine. The saved launch continues after installation is confirmed.')} catch { return hold('Waiting to confirm durable engine installation ownership.') }}const ensure = async (engine: AgentEngine, recipe: EngineInstallRecipe, environment: Record<string, string>, request: string, current: () => boolean): Promise<NativeInstallation> =>diff --git a/cli/src/engines/nativeLaunch.probe.spec.ts b/cli/src/engines/nativeLaunch.probe.spec.tsindex 5858b6120..f58ad7a42 100644--- a/cli/src/engines/nativeLaunch.probe.spec.ts+++ b/cli/src/engines/nativeLaunch.probe.spec.ts@@ -96,5 +96,5 @@ it('reads help an engine prints to standard error, as OpenCode 1.19.0 does', asyit('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 })+ detail: 'Codex is installed but cannot run: /usr/bin/env: ‘node’: No such file or directory', refusal: 'ENGINE_CANNOT_RUN' })}, 15_000)diff --git a/cli/src/engines/nativeLaunch.spec.ts b/cli/src/engines/nativeLaunch.spec.tsindex b9de9f0fb..2b4a403a3 100644--- a/cli/src/engines/nativeLaunch.spec.ts+++ b/cli/src/engines/nativeLaunch.spec.ts@@ -56,7 +56,7 @@ it('says why an OpenCode that ran and failed cannot run, and waits for one that// 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,+ expect(await inspectNativeLaunch('opencode')).toMatchObject({ ok: false, refusal: 'ENGINE_CANNOT_RUN',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' })@@ -65,11 +65,11 @@ it('says why an OpenCode that ran and failed cannot run, and waits for one thatfixture.current = falseconst changing = await inspectNativeLaunch('opencode')expect(changing).toMatchObject({ ok: false, unavailable: 'native' })- expect(changing).not.toHaveProperty('cannotRun')+ expect(changing).not.toHaveProperty('refusal')})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,+ expect(await inspectNativeLaunch('claude', { permissionMode: 'auto' })).toMatchObject({ refusal: 'ENGINE_CANNOT_RUN',detail: 'Claude Code is installed but cannot run: env: node: No such file or directory' })})diff --git a/cli/src/engines/nativeLaunch.ts b/cli/src/engines/nativeLaunch.tsindex de8723c43..9b2d88513 100644--- a/cli/src/engines/nativeLaunch.ts+++ b/cli/src/engines/nativeLaunch.ts@@ -2,7 +2,8 @@import { execFile } from 'node:child_process'import { randomUUID } from 'node:crypto'import { isAbsolute, join } from 'node:path'-import { engineLabel } from '../lib/agentNames.js'+import { engineName } from '../lib/agentNames.js'+import { failureReason } from '../lib/failureReason.js'import { permissionFlagToVerify, type PermissionLaunchChoice } from '../lib/engineLaunch.js'import type { EngineInstallRecipe } from '../lib/engineInstall.js'import { patientDeadline } from '../lib/patientExec.js'@@ -37,12 +38,15 @@ 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>- /** 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 }+ /** No wait ends this by itself: the selected executable ran and failed, or this request's own installer+ * did. A creation is refused with this code rather than held (core/agents/create.ts); a relaunch,+ * which nobody is waiting on, still holds. */+ refusal?: 'ENGINE_CANNOT_RUN' | 'ENGINE_INSTALL_FAILED'+ /** Harness is installing the engine for this launch (engines/prepareNativeLaunch.ts). */+ installing?: 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 })+ ({ ...waiting(`${engineName(engine)} is installed but cannot run: ${reason}`), refusal: 'ENGINE_CANNOT_RUN' })const noNative: NativeLaunch = {opencodeMajor: null, environment: {}, proofs: [], current: () => true,prepareHooks: async () => true, permission: async () => 'supported',@@ -90,18 +94,6 @@ 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 } = {},@@ -130,7 +122,7 @@ export async function inspectNativeLaunch(engine: AgentEngine, source: NativeLauconst output = engine === 'opencode' ? await read(executable.command, OPENCODE_VERSION.args, environment) : null// 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))+ if (output && output.code !== 0 && executable.current()) return cannotRun(engine, failureReason(`${output.stderr}\n${output.stdout}`, `it exited with status ${output.code}`))// 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.')@@ -197,7 +189,7 @@ export async function inspectNativeLaunch(engine: AgentEngine, source: NativeLaufailed = nullconst probe = await read(executable.command, ['--help'], selectedEnvironment)if (!probe || !current() || observedRevision !== revision) return 'unknown'- if (probe.code !== 0) { failed = failureReason(probe); return 'unknown' }+ if (probe.code !== 0) { failed = failureReason(`${probe.stderr}\n${probe.stdout}`, `it exited with status ${probe.code}`); 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 helddiff --git a/cli/src/engines/prepareNativeLaunch.spec.ts b/cli/src/engines/prepareNativeLaunch.spec.tsindex 19c478651..b69bf9785 100644--- a/cli/src/engines/prepareNativeLaunch.spec.ts+++ b/cli/src/engines/prepareNativeLaunch.spec.ts@@ -54,10 +54,28 @@ it('does not mistake a newly visible executable for its still-running installer})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 broken: NativeLaunchResult = { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Codex is installed but cannot run: fixture', refusal: 'ENGINE_CANNOT_RUN' }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)})++it('names the engine it is installing, and refuses a launch whose own installer failed', async () => {+ const ensure = vi.fn().mockResolvedValueOnce({ complete: false, running: true, detail: 'Installing the required engine.' })+ .mockResolvedValueOnce({ complete: false, failed: true, detail: 'npm error network request failed' })+ const status = vi.fn().mockResolvedValueOnce({ complete: false, running: true, detail: 'Waiting for the saved installer to settle.' })+ .mockResolvedValueOnce({ complete: false, failed: true, detail: 'its installer exited with status 1' })+ const inspect = vi.fn().mockResolvedValueOnce(absent).mockResolvedValueOnce(absent).mockResolvedValue(ready)+ const prepare = createNativeLaunchPreparer({ installations: { ensure, status }, inspect })+ const authority = { id: 'fixture-request', current: () => true }+ const installing = { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', installing: true,+ detail: 'Installing Claude Code. The harness starts once it is installed.' }+ expect(await prepare('claude', {}, authority)).toEqual(installing)+ expect(await prepare('codex', {}, authority)).toEqual({ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native',+ refusal: 'ENGINE_INSTALL_FAILED', detail: 'Codex could not be installed: npm error network request failed' })+ // The executable is there, its installer not yet settled or settled with a failure.+ expect(await prepare('claude', {}, authority)).toEqual(installing)+ expect(await prepare('codex', {}, authority)).toMatchObject({ refusal: 'ENGINE_INSTALL_FAILED', detail: 'Codex could not be installed: its installer exited with status 1' })+})diff --git a/cli/src/engines/prepareNativeLaunch.ts b/cli/src/engines/prepareNativeLaunch.tsindex c2dd14fad..73bacc2fc 100644--- a/cli/src/engines/prepareNativeLaunch.ts+++ b/cli/src/engines/prepareNativeLaunch.ts@@ -1,5 +1,6 @@import type { CreationAuthority } from '../lib/agentCreationReceipt.js'-import type { createNativeInstallations } from './kit/nativeInstall.js'+import type { createNativeInstallations, NativeInstallation } from './kit/nativeInstall.js'+import { engineName } from '../lib/agentNames.js'import { inspectNativeLaunch, type NativeLaunchResult, type NativeLaunchSource } from './nativeLaunch.js'import type { AgentEngine } from './types.js'@@ -11,22 +12,29 @@ export function createNativeLaunchPreparer({ installations, inspect = inspectNat}) {return async (engine: AgentEngine, source: NativeLaunchSource, authority: Pick<CreationAuthority, 'id' | 'current'>): Promise<NativeLaunchResult> => {source = { ...source }- const held = (detail: string): NativeLaunchResult => ({ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail })+ const held = (detail: string): Extract<NativeLaunchResult, { ok: false }> => ({ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail })+ // What an unfinished installation means for this launch, in words a person waiting reads: an installer at work+ // says which engine (`harness new` waits longer for it, lib/newCommand.ts); this request's own failed installer+ // is a refusal with its reason, never a hold that says the launch continues (a fresh Ubuntu VM, 2026-10-12).+ const unfinished = (installation: Extract<NativeInstallation, { complete: false }>): NativeLaunchResult =>+ installation.failed ? { ...held(`${engineName(engine)} could not be installed: ${installation.detail}`), refusal: 'ENGINE_INSTALL_FAILED' }+ : installation.running ? { ...held(`Installing ${engineName(engine)}. The harness starts once it is installed.`), installing: true }+ : held(installation.detail)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 || found.cannotRun) {+ if (found.ok || found.refusal) {// 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.+ // held while its installer is unsettled, refused 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+ return obligation && !obligation.complete ? unfinished(obligation) : found}if (!found.install || !found.environment) return foundconst installed = await installations.ensure(engine, found.install, found.environment, authority.id, authority.current)- if (!installed.complete) return held(installed.detail)+ if (!installed.complete) return unfinished(installed)if (!authority.current()) return held('Waiting for the original launch request’s authority.')const prepared = await inspect(engine, source)return authority.current() ? prepared : held('Waiting for the original launch request’s authority.')diff --git a/cli/src/lib/agentNames.ts b/cli/src/lib/agentNames.tsindex bbb1bba7e..828e3c385 100644--- a/cli/src/lib/agentNames.ts+++ b/cli/src/lib/agentNames.ts@@ -34,6 +34,11 @@ export function engineLabel(engine: string): string {return ENGINE_LABELS[engine as AgentEngine] ?? engine}+/** An engine's name in a sentence: Claude Code by its whole name, as its install says it. */+export function engineName(engine: string): string {+ return engine === 'claude' ? 'Claude Code' : engineLabel(engine)+}+const pad = (n: number): string => String(n).padStart(2, '0')/**diff --git a/cli/src/lib/failureReason.ts b/cli/src/lib/failureReason.tsnew file mode 100644index 000000000..3837cf7fc--- /dev/null+++ b/cli/src/lib/failureReason.ts@@ -0,0 +1,15 @@+/**+ * Why a program that exited with a failure failed, in its own words: one line of what it printed.+ *+ * The line that says what failed comes first ("No such file or directory", "Could not resolve host",+ * "… failed, reason: getaddrinfo ENOTFOUND …"), then one that names an error, then the first line. A+ * Node stack trace starts with a source location and ends with the Node version, and npm ends with+ * where its log is, so neither end is the reason. Harness's own lines in an installer's output+ * (`harness: …`) are never the reason. [otherwise] is said when it printed nothing at all.+ */+export function failureReason(output: string, otherwise: string): string {+ const lines = output.split('\n').map(line => line.replace(/[\x00-\x1f\x7f]/g, ' ').trim()).filter(line => line && !line.startsWith('harness:'))+ const line = lines.find(text => /\b(failed|could not|cannot|can't|no such|not found|denied|refused|timed out|unable|missing)\b/i.test(text))+ ?? lines.find(text => /\berror\b/i.test(text)) ?? lines[0]+ return line ? line.slice(0, 300) : otherwise+}diff --git a/cli/src/lib/launchPreparation.ts b/cli/src/lib/launchPreparation.tsindex 9ecfcbaf4..4aedf6f04 100644--- a/cli/src/lib/launchPreparation.ts+++ b/cli/src/lib/launchPreparation.ts@@ -6,4 +6,6 @@ export interface LaunchAuthority extends CreationAuthority { readonly label: strexport type LaunchPreparation<Result> =| { ok: true; dispatch: () => Promise<Result> }- | { ok: false; error: string; detail?: string; unavailable?: string }+ | { ok: false; error: string; detail?: string; unavailable?: string+ /** The engine is being installed for this launch (engines/prepareNativeLaunch.ts): its hold names the install. */+ installing?: boolean }diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.tsindex 3ed364025..483d289ce 100644--- a/cli/src/lib/newCommand.spec.ts+++ b/cli/src/lib/newCommand.spec.ts@@ -265,6 +265,38 @@ describe('harness new: the daemon', () => {expect(d.out).toEqual([])})+ it('waits for an engine Harness is installing, saying so once, then starts the harness', async () => {+ // A fresh Ubuntu VM (2026-10-12): Codex took about a minute to install, the whole of the wait every other hold gets.+ const installing = { state: 'pending', held: { service: 'install', detail: 'Installing Codex. The harness starts once it is installed.' } }+ let asks = 0+ const socket = new FakeSocket((frame) => frame.type === 'agent_create' ? installing+ : frame.type === 'agent_create_status' ? (++asks < 60 ? installing : asks < 70 ? { state: 'pending', held: { service: 'native', detail: 'Waiting to confirm the engine’s native hooks.' } }+ : { state: 'created', agent: { id: 'h3', name: 'cx' } }) : null)+ const d = deps(['codex', '--', 'Reply with pong'], socket, { sleep: async () => {} })+ expect(await newCommand(d)).toBe(0)+ expect(d.err).toEqual(['Installing Codex. The harness starts once it is installed.', 'Waiting to confirm the engine’s native hooks.'])+ expect(d.out[0]).toBe('Created cx on this computer in /work/repo.')+ expect(socket.sent.some((f) => f.type === 'agent_create_cancel')).toBe(false)+ })++ it('gives an install five minutes, then says plainly it is still installing and that this request will not start', async () => {+ let asks = 0+ const socket = new FakeSocket((frame) => frame.type === 'agent_create_cancel' ? { state: 'cancelled' }+ : (frame.type === 'agent_create_status' && ++asks, { state: 'pending', held: { service: 'install', detail: 'Installing Claude Code. The harness starts once it is installed.' } }))+ const d = deps(['claude'], socket, { sleep: async () => {} })+ expect(await newCommand(d)).toBe(1)+ expect(asks).toBe(180)+ expect(d.err.at(-1)).toBe('Harness is still installing Claude Code. Run the same command again in a minute; this request is cancelled, so it will not start later.')+ // A hold after an install has finished is given its minute, and then said as the hold it is.+ asks = 0+ const after = new FakeSocket((frame) => frame.type === 'agent_create_cancel' ? null+ : (frame.type === 'agent_create_status' && ++asks, asks < 10 ? { state: 'pending', held: { service: 'install', detail: 'Installing Codex.' } } : { state: 'pending', held: { service: 'native', detail: 'Waiting.' } }))+ const late = deps(['codex'], after, { sleep: async () => {} })+ expect(await newCommand(late)).toBe(1)+ expect(asks).toBe(39)+ expect(late.err.at(-1)).toBe('Harness did not start the harness in time: Waiting. It is still saved and may start later by itself: check with `harness ps` before starting another.')+ })+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' }diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.tsindex 170474d25..0206542ff 100644--- a/cli/src/lib/newCommand.ts+++ b/cli/src/lib/newCommand.ts@@ -465,8 +465,13 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {// 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). 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++) {+ // An engine Harness is installing for this launch (a hold under `install`) is waited for up to five minutes,+ // and the launch then gets its minute: a minute in all ended a Codex install as it finished (a fresh Ubuntu VM,+ // 2026-10-12, where it took about that).+ const installing = (status: Record<string, unknown>) => (status.held as { service?: unknown } | undefined)?.service === 'install'+ let said = '', polls = 30+ for (let i = 0; i < polls && (result.state === 'pending' || result.state === 'unconfirmed'); i++) {+ if (installing(result)) polls = Math.min(180, Math.max(polls, i + 30))const reason = holdReason(result)if (reason && reason !== said && !args.json) deps.error(reason)said = reason || said@@ -478,15 +483,17 @@ export async function newCommand(deps: NewCommandDeps): Promise<number> {// otherwise answers what became of it, which is then the answer here.if (result.state === 'pending') {const reason = holdReason(result) || said+ const install = installing(result)+ const why = install ? `Harness is still installing ${engineName(String(payload.engine))}.`+ : `Harness did not start the harness ${polls > 30 ? 'in time' : 'within a minute'}${reason ? `: ${reason}` : '.'}`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.')+ throw new Error(`${why} ${install ? 'Run the same command again in a minute; this request is cancelled' : '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.')+ throw new Error(`${why} 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