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.

Preserve native launch preparation across dependency outages (#1160)

Dee740fb5286e37
diff --git a/cli/e2e/eagerHooks.e2e.ts b/cli/e2e/eagerHooks.e2e.ts
index c3fa06e6f..d28336e53 100644
--- a/cli/e2e/eagerHooks.e2e.ts
+++ b/cli/e2e/eagerHooks.e2e.ts
@@ -8,6 +8,7 @@ import { readLeanBundle } from '../src/harnessd/leanBundle.js'
import { LocalClient } from './harness/client.js'
import { assertHooksContained, CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
import { withLean } from './harness/release.js'
+import { shellSingleQuote } from '../src/lib/shellQuote.js'
let scratch = '', bundle = ''
let daemon: IsolatedDaemon | undefined, client: LocalClient | undefined
@@ -79,6 +80,105 @@ const timer = setInterval(() => { if (fs.existsSync(${JSON.stringify(release)}))
expect((await launch).error).toBe('AGENT_UNSUPPORTED')
}, 90_000)
+it('retains and cancels native-held requests across a core crash, then recovers one launch with its saved prompt', async () => {
+ const d = daemon = await IsolatedDaemon.create({ scriptPath: bundle, env: { HARNESS_CONNECTIONS_PORT: '0' } })
+ onTestFailed(() => console.log(d.log()))
+ const executable = join(d.root, 'late-codex')
+ d.env.CODEX_PATH = executable
+ await d.start()
+ let c = client = await LocalClient.connect(d)
+ const cwd = join(d.projectsDir, 'native-held'); mkdirSync(cwd)
+ const request = { engine: 'codex', cwd, bypassPermission: true, prompt: 'saved native launch prompt', creationId: 'native-held-recovery' }
+ const cancelled = { ...request, creationId: 'native-held-cancelled' }
+ for (const payload of [request, cancelled]) {
+ expect(await c.request('agent_create', payload, 15_000)).toMatchObject({ state: 'pending', held: { service: 'native' } })
+ }
+ expect((await c.request('agents_list', { includeStopped: true })).agents).toHaveLength(0)
+ const before = d.log().length
+ process.kill(d.corePid()!, 'SIGKILL'); c.close()
+ await until('core readiness while the native executable is unavailable', () => d.log().slice(before).includes('[cli] ready'), 15_000)
+ c = client = await LocalClient.connect(d)
+ expect(await c.request('agent_create_status', { creationId: request.creationId })).toMatchObject({ state: 'pending', held: { service: 'native' } })
+ expect(await c.request('agent_create_cancel', { creationId: cancelled.creationId })).toMatchObject({ state: 'cancelled' })
+ const terminal = await c.request('agent_create', { engine: 'terminal', cwd }, 15_000)
+ expect(terminal.error, JSON.stringify(terminal)).toBeUndefined()
+ const settings = join(d.engineConfig.codexHome, 'hooks.json'), original = readFileSync(settings)
+ writeFileSync(settings, '{incomplete native configuration')
+ const calls = join(d.root, 'native-dispatches'), wrapper = readFileSync(join(d.root, 'bin', 'codex'), 'utf8')
+ const line = wrapper.indexOf('\n') + 1
+ writeFileSync(executable, wrapper.slice(0, line) + `import { appendFileSync as recordNativeLaunch } from 'node:fs';\nif (!process.argv.includes('--version') && !process.argv.includes('--help')) recordNativeLaunch(${JSON.stringify(calls)}, JSON.stringify(process.argv.slice(2)) + '\\n');\n` + wrapper.slice(line), { mode: 0o755 })
+ await until('the saved request to name its hook hold', async () => {
+ const status = await c.request('agent_create_status', { creationId: request.creationId })
+ return status.state === 'pending' && /hook/i.test(status.held?.detail ?? '')
+ }, 15_000)
+ expect(readFileSync(settings, 'utf8')).toBe('{incomplete native configuration')
+ expect((await c.request('agents_list', { includeStopped: true })).agents).toHaveLength(1)
+ writeFileSync(settings, original)
+ const recovered = await until('the native request to recover after configuration repair', async () => {
+ const status = await c.request('agent_create_status', { creationId: request.creationId })
+ return status.state === 'created' ? status.agent : null
+ }, 30_000)
+ await until('the recovered Codex to bind', async () => {
+ const agents = (await c.request('agents_list', { includeStopped: true })).agents
+ return agents.find((agent: any) => agent.id === recovered.id && agent.sessionId && agent.status === 'active')
+ }, 30_000)
+ expect(await c.request('agent_create', request)).toMatchObject({ state: 'created', agent: { id: recovered.id } })
+ expect(await c.request('agent_create', cancelled)).toMatchObject({ state: 'cancelled' })
+ expect((await c.request('agents_list', { includeStopped: true })).agents).toHaveLength(2)
+ const launched = readFileSync(calls, 'utf8').trim().split('\n').map(line => JSON.parse(line))
+ expect(launched).toHaveLength(1)
+ expect(launched[0].at(-1)).toBe(request.prompt)
+}, 120_000)
+
+it.each(['create', 'fork'] as const)('keeps a post-rc held %s with its original request through repair and core restart', async operation => {
+ const d = daemon = await IsolatedDaemon.create({ scriptPath: bundle, env: { HARNESS_CONNECTIONS_PORT: '0', SHELL: '/bin/bash' } })
+ onTestFailed(() => console.log(d.log()))
+ const executable = join(d.root, 'bin', 'codex'), calls = join(d.root, 'dispatches')
+ const originalWrapper = readFileSync(executable, 'utf8'), line = originalWrapper.indexOf('\n') + 1
+ writeFileSync(executable, originalWrapper.slice(0, line)
+ + `import { appendFileSync as recordNativeLaunch } from 'node:fs';\nif (!process.argv.includes('--version') && !process.argv.includes('--help')) recordNativeLaunch(${JSON.stringify(calls)}, JSON.stringify(process.argv.slice(2)) + '\\n');\n`
+ + originalWrapper.slice(line), { mode: 0o755 })
+ await d.start()
+ let c = client = await LocalClient.connect(d)
+ const cwd = join(d.projectsDir, 'post-rc-held'); mkdirSync(cwd)
+ let source: string | undefined
+ if (operation === 'fork') {
+ const parent = await c.request('agent_create', { engine: 'codex', cwd, bypassPermission: true }, 30_000)
+ expect(parent.error, JSON.stringify(parent)).toBeUndefined()
+ source = parent.agent.id
+ await until('the source conversation to bind', async () => {
+ const rows = (await c.request('agents_list')).agents
+ return rows.find((row: any) => row.id === source && row.sessionId)
+ }, 30_000)
+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === source, 30_000)
+ c.send('message', { agentId: source, content: 'private fork source' }); await ended
+ }
+ // Only the new pane's rc file changes this private config, after preparation.
+ // Native probes have no TMUX_PANE. This forces the real final guard to hold.
+ const config = join(d.engineConfig.codexHome, 'config.toml'), trigger = join(d.root, 'change-once')
+ const original = readFileSync(config)
+ writeFileSync(trigger, '')
+ writeFileSync(join(d.env.HOME!, '.bashrc'), `if [ -n "$TMUX_PANE" ] && [ -f ${shellSingleQuote(trigger)} ]; then printf '\\n# changed by private pane fixture\\n' >> ${shellSingleQuote(config)}; /bin/rm ${shellSingleQuote(trigger)}; fi\n`)
+ const response = await c.request(operation === 'create' ? 'agent_create' : 'agent_fork', operation === 'create'
+ ? { engine: 'codex', cwd, bypassPermission: true, prompt: 'original held prompt' }
+ : { agentId: source, prompt: 'original fork prompt' }, 30_000)
+ expect(response.error, JSON.stringify(response)).toBeUndefined()
+ const id = response.agent.id
+ const held = async () => (await c.request('agents_list', { includeStopped: true })).agents.find((row: any) => row.id === id)
+ await until('the post-rc native hold', async () => (await held())?.launch?.state === 'held', 30_000)
+ expect((await held()).sessionId).toBeFalsy()
+ writeFileSync(config, original)
+ const before = d.log().length
+ process.kill(d.corePid()!, 'SIGKILL'); c.close()
+ await until('the core to recover while retaining the original request', () => d.log().slice(before).includes('[cli] ready'), 15_000)
+ c = client = await LocalClient.connect(d)
+ expect(await c.request('agent_restart', { agentId: id }, 15_000)).toMatchObject({ error: 'NATIVE_LAUNCH_HELD' })
+ expect(await held()).toMatchObject({ launch: { state: 'held', service: 'native' } })
+ expect((await held()).sessionId).toBeFalsy()
+ const dispatched = existsSync(calls) ? readFileSync(calls, 'utf8').trim().split('\n') : []
+ expect(dispatched).toHaveLength(operation === 'fork' ? 1 : 0)
+}, 120_000)
+
it.each([['missing', 'claude'], ['stalled', 'codex']] as const)(
'%s shared hooks: ready, native files installed, OpenCode launch and %s Stop/resume work', async (mode, engine) => {
const lean = readLeanBundle(readFileSync(bundle))!
diff --git a/cli/e2e/enginehomes.e2e.ts b/cli/e2e/enginehomes.e2e.ts
index 20085def8..7117dd4fa 100644
--- a/cli/e2e/enginehomes.e2e.ts
+++ b/cli/e2e/enginehomes.e2e.ts
@@ -133,7 +133,7 @@ describe('the person\'s engines keeping their data elsewhere', () => {
const agent = await until('the model-picker agent to bind', async () => {
const now = await row(client, created.agent.id); return now?.sessionId ? now : null
}, 30_000)
- if (engine === 'codex') expect(agent.codexHome).toBeNull()
+ if (engine === 'codex') expect(agent.codexHome).toBe(home)
const answer = await client.request('models_list', { agentId: agent.id }, 30_000)
expect(answer.error, JSON.stringify(answer)).toBeUndefined()
const ids = answer.models.map((model: Row) => model.id)
@@ -161,7 +161,7 @@ describe('the person\'s engines keeping their data elsewhere', () => {
const agent = await until('the shared conversation to bind', async () => {
const now = await row(client, created.agent.id); return now?.sessionId ? now : null
}, 30_000)
- expect(agent.codexHome).toBeNull()
+ expect(agent.codexHome).toBe(home)
server.state.threadId = agent.sessionId
const started = client.next(isTurn('turn_started', agent.id), 30_000)
client.send('message', { agentId: agent.id, content: '!hold' })
@@ -206,7 +206,7 @@ describe('the person\'s engines keeping their data elsewhere', () => {
for (const [folder, thread_name] of [[d.env.CODEX_HOME!, 'Wrong login name'], [home, 'Moved home conversation']]) {
writeFileSync(join(folder, 'session_index.jsonl'), JSON.stringify({ id: agent.sessionId, thread_name }) + '\n')
}
- expect(agent.codexHome).toBeNull()
+ expect(agent.codexHome).toBe(home)
await until('the moved-home name on the agent', async () => (await row(client, agent.id))?.name === 'Moved home conversation', 20_000)
client.close()
})
diff --git a/cli/e2e/recovery.e2e.ts b/cli/e2e/recovery.e2e.ts
index c2fac03ab..7ad8b96c0 100644
--- a/cli/e2e/recovery.e2e.ts
+++ b/cli/e2e/recovery.e2e.ts
@@ -3,7 +3,7 @@
* work, its master killed outright, an engine missing from this machine, and a registry lock left by
* a daemon that crashed holding it. Agents live in tmux, so every way back must find them again.
*/
-import { mkdirSync, rmSync, writeFileSync } from 'node:fs'
+import { mkdirSync, renameSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
import { LocalClient, type Frame } from './harness/client.js'
@@ -79,25 +79,29 @@ describe('coming back', () => {
again.close()
})
- it('an engine missing from this machine fails its launch with the reason, and the other engine works', async () => {
+ it('an unavailable engine holds its saved launch while another engine works, then recovers the same request', async () => {
const d = await fresh()
- rmSync(join(d.root, 'bin', 'codex'), { force: true })
+ const executable = join(d.root, 'bin', 'codex')
+ renameSync(executable, executable + '.unavailable')
await d.start()
const client = await LocalClient.connect(d)
const cwd = join(d.projectsDir, 'no-codex')
mkdirSync(cwd, { recursive: true })
- // The pane opens and the launch fails in it, so the person sees why: the agent says it, and so does
- // its terminal.
- const created = await client.request('agent_create', { engine: 'codex', cwd, bypassPermission: true }, 90_000)
- const failed = await until('the launch to fail with its reason', async () => {
- const agent = created.agent?.id ? await row(client, created.agent.id) : undefined
- return agent?.launch?.state === 'failed' ? agent : null
- }, 30_000, 250)
- expect(failed.launch.error).toBe('ENGINE_NOT_INSTALLED')
- expect(failed.launch.detail).toContain('codex is not installed')
- expect(failed.status).not.toBe('active')
+ const payload = { creationId: 'missing-codex-recovery', engine: 'codex', cwd, bypassPermission: true }
+ const created = await client.request('agent_create', payload, 90_000)
+ expect(created).toMatchObject({ state: 'pending', held: { service: 'native' } })
+ expect(created.held.detail).toContain('executable')
+ expect((await client.request('agents_list', { includeStopped: true })).agents).toEqual([])
const claude = await create(d, client, 'claude', 'still-claude')
await turn(client, claude.id, 'claude is still here')
+ renameSync(executable + '.unavailable', executable)
+ const recovered = await until('the original missing-engine request to recover', async () => {
+ const reply = await client.request('agent_create_status', { creationId: payload.creationId })
+ return reply.state === 'created' ? reply : null
+ }, 60_000, 250)
+ await until('the recovered Codex conversation to bind', async () => (await row(client, recovered.agent.id))?.sessionId || null)
+ expect(await client.request('agent_create', payload)).toMatchObject({ state: 'created', agent: { id: recovered.agent.id } })
+ await turn(client, recovered.agent.id, 'the held launch recovered')
expect(d.coresStarted()).toBe(1)
client.close()
})
diff --git a/cli/e2e/updates.e2e.ts b/cli/e2e/updates.e2e.ts
index ef717b9c0..412e1dfcf 100644
--- a/cli/e2e/updates.e2e.ts
+++ b/cli/e2e/updates.e2e.ts
@@ -239,7 +239,7 @@ describe('engines updated in place', () => {
client.close()
})
- it.each(engines)('%s: uninstalled while an agent runs: it goes on; a new agent and a restart fail at once with the reason; reinstalled, both work with no daemon restart', async (engine) => {
+ it.each(engines)('%s: uninstalled while an agent runs: it goes on; a new request waits while restart preserves the running agent; reinstalled, both work with no daemon restart', async (engine) => {
const d = await fresh()
const client = await LocalClient.connect(d)
const agent = await create(d, client, engine, `uninstalled-${engine}`)
@@ -253,26 +253,30 @@ describe('engines updated in place', () => {
const cwd = join(d.projectsDir, `missing-${engine}`)
mkdirSync(cwd, { recursive: true })
let startedAt = Date.now()
- const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
- const failed = await until('the launch to fail with its reason', async () => {
- const now = created.agent?.id ? await row(client, created.agent.id) : undefined
- return now?.launch?.state === 'failed' ? now : null
- }, 30_000, 250)
+ const payload = { creationId: `uninstalled-${engine}-request`, engine, cwd, bypassPermission: true }
+ const created = await client.request('agent_create', payload, 90_000)
expect(Date.now() - startedAt).toBeLessThan(10_000)
- expect(failed.launch.error).toBe('ENGINE_NOT_INSTALLED')
- expect(failed.launch.detail).toContain(`${engine} is not installed`)
+ expect(created).toMatchObject({ state: 'pending', held: { service: 'native' } })
+ expect(created.held.detail).toContain('executable')
+ expect((await rows(client)).map(row => row.id)).toEqual([agent.id])
- // A restart cannot bring the agent back on an engine that is not there, so it is refused before the
- // running agent is touched, with the reason, the way the agent's folder is checked first.
+ // Restart holds before touching the live process. Repairing the executable
+ // then retrying must keep this agent's original conversation.
startedAt = Date.now()
const restarted = await client.request('agent_restart', { agentId: agent.id }, 90_000)
expect(Date.now() - startedAt).toBeLessThan(10_000)
- expect(restarted.error, JSON.stringify(restarted)).toBe('ENGINE_NOT_INSTALLED')
- expect(String(restarted.detail)).toContain(`${engine} is not installed`)
+ expect(restarted.error, JSON.stringify(restarted)).toBe('NATIVE_LAUNCH_HELD')
+ expect(String(restarted.detail)).toContain('executable')
+ expect(await row(client, agent.id)).toMatchObject({ status: 'active', sessionId: agent.sessionId })
await turn(client, agent.id, 'after the refused restart')
install(d, engine, { version: NEW[engine] })
- const next = await create(d, client, engine, `reinstalled-${engine}`)
+ const recovered = await until('the original request after reinstall', async () => {
+ const reply = await client.request('agent_create_status', { creationId: payload.creationId })
+ return reply.state === 'created' ? reply : null
+ }, 60_000, 250)
+ const next = await bound(client, recovered.agent.id)
+ expect(await client.request('agent_create', payload)).toMatchObject({ state: 'created', agent: { id: next.id } })
expect(await runningVersion(client, next.id)).toBe(versionLine(engine, NEW[engine]))
// The first agent restarts onto the engine installed again, in its own conversation.
const back = await client.request('agent_restart', { agentId: agent.id }, 90_000)
diff --git a/cli/scripts/handoff-2026-10-08/mutate-native-launch.py b/cli/scripts/handoff-2026-10-08/mutate-native-launch.py
new file mode 100644
index 000000000..d2e52d767
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-native-launch.py
@@ -0,0 +1,81 @@
+#!/usr/bin/env python3
+"""Break native launch boundaries in an explicitly owned disposable worktree."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+assert (cli.parent / '.git').is_file(), 'An owned disposable worktree is required'
+assert os.environ.get('HARNESS_NATIVE_MUTATIONS_OWNED') == '1'
+launch = 'src/engines/nativeLaunchCompatibility.golden.spec.ts'
+grid = 'src/lib/gridConfigCompatibility.golden.spec.ts'
+guard = 'src/engines/kit/nativeLaunchGuard.spec.ts'
+prepare = 'src/engines/prepareNativeLaunch.spec.ts'
+settings = 'src/engines/kit/hookSettings.spec.ts'
+mutations = [
+ ('ignore captured executable', 'src/lib/engineLaunch.ts', 'opts.native?.executable?.command ?? engineBin(engine)', 'engineBin(engine)', launch, ''),
+ ('drop original first prompt', 'src/lib/engineLaunch.ts', 'if (opts.firstPrompt) argv.push(...firstPromptArgs(engine, opts.firstPrompt))', 'if (false) argv.push(...firstPromptArgs(engine, opts.firstPrompt!))', launch, ''),
+ ('disconnect installer dispatch', 'src/engines/kit/nativeInstall.ts', ' dispatch(runtime, file, hash)', ' void runtime; void file; void hash', launch, ''),
+ ('accept unfinished visible executable', 'src/engines/prepareNativeLaunch.ts', 'obligation && !obligation.complete ? held(obligation.detail) : found', 'false ? held(obligation!.detail) : found', prepare, 'newly visible executable'),
+ ('skip fresh post-install observation', 'src/engines/prepareNativeLaunch.ts', 'const prepared = await inspect(engine, source)', 'const prepared = found', prepare, 'fresh post-install snapshot'),
+ ('drop final hook proof', 'src/engines/kit/nativeLaunchGuard.ts', 'files: launch.proofs.flatMap(item => item.files)', 'files: []', guard, 'changed hook contents'),
+ ('ignore prepared executable identity', 'src/engines/kit/nativeLaunchGuard.ts', '!==p.identity)throw 0;', '===undefined)throw 0;', guard, 'after shell startup'),
+ ('change published configuration', 'src/lib/publishedGridConfig.ts', 'await previous.replace(file.content, attempt, previous.content === null)', "await previous.replace(file.content + '\\n', attempt, previous.content === null)", grid, ''),
+ ('drop Messages within the shared hook reservation', 'src/engines/kit/hookSettings.ts', 'if (settings.inbox) await installMessagesBlock(settings, home, attempt, verifyRequired)', 'void verifyRequired', settings, 'publishes one current'),
+ ('globally adopt a session profile', 'src/engines/nativeLaunch.ts', 'home === implicitHome', 'true', 'src/engines/nativeLaunch.spec.ts', 'profile scoped to its session'),
+ ('approve first owned block only', 'src/engines/kit/hookReview.ts', 'for (const [blockIndex, block] of blocks.entries())', 'for (const [blockIndex, block] of [...blocks.entries()].slice(0, 1))', settings, 'earlier optional hook'),
+ ('own marker-only foreign commands', 'src/engines/kit/messagesHook.ts', "return value === messagesCommand(root, node)", "return value === messagesCommand(root, node) || value.includes('harness-agent-messages')", 'src/engines/kit/messagesHook.spec.ts', ''),
+ ('drop saved local trust authority', 'src/core/agents/launches.ts', '{ local: saved.local }', '{ local: false }', 'src/core/agents/nativeCreate.spec.ts', 'saved local authority true'),
+ ('publish stale pane hold', 'src/core/agents/newPane.ts', "if (!current()) return\n if (waiting === true)", "if (waiting === true)", 'src/core/agents/newPane.spec.ts', 'delayed native hold'),
+ ('drop nested retarget native proof', 'src/core/agents/retarget.ts', 'retargetPermission.permissionMode ?? null, dispatchCurrent), isCurrent: dispatchCurrent', 'retargetPermission.permissionMode ?? null, current), isCurrent: current', 'src/core/agents/retarget.spec.ts', 'proof changes during hold-open'),
+ ('drop fallback native proof', 'src/lib/restoreAgents.ts', 'const dispatchCurrent = () => current() && launch.current?.() !== false\n return inPane', 'const dispatchCurrent = () => current()\n return inPane', 'src/lib/restoreAgents.spec.ts', 'fallback proof expires'),
+ ('drop captured native API authority', 'src/engines/kit/nativeSessionModel.ts', '{ ...deps, cwd: input.cwd, store: input.dbPath, checkCatalog: input.checkCatalog }', '{ current: deps.current, cwd: input.cwd, store: input.dbPath, checkCatalog: input.checkCatalog }', 'src/engines/kit/nativeMutationDispatch.spec.ts', 'public apply API'),
+ ('inherit absent native API location', 'src/engines/kit/nativeSessionModel.ts', 'env: nativeProcessEnvironment(authority.environment)', 'env: { ...process.env, ...authority.environment }', 'src/engines/kit/nativeMutationDispatch.spec.ts', 'public apply API'),
+ ('forget native receipt environment', 'src/engines/kit/nativeSessionModel.ts', ' || previous.environment !== environment', '', 'src/engines/kit/nativeMutationDispatch.spec.ts', 'newly captured store'),
+ ('trust an obsolete empty read', 'src/core/agents/create.ts', ' files.verify()', ' void files', 'src/core/agents/create.spec.ts', 'changed after enumeration'),
+ ('recognize an inline launch as held', 'src/lib/nativePaneHold.ts', '#{==:#{m:*${NATIVE_LAUNCH_MARKER}=*,#{pane_start_command}},0}', '1', 'src/lib/nativePaneHold.spec.ts', 'sourced false'),
+ ('replace a newer pane occupant', 'src/lib/nativePaneHold.ts', '#{==:#{pane_pid},"+pid+"}', '1', 'src/lib/nativePaneHold.spec.ts', 'delayed server command'),
+ ('lose legacy pane ownership', 'src/lib/nativePaneHold.ts', 'const command = `/usr/bin/env HARNESS_DAEMON=${owner} ${heldCommand}`', 'const command = heldCommand', 'src/lib/nativePaneHold.spec.ts', 'sourced true'),
+ ('wait indefinitely for the tmux client', 'src/lib/nativePaneHold.ts', 'timeout:2000', 'timeout:60000', 'src/lib/nativePaneHold.spec.ts', 'stalled transition'),
+ ('fail unconfirmed native launch', 'src/core/agents/newPane.ts', 'registry.setLaunch(pending.agentId, nativeToken', 'registry.setLaunch(pending.agentId, false', 'src/core/agents/newPane.spec.ts', 'post-rc native guard hold'),
+ ('forget an unconfirmed native launch after crash', 'src/lib/restoreAgents.ts', 'if (nativeToken) {\n // A core crash', 'if (false) {\n // A core crash', 'src/lib/restoreAgents.spec.ts', 'unrecognized inert launch'),
+ ('retain restore authority after shutdown', 'src/core/agents/heldLaunches.ts', 'restore(new Set([agentId]), current)', 'restore(new Set([agentId]), () => true)', 'src/lib/restoreAgents.spec.ts', 'shutdown begins during launch preparation'),
+ ('forget prepared dispatch authority', 'src/core/agents/launches.ts', "if (!authority.current()) return { state: 'unconfirmed' }", 'void authority', 'src/core/agents/launches.spec.ts', 'before invocation'),
+]
+environment = dict(os.environ, TZ='UTC', TMPDIR='/tmp', HARNESS_CONNECTIONS_PORT='0')
+for key in ('TMUX', 'TMUX_PANE', 'RECORD_NATIVE_LAUNCH_GOLDEN', 'RECORD_GRID_CONFIG_GOLDEN'):
+ environment.pop(key, None)
+tmux = cli.parent / '.harness/tmux'
+tmux.mkdir(parents=True, exist_ok=True)
+environment['TMUX_TMPDIR'] = str(tmux)
+
+
+def run(specs, pattern=''):
+ command = ['node', 'node_modules/vitest/vitest.mjs', 'run', *specs, '--maxWorkers=1']
+ if pattern:
+ command += ['-t', pattern]
+ return subprocess.run(command, cwd=cli, env=environment, text=True, capture_output=True, timeout=240)
+
+
+baseline = run(sorted({item[4] for item in mutations}))
+assert baseline.returncode == 0, 'Unchanged baseline failed; no mutants ran.\n' + baseline.stdout + baseline.stderr
+print('Unchanged baselines passed', flush=True)
+failures = []
+for label, relative, before, after, spec, pattern in mutations:
+ path = cli / relative
+ original = path.read_text()
+ assert original.count(before) == 1, (label, original.count(before))
+ try:
+ path.write_text(original.replace(before, after))
+ result = run([spec], pattern)
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError' not in output:
+ failures.append(label)
+ print(label + ': NOT caught by assertion\n' + output, flush=True)
+ else:
+ print(label + ': caught by assertion', flush=True)
+ finally:
+ path.write_text(original)
+if failures:
+ raise SystemExit('Uncaught mutations: ' + ', '.join(failures))
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index 331d3a236..2fef6df9e 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -1,4 +1,5 @@
-import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, mkdirSync, mkdtempSync, opendirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { readdir } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -21,8 +22,24 @@ import { createAgentCreator, type CreateAgentDeps } from './create.js'
import { prepareInstructionWrites } from '../../scm/scmProjects.js'
import { opencodeMajorVersion } from '../../engines/launchControl.js'
import { installOpencodePlugin } from '../../engines/nativeHooks.js'
+import type { NativeLaunch } from '../../engines/nativeLaunch.js'
+import { projectsRoot } from '../../lib/projectFolder.js'
+import { NativeFiles } from '../../engines/kit/nativeFiles.js'
+
+vi.mock('../../lib/projectFolder.js', async real => {
+ const actual = await real<typeof import('../../lib/projectFolder.js')>()
+ return { ...actual, projectsRoot: vi.fn(actual.projectsRoot) }
+})
vi.mock('../../scm/scmProjects.js', async real => ({ ...await real<object>(), prepareInstructionWrites: vi.fn(async () => {}) }))
+vi.mock('node:fs', async real => {
+ const actual = await real<typeof import('node:fs')>()
+ return { ...actual, opendirSync: vi.fn(actual.opendirSync) }
+})
+vi.mock('node:fs/promises', async real => {
+ const actual = await real<typeof import('node:fs/promises')>()
+ return { ...actual, readdir: vi.fn(actual.readdir) }
+})
vi.mock('../../dsh/installed.js', () => ({ installedDsh: vi.fn(() => undefined) }))
vi.mock('../../dsh/manifest.js', async (real) => ({ ...await real<object>(), dshPinnedPermissionMode: vi.fn(() => null) }))
@@ -40,7 +57,10 @@ vi.mock('../../engines/kit/nativePlugin.js', () => ({
prepareNativePlugin: vi.fn(() => ({ verify: () => {}, commit: async () => ({ verify: () => {} }) })),
prepareNativePluginRemoval: vi.fn(() => ({ verify: () => {}, commit: async () => ({ verify: () => {} }) })),
}))
-vi.mock('../../engines/kit/nativeHookFiles.js', () => ({ runHookPreparation: async (_files: string[], work: () => Promise<unknown>) => work() }))
+vi.mock('../../engines/kit/nativeHookFiles.js', () => ({
+ runHookPreparation: async (_files: string[], work: () => Promise<unknown>) => work(),
+ hookPreparationRoutes: () => ({ verify: () => {}, keys: [] }),
+}))
// The engines' folder trust (engines/launchPrep.ts), one spy per engine: never the person's own config.
const trust = vi.hoisted(() => ({
claudeTrusts: vi.fn((_path: string) => false), codexTrusts: vi.fn((_path: string, _profile?: string | null) => false),
@@ -130,12 +150,178 @@ const installed = (over: Record<string, unknown> = {}) => ({ id: 'autonomous/ble
describe('creating an agent', () => {
beforeEach(() => {
+ vi.mocked(projectsRoot).mockReset()
+ vi.mocked(opendirSync).mockReset()
vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.mocked(createAndRegisterPane).mockReset().mockResolvedValue({ ok: true, spawned: { runtime: { paneId: '%1' } }, pending } as never)
})
afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+ it.each(['local', 'remote', 'nonempty', 'unreadable', 'unreadable before trust', 'revoked', 'revoked before trust', 'changed contents', 'replaced workspace', 'changed after enumeration', 'redirected during enumeration', 'error', 'thrown text', 'no trust contract', 'legacy'] as const)(
+ 'decides local trust before workspace preparation and writes it before final proof: %s', async mode => {
+ const parent = mode === 'redirected during enumeration' ? folder() : root
+ vi.mocked(projectsRoot).mockReturnValueOnce(parent)
+ const cwd = parent === root ? folder(mode === 'nonempty' ? ['user-file'] : []) : join(parent, 'workspace')
+ mkdirSync(cwd, { recursive: true })
+ let current = true
+ if (mode === 'unreadable') vi.mocked(readdir).mockRejectedValueOnce(Error('fixture denied'))
+ if (mode === 'unreadable before trust') vi.spyOn(NativeFiles.prototype, 'entries').mockImplementationOnce(() => { throw Error('fixture denied') })
+ if (mode === 'revoked') vi.mocked(readdir).mockImplementationOnce(async () => { current = false; return [] })
+ if (mode === 'revoked before trust') vi.spyOn(NativeFiles.prototype, 'entries').mockImplementationOnce(() => { current = false; return [] })
+ if (mode === 'changed after enumeration') {
+ const entries = NativeFiles.prototype.entries
+ vi.spyOn(NativeFiles.prototype, 'entries').mockImplementationOnce(function (this: NativeFiles, path, missing) {
+ const result = entries.call(this, path, missing)
+ writeFileSync(join(cwd, 'user-file'), 'arrived after the empty read')
+ return result
+ })
+ }
+ if (mode === 'redirected during enumeration') {
+ const actual = await vi.importActual<typeof import('node:fs')>('node:fs')
+ vi.mocked(opendirSync).mockImplementationOnce((path, options) => {
+ renameSync(parent, parent + '-original'); mkdirSync(cwd, { recursive: true })
+ try { return actual.opendirSync(path, options) }
+ finally { renameSync(parent, parent + '-redirected'); renameSync(parent + '-original', parent) }
+ })
+ }
+ if (mode === 'error' || mode === 'thrown text') preTrustCodexProject.mockImplementationOnce(() => { throw mode === 'error' ? Error('fixture denied') : 'fixture denied' })
+ const expected = !['remote', 'nonempty', 'unreadable', 'unreadable before trust', 'revoked', 'revoked before trust', 'changed contents', 'replaced workspace', 'changed after enumeration', 'redirected during enumeration', 'no trust contract'].includes(mode)
+ const launch = { current: () => current, environment: { HOME: '/fixture/home', CODEX_HOME: '/fixture/selected' },
+ permission: async () => 'supported', prepareHooks: vi.fn(async () => {
+ expect(preTrustCodexProject, JSON.stringify(vi.mocked(console.warn).mock.calls)).toHaveBeenCalledTimes(expected ? 1 : 0)
+ return true
+ }),
+ } as unknown as NativeLaunch
+ const run = setup(mode === 'legacy' ? {} : { native: async () => {
+ if (mode === 'changed contents') writeFileSync(join(cwd, 'user-file'), 'user content')
+ if (mode === 'replaced workspace') { renameSync(cwd, cwd + '-original'); mkdirSync(cwd) }
+ return { ok: true, launch }
+ } })
+ const result = await run.create.prepare(request({ cwd, engine: mode === 'no trust contract' ? 'opencode' : 'codex' }),
+ { id: 'fixture', label: 'harness-codex-fixture', current: () => current, hold: () => {} }, { local: mode !== 'remote' })
+ if (mode === 'revoked' || mode === 'revoked before trust') expect(result).toMatchObject({ ok: false, unavailable: 'launch' })
+ else expect(result.ok).toBe(true)
+ expect(preTrustCodexProject, JSON.stringify(vi.mocked(console.warn).mock.calls)).toHaveBeenCalledTimes(expected ? 1 : 0)
+ if (expected) expect(preTrustCodexProject).toHaveBeenCalledWith(cwd, mode === 'legacy' ? null : '/fixture/selected')
+ })
+
+ it.each(['folder inspection', 'tmux capabilities', 'config publication'] as const)('holds a create revoked during %s before launch side effects', async stage => {
+ let current = true
+ vi.mocked(installedDsh).mockReturnValue(installed() as never)
+ const run = setup()
+ if (stage === 'folder inspection') vi.mocked(readdir).mockImplementationOnce(async () => { current = false; return [] })
+ if (stage === 'tmux capabilities') vi.mocked(tmuxSupportsSessionEnv).mockImplementationOnce(async () => { current = false; return true })
+ if (stage === 'config publication') vi.mocked(writeGridConfigDir).mockImplementationOnce(async () => { current = false; return '/fixture/config' })
+ buildGridLaunch.mockResolvedValueOnce({ ok: true, override: { networkId: 'fixture', networkName: 'Fixture', baseUrl: 'http://fixture.invalid', apiKey: 'fixture' }, launch: {
+ env: {}, args: [], webSearch: 'unsupported', configDir: { envVar: 'PI_CONFIG', files: [] },
+ } })
+ try {
+ expect(await run.create.prepare(request(stage === 'folder inspection' ? { dsh: 'blender' } : { grid: { networkName: 'Fixture' } }),
+ { id: 'fixture', label: 'harness-claude-fixture', current: () => current, hold: vi.fn() }))
+ .toMatchObject({ error: 'LAUNCH_AUTHORITY_CHANGED' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ expect(run.deps.prepareApiTools).not.toHaveBeenCalled()
+ } finally {
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ buildGridLaunch.mockReset().mockImplementation(async request => ({ ok: true, override: request.override,
+ launch: { env: { GRID_KEY: 'k' }, args: ['--grid'], webSearch: 'unsupported' } }))
+ }
+ })
+
+ it('uses the confirmed native version for a named launch and forwards preparation holds', async () => {
+ const launch = { current: () => true, environment: { HOME: root }, prepareHooks: async () => true, opencodeMajor: 1 } as unknown as NativeLaunch
+ const run = setup({ native: async (_engine, _source, authority) => {
+ authority.hold({ service: 'native', detail: 'Checking fixture executable' })
+ return { ok: true, launch }
+ } })
+ expect(await run.create(request({ engine: 'opencode', agent: 'named' }))).toMatchObject({ ok: true })
+ expect(namedAgentArgs).toHaveBeenCalledWith('opencode', 'named', 1)
+ expect(opencodeMajorVersion).not.toHaveBeenCalled()
+ })
+
+ it.each(['initial', 'inspect', 'permission', 'models', 'account', 'materialize', 'harness', 'instructions', 'api', 'dispatch'] as const)(
+ 'revokes preparation at %s before any native pane dispatch', async stage => {
+ let current = stage !== 'initial'
+ const revoke = (at: string) => { if (stage === at) current = false }
+ const launch = { current: () => true, environment: { HOME: root }, prepareHooks: async () => true, opencodeMajor: 1 } as unknown as NativeLaunch
+ vi.mocked(installedDsh).mockReturnValue(installed() as never)
+ vi.mocked(refusePermissionFlagIfUnsupported).mockImplementationOnce(async () => { revoke('permission'); return null })
+ const run = setup({ native: async () => { revoke('inspect'); return { ok: true, launch } },
+ buildGridLaunch: async request => { revoke('models'); return { ok: true, override: request.override, launch: { env: {}, args: [], webSearch: 'unsupported' } } },
+ privateGridName: async () => { revoke('account'); return null },
+ dshLaunch: {
+ materialize: async () => { revoke('materialize'); return { ok: true, warnings: [], created: [], kept: [] } },
+ launch: async () => { revoke('harness'); return { ok: true, launch: { env: {}, args: [] } } },
+ },
+ prepareApiTools: () => revoke('api'),
+ })
+ vi.mocked(prepareInstructionWrites).mockImplementationOnce(async () => revoke('instructions'))
+ try {
+ const prepared = await run.create.prepare(request({ dsh: 'blender', grid: { networkName: 'fixture' } }),
+ { id: 'fixture', label: 'harness-claude-fixture', current: () => current, hold: vi.fn() })
+ revoke('dispatch')
+ const result = prepared.ok ? await prepared.dispatch() : prepared
+ expect(result).toMatchObject({ ok: false, error: 'LAUNCH_AUTHORITY_CHANGED' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ } finally {
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ vi.mocked(refusePermissionFlagIfUnsupported).mockReset().mockResolvedValue(null)
+ vi.mocked(prepareInstructionWrites).mockReset().mockResolvedValue(undefined)
+ }
+ },
+ )
+
+ it('holds an unavailable native snapshot, unsupported named engine and incomplete hook preparation', async () => {
+ const held = { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting for executable' } as const
+ expect(await setup({ native: async () => held }).create(request())).toEqual(held)
+ const launch = { current: () => true, environment: { HOME: root }, prepareHooks: async () => false, opencodeMajor: 2 } as unknown as NativeLaunch
+ const run = setup({ native: async () => ({ ok: true, launch }) })
+ expect(await run.create(request({ engine: 'opencode', agent: 'named' }))).toMatchObject({ error: 'AGENT_UNSUPPORTED' })
+ expect(await run.create(request())).toMatchObject({ unavailable: 'native', detail: expect.stringContaining('hooks') })
+ 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,
+ ...(mode === 'no retain' ? {} : { retain: vi.fn(() => mode !== 'revoked proof') }),
+ } as unknown as NativeLaunch
+ const publishConfig = vi.fn<NonNullable<CreateAgentDeps['publishConfig']>>(async (_key, _files, _links, current) => {
+ expect(current?.()).toBe(true)
+ if (mode === 'write failed') throw Error('fixture publication unavailable')
+ return { directory: '/fixture/published', proof }
+ })
+ const run = setup({ native: async () => ({ ok: true, launch }), ...(mode === 'legacy' ? {} : { publishConfig }),
+ buildGridLaunch: async request => ({ ok: true, override: request.override, launch: { env: {}, args: [], webSearch: 'unsupported',
+ configDir: { envVar: 'PI_CONFIG', files: [], links: [] } } }),
+ })
+ const result = await run.create(request({ engine: 'pi', grid: { networkName: 'fixture' } }))
+ if (mode === 'published' || mode === 'legacy') expect(result).toMatchObject({ ok: true })
+ else {
+ expect(result).toMatchObject({ ok: false, unavailable: mode === 'write failed' ? 'native' : 'launch' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ }
+ })
+
+ it('records the final harness-selected Codex home used by real native preparation', async () => {
+ const executable = await import('../../engines/kit/launchExecutable.js')
+ vi.spyOn(executable, 'captureLaunchExecutable').mockResolvedValue({ state: 'ready',
+ executable: { command: '/fixture/engine', identity: 'fixture', current: () => true },
+ environment: { HOME: root, PATH: '/fixture/bin' },
+ })
+ const { inspectNativeLaunch } = await import('../../engines/nativeLaunch.js')
+ vi.mocked(installedDsh).mockReturnValue(installed() as never)
+ const finalHome = join(root, 'harness-codex')
+ launchDsh.mockResolvedValueOnce({ ok: true, launch: { env: { CODEX_HOME: finalHome }, args: [] } })
+ const { create } = setup({ native: (engine, source) => inspectNativeLaunch(engine, source), hooksDisabled: true })
+ const result = await create(request({ engine: 'codex', codexHome: join(root, 'selected-codex'), dsh: 'blender' }))
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ expect(result, JSON.stringify(result)).toMatchObject({ ok: true })
+ expect(createAndRegisterPane).toHaveBeenCalledWith(expect.objectContaining({ codexHome: finalHome, env: expect.objectContaining({ CODEX_HOME: finalHome }) }))
+ expect(vi.mocked(createAndRegisterPane).mock.calls[0]![0].current?.()).toBe(true)
+ })
+
it('does not open a Codex pane before its profile hooks are durably confirmed', async () => {
let finish!: (installed: boolean) => void
vi.mocked(engineHooks.codex.installIn).mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
@@ -204,8 +390,11 @@ describe('creating an agent', () => {
vi.mocked(materializeWorkspace).mockRejectedValueOnce(new Error('disk full')).mockRejectedValueOnce('worse')
expect(await create(request({ dsh: 'blender' }))).toMatchObject({ error: 'DSH_MATERIALIZE_FAILED', detail: 'could not prepare the workspace for blender · disk full' })
expect(await create(request({ dsh: 'blender' }))).toMatchObject({ detail: 'could not prepare the workspace for blender · worse' })
- launchDsh.mockResolvedValueOnce({ ok: false, error: 'DSH_RUNTIME', detail: 'no runtime' } as never)
+ launchDsh.mockResolvedValueOnce({ ok: false, error: 'DSH_RUNTIME', detail: 'no runtime', thrown: 'Error: no runtime' })
expect(await create(request({ dsh: 'blender' }))).toEqual({ ok: false, error: 'DSH_RUNTIME', detail: 'no runtime' })
+ launchDsh.mockResolvedValueOnce({ ok: false, error: 'DSH_UNAVAILABLE', detail: 'Store unavailable', unavailable: 'store' })
+ expect(await create(request({ dsh: 'blender' }))).toEqual({ ok: false, error: 'DSH_UNAVAILABLE', detail: 'Store unavailable', unavailable: 'store' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
})
@@ -214,7 +403,7 @@ describe('creating an agent', () => {
const grid = { networkId: 'g1', networkName: 'Home', baseUrl: 'http://g', model: 'm' }
const { create } = setup()
buildGridLaunch.mockResolvedValueOnce({ ok: false, error: 'GRID_UNAVAILABLE', detail: 'models is down', unavailable: 'models' })
- expect(await create(request({ dsh: 'blender', grid }))).toEqual({ ok: false, error: 'GRID_UNAVAILABLE', detail: 'models is down' })
+ expect(await create(request({ dsh: 'blender', grid }))).toEqual({ ok: false, error: 'GRID_UNAVAILABLE', detail: 'models is down', unavailable: 'models' })
expect(materializeWorkspace).not.toHaveBeenCalled()
expect(preTrustClaudeProject).not.toHaveBeenCalled()
expect(prepareInstructionWrites).not.toHaveBeenCalled()
@@ -277,7 +466,7 @@ describe('creating an agent', () => {
const refused = { ok: false as const, error: 'DSH_UNAVAILABLE', detail: 'Store unavailable', unavailable: 'store' as const }
const materialize = vi.fn(async () => refused)
const { create } = setup({ dshLaunch: { materialize, launch: launchDsh } })
- expect(await create(request({ dsh: 'blender' }))).toEqual({ ok: false, error: refused.error, detail: refused.detail })
+ expect(await create(request({ dsh: 'blender' }))).toEqual(refused)
expect(launchDsh).not.toHaveBeenCalled()
expect(createAndRegisterPane).not.toHaveBeenCalled()
expect(preTrustClaudeProject).not.toHaveBeenCalled()
@@ -418,7 +607,7 @@ describe('creating an agent', () => {
expect(loadEngine).not.toHaveBeenCalled()
buildGridLaunch.mockResolvedValueOnce({ ok: false, error: 'GRID_UNSUPPORTED', detail: 'no' })
await t.create(request({ engine: 'claude', agent: 'reviewer', grid: { networkName: 'g' } }))
- expect(t.deps.gridLaunchMachine).toHaveBeenCalledWith('claude')
+ expect(t.deps.gridLaunchMachine).toHaveBeenCalledWith('claude', undefined)
})
it('opens as a named agent, with a first prompt, and does not install an engine with a path override', async () => {
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index 339c2343c..a368862c8 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -1,3 +1,4 @@
+import type { NativeLaunch, NativeLaunchResult, NativeLaunchSource } from '../../engines/nativeLaunch.js'
/**
* Creating an agent (`agent_create`): open a fresh pane running the chosen engine in the chosen
* folder, as a domain-specific harness or a plain session, on a grid or the engine's own login, opening
@@ -6,9 +7,9 @@
*
* Moved verbatim out of `runForeground` (the core boundary, step 11: docs/design/2026-10-03-harnessd.md).
*/
-import { statSync } from 'node:fs'
+import { realpathSync, statSync } from 'node:fs'
import { readdir } from 'node:fs/promises'
-import { join } from 'node:path'
+import { dirname, join } from 'node:path'
import type { BackendSocket } from '../../backendSocket.js'
import type { ModelsPort } from '../api.js'
import { MODEL_MANAGER_ID } from '../../dsh/builtinIds.js'
@@ -25,7 +26,7 @@ import { enginePathOverride } from '../../lib/engineBin.js'
import { engineInstallRecipe } from '../../lib/engineInstall.js'
import {
buildEngineCommandArgv, buildEngineLaunchArgv, namedAgentArgs, permissionModeApproves, permissionModeFlags,
- refusePermissionFlagIfUnsupported, supportsFirstPrompt,
+ refusePermissionFlagIfUnsupported, supportsFirstPrompt, supportsNamedAgent, NamedAgentUnsupportedError,
} from '../../lib/engineLaunch.js'
import { setUpWithin } from '../../lib/setUpWithin.js'
import { writeGridConfigDir } from '../../lib/gridConfigDir.js'
@@ -33,8 +34,13 @@ import { describeGridLaunch, gridConflictingEnvToClear, type GridLaunchAnswer, t
import { profileEnvironment } from '../../lib/engineHomes.js'
import { DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from '../../lib/harnessDefaults.js'
import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'
+import type { LaunchAuthority, LaunchPreparation } from '../../lib/launchPreparation.js'
+import type { publishGridConfigDir } from '../../lib/publishedGridConfig.js'
+import { nativeHookLocations } from '../../engines/kit/nativeLocations.js'
import { engineHooks } from '../../engines/hooks.js'
import { folderTrust } from '../../engines/launchPrep.js'
+import { projectsRoot } from '../../lib/projectFolder.js'
+import { NativeFiles } from '../../engines/kit/nativeFiles.js'
import type { registry, RegisteredSession } from '../../lib/registry.js'
import { clearPaneRemainOnExit } from '../../lib/tmux.js'
import type { TmuxBackend } from '../../lib/tmuxBackend.js'
@@ -51,7 +57,9 @@ const MODEL_MANAGER_GRID_WAIT_MS = 8_000
type CreateAgent = NonNullable<BackendSocket['onCreateAgent']>
export interface CreateAgentDeps {
+ publishConfig?: typeof publishGridConfigDir
/** The tmux backend; null where the configuration lists no tmux. */
+ native?: (engine: AgentEngine, source: NativeLaunchSource, authority: LaunchAuthority) => Promise<NativeLaunchResult>
tmuxBackend: TmuxBackend | null
registry: typeof registry
externalResume: CreateAgent
@@ -67,7 +75,7 @@ export interface CreateAgentDeps {
* `installOpencodePluginBeforeSpawn`): eager, independent of optional interpretation. */
installOpencodePlugin: (port: number) => Promise<boolean>
/** The facts about this machine a launch of `engine` needs (lib/gridLaunch.ts). */
- gridLaunchMachine: (engine: AgentEngine) => GridLaunchMachine | Promise<GridLaunchMachine>
+ gridLaunchMachine: (engine: AgentEngine, native?: NativeLaunch) => GridLaunchMachine | Promise<GridLaunchMachine>
/** A grid or saved-API launch, built by the models service (core/agents/launch.ts `gridLaunchThrough`): the core
* builds none itself, and a create on a grid while models is down is refused (GRID_UNAVAILABLE). */
buildGridLaunch: (request: GridLaunchRequest) => Promise<GridLaunchAnswer>
@@ -82,20 +90,30 @@ export interface CreateAgentDeps {
}
export function createAgentCreator({
- tmuxBackend, registry, externalResume, watchNewPane, announceSession, attachDsh,
+ native: inspectNative, publishConfig, tmuxBackend, registry, externalResume, watchNewPane, announceSession, attachDsh,
prepareApiTools, hookPort, hooksDisabled, installOpencodePlugin, gridLaunchMachine, buildGridLaunch, terminalHintMachineName, blocksFolder,
gridSetup, privateGridName, dshLaunch,
}: CreateAgentDeps) {
- const createAgent: CreateAgent = async input => {
- if (input.resumeSessionId) return externalResume(input)
+ const prepare = async (input: Parameters<CreateAgent>[0], authority: LaunchAuthority, context?: { local: boolean }): Promise<LaunchPreparation<Awaited<ReturnType<CreateAgent>>>> => {
+ if (input.resumeSessionId) return { ok: true, dispatch: () => externalResume(input) }
+ const stale = () => ({ ok: false as const, error: 'LAUNCH_AUTHORITY_CHANGED', unavailable: 'launch', detail: 'Waiting for the original launch request’s authority.' })
+ if (!authority.current()) return stale()
let { engine, cwd, bypassPermission, permissionMode, grid, codexHome, dsh, prompt, name, agent, scmLaunchRecord } = input
if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
if (blocksFolder(cwd)) return { ok: false, error: 'WORKTREE_BUSY' }
+ const workspaceIdentity = () => { const info = statSync(cwd); return `${info.dev}:${info.ino}:${realpathSync(cwd)}` }
+ let originalWorkspace: string
try {
if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }
+ originalWorkspace = workspaceIdentity()
} catch {
return { ok: false, error: 'CWD_NOT_FOUND' }
}
+ // The local Desktop already made this workspace. Observe emptiness before any
+ // preparation writes, but grant trust only after its dependencies are ready.
+ const trustEmptyProject = context?.local === true && !dsh && dirname(cwd) === projectsRoot()
+ && await readdir(cwd).then(names => names.length === 0, () => false)
+ if (!authority.current()) return stale()
// A harness can pin its permission mode (`dshPinnedPermissionMode`): the Grid harness starts model
// servers, which Codex's sandbox would start without a GPU. Pinned before anything reads the mode,
// and recorded on the row like a chosen one, so a relaunch keeps it.
@@ -105,13 +123,23 @@ export function createAgentCreator({
permissionMode = pinnedMode
bypassPermission = permissionModeApproves(pinnedMode)
}
+ const inspected = await inspectNative?.(engine, { ...input, permissionMode, bypassPermission }, authority)
+ if (inspected && !inspected.ok) return 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())
+ if (!current()) return stale()
+ if (native && agent && !supportsNamedAgent(engine, native.opencodeMajor)) {
+ return { ok: false, error: 'AGENT_UNSUPPORTED', detail: new NamedAgentUnsupportedError(engine).message }
+ }
// An engine too old for the flag this permission mode launches it with prints its help and
// exits; the wrapper then hands the pane to a shell, and what the person gets is a terminal
// full of help text with nothing anywhere saying why (openharness#285, opencode without
// `--auto`). Refuse before opening a pane — this is a launch somebody is waiting on, and Ask
// works today. Codex has been checked this way since it gained `--approve-for-me`; every other
// engine with a permission flag was not, and carried the same failure.
- const refusal = await refusePermissionFlagIfUnsupported(engine, { permissionMode, bypassPermission })
+ const refusal = await refusePermissionFlagIfUnsupported(engine, { permissionMode, bypassPermission }, undefined, native)
+ if (!current()) return stale()
if (refusal) {
console.warn(`[agent] create refused · ${engine} · ${refusal.detail}`)
return { ok: false, ...refusal }
@@ -124,7 +152,7 @@ export function createAgentCreator({
// The `harness-` prefix is also discovery's whitelist for a pane nobody tagged (see `ownedHere` /
// `TmuxBackend.inventory()`): the panes this daemon creates carry its tag, which goes with them into
// any session the person moves them to.
- const label = buildHarnessSessionLabel(engine)
+ const label = authority.label
// Prepare the harness workspace, then bind its session context to the selected engine.
// Missing packages or invalid runtimes refuse the launch before the agent is started.
let dshEnv: Record<string, string> | undefined
@@ -153,10 +181,11 @@ export function createAgentCreator({
// refusal rather than a fallback — an agent silently started on the engine's own login spends the
// wrong account and looks identical to one that worked. Asked of models before a harness's workspace is
// laid out or trusted: a create refused here leaves the folder as it was.
- const built = grid ? await buildGridLaunch({ engine, override: grid, machine: await gridLaunchMachine(engine) }) : null
+ const built = grid ? await buildGridLaunch({ engine, override: grid, machine: await gridLaunchMachine(engine, native) }) : null
+ if (!current()) return stale()
if (built && !built.ok) {
console.warn(`[agent] create ${engine} refused · ${built.detail}`)
- return { ok: false, error: built.error, detail: built.detail }
+ return built
}
if (dsh) {
// Checked above: a harness that is not installed was refused before models was asked.
@@ -170,13 +199,16 @@ export function createAgentCreator({
}
try {
dshAccount = { privateGrid: await privateGridName().catch(() => null) }
+ if (!current()) return stale()
// Asked BEFORE the template goes in: afterwards every folder has content.
// Not there yet is empty; unreadable is not — trust is only ever granted on evidence.
const emptyBefore = await readdir(cwd).then((names) => names.length === 0,
(error: NodeJS.ErrnoException) => error.code === 'ENOENT')
+ if (!current()) return stale()
const materialized = await dshLaunch.materialize({ dsh, workspace: cwd, account: dshAccount, engine, key: label })
+ if (!current()) return stale()
if (!materialized.ok) {
- if (materialized.unavailable) return { ok: false, error: materialized.error, detail: materialized.detail }
+ if (materialized.unavailable) return materialized
throw new Error(materialized.detail)
}
for (const warning of materialized.warnings) console.warn(`[dsh] ${dsh} materialize · ${warning}`)
@@ -196,7 +228,9 @@ export function createAgentCreator({
return { ok: false, error: 'DSH_MATERIALIZE_FAILED', detail }
}
const prepared = await dshLaunch.launch({ dsh, workspace: cwd, engine, key: label, account: dshAccount })
- if (!prepared.ok) return { ok: false, error: prepared.error, detail: prepared.detail }
+ if (!current()) return stale()
+ if (!prepared.ok) return { ok: false, error: prepared.error, detail: prepared.detail,
+ ...(prepared.unavailable ? { unavailable: prepared.unavailable } : {}) }
dshEnv = prepared.launch.env
dshArgs = prepared.launch.args
dshLabel = harness.manifest.name
@@ -211,36 +245,62 @@ export function createAgentCreator({
console.warn(`[agent] create ${engine} refused · ${detail}`)
return { ok: false, error: 'TMUX_TOO_OLD_FOR_GRID', detail }
}
+ if (!current()) return stale()
gridLaunch = { env: { ...built.launch.env }, args: built.launch.args, webSearch: built.launch.webSearch }
// An engine whose provider lives in a file gets a directory this daemon owns, never the
// user's own dotfiles. The label is unique per creation, so two agents never share one.
if (built.launch.configDir) {
const { envVar, files, pointAt, links } = built.launch.configDir
try {
- const dir = await writeGridConfigDir(label, files, links)
+ const publication = native && publishConfig ? await publishConfig(label, files, links, current) : null
+ if (publication && !native?.retain?.(publication.proof)) return stale()
+ const dir = publication?.directory ?? await writeGridConfigDir(label, files, links)
// Pi is handed the directory; OpenCode's OPENCODE_CONFIG wants the file inside it.
gridLaunch.env[envVar] = pointAt ? join(dir, pointAt) : dir
} catch (error) {
const detail = `could not write ${engine}'s grid configuration · ${error instanceof Error ? error.message : error}`
console.warn(`[agent] create ${engine} refused · ${detail}`)
- return { ok: false, error: 'GRID_CONFIG_FAILED', detail }
+ return { ok: false, error: 'GRID_CONFIG_FAILED', detail, ...(native ? { unavailable: 'native' } : {}) }
}
}
// Named in the log because the pane itself gives nothing away: the engine looks exactly like a
// normally launched one. The key is never printed.
console.log(describeGridLaunch(engine, grid, built.launch.webSearch))
}
+ if (!current()) return stale()
+ if (trustEmptyProject) {
+ try {
+ // A clone or user edit can arrive while dependencies are being prepared.
+ // Trust only the same physical workspace, still empty at the write boundary.
+ const files = new NativeFiles()
+ const empty = files.entries(cwd).length === 0
+ if (!current()) return stale()
+ if (empty && workspaceIdentity() === originalWorkspace) {
+ files.verify()
+ const environment = native ? { ...native.environment, ...gridLaunch?.env, ...dshEnv } : undefined
+ const profile = engine === 'codex' && environment ? nativeHookLocations(environment).CODEX_HOME : codexHome
+ folderTrust(engine, profile, environment)?.record(cwd)
+ }
+ } catch (error) { console.warn(`[agent] pre-trust ${cwd} · ${error instanceof Error ? error.message : error}`) }
+ }
+ if (native && !await native.prepareHooks(hooksDisabled ? 0 : hookPort, authority.current,
+ { ...gridLaunch?.env, ...dshEnv }, gridLaunch ? gridConflictingEnvToClear(gridLaunch) : [])) return {
+ ok: false, error: 'NATIVE_LAUNCH_HELD', detail: 'Waiting to confirm the engine’s native hooks.', unavailable: 'native',
+ }
+ // Harness configuration can change the profile after executable discovery. Binding and Resume
+ // must retain the home the prepared child will actually use.
+ if (engine === 'codex' && native) codexHome = nativeHookLocations(native.environment).CODEX_HOME
// A Codex agent pointed at a profile OTHER than this machine's default reads hooks.json from
// THAT folder, not the one `harness login` already installed into — without this, such an agent
// fires no hook at all (no SessionStart/UserPromptSubmit/Stop) and never streams a single event.
// Idempotent, so paying this on every create against an already-set-up profile is free.
- if (codexHome && !hooksDisabled && !await engineHooks.codex.installIn(hookPort, codexHome)) return {
- ok: false, error: 'NATIVE_LAUNCH_HELD', detail: 'Waiting to confirm Codex’s hooks in the selected profile.',
+ if (!native && codexHome && !hooksDisabled && !await engineHooks.codex.installIn(hookPort, codexHome)) return {
+ ok: false, error: 'NATIVE_LAUNCH_HELD', detail: 'Waiting to confirm Codex’s hooks in the selected profile.', unavailable: 'native',
}
// OpenCode may have upgraded from 1.x to 2.x while this daemon was running. Its new TUI must
// not discover our old server plugin; the cached version probe changes with the executable.
// Native installation is eager. A plugin is how this engine tells the daemon its session.
- if (engine === 'opencode' && !hooksDisabled && !await installOpencodePlugin(hookPort)) {
+ if (!native && engine === 'opencode' && !hooksDisabled && !await installOpencodePlugin(hookPort)) {
const detail = 'OpenCode\'s plugin installer could not be loaded'
console.warn(`[agent] create opencode refused · ${detail}`)
return { ok: false, error: 'ENGINE_UNAVAILABLE', detail }
@@ -258,11 +318,11 @@ export function createAgentCreator({
// The named agent takes the same argv slot on every relaunch (`buildLaunchOverrides` appends it
// from the row's `agent`, after the grid's and the DSH's argv, exactly as here). The engine was
// checked for a contract at the wire (AGENT_UNSUPPORTED, opencode v2 included), so this cannot throw.
- const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, opencode ? await opencode.opencodeMajorVersion() : null) : [])]
+ const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, native ? native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null) : [])]
// The first prompt is a launch option only — never part of `extraArgs`, which the registry row
// carries into a relaunch (engineLaunch.ts, `firstPrompt`).
const firstPrompt = prompt
- const launchOptions = { bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), terminalHint: { machineName: terminalHintMachineName() } }
+ const launchOptions = { ...(native ? { native } : {}), bypassPermission, ...(permissionMode ? { permissionMode } : {}), extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd, harnessNode: dsh ? true : undefined, ...(firstPrompt ? { firstPrompt } : {}), terminalHint: { machineName: terminalHintMachineName() } }
const command = buildEngineCommandArgv(engine, launchOptions)
const argv = buildEngineLaunchArgv(engine, launchOptions)
// A tmux route is enough to stream its screen. Register it before looking for a process so both
@@ -274,11 +334,16 @@ export function createAgentCreator({
// there: a stale registry entry from a previous tmux-server generation occasionally collides with
// a freshly-minted pane id, and that collision clears on its own on the very next pane.
await prepareInstructionWrites(cwd)
+ if (!current()) return stale()
prepareApiTools(cwd, engine)
// Mutually exclusive with a grid (backendSocket.ts refuses the two together): a chosen Codex
// profile becomes the new session's CODEX_HOME (its session store's variable, lib/engineHomes.ts
// `profileEnvironment`), the same `-e` mechanism a grid's own env rides.
+ if (!current()) return stale()
+ return { ok: true, dispatch: async () => {
+ if (!current()) return stale()
const result = await createAndRegisterPane({
+ current, ...(native ? { nativeToken: native.token } : {}),
tmuxBackend,
registry,
engine,
@@ -286,7 +351,7 @@ export function createAgentCreator({
sessionLabel: label,
argv,
env: freshHarnessEnvironment(engine, mergedLaunchEnv(mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? profileEnvironment(engine, codexHome) : undefined), dshEnv),
- scmLaunchEnv(scmLaunchRecord)), !!grid,
+ mergedLaunchEnv(scmLaunchEnv(scmLaunchRecord), native?.environment)), !!grid,
permissionMode ?? (bypassPermission ? DEFAULT_HARNESS_PERMISSION : 'ask')),
grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,
gridLaunchRecord: grid && gridLaunch ? { override: grid, webSearch: gridLaunch.webSearch } : null,
@@ -318,6 +383,12 @@ export function createAgentCreator({
void watchNewPane(engine, pending, spawned, command, installIfMissing, undefined)
console.log(`[agent] create pane open · ${engine} · agent ${pending.agentId}`)
return { ok: true, session: pending }
+ } }
+ }
+ const createAgent: CreateAgent = async input => {
+ const label = buildHarnessSessionLabel(input.engine)
+ const prepared = await prepare(input, { id: label, label, current: () => true, hold: () => {} })
+ return prepared.ok ? prepared.dispatch() : prepared
}
- return createAgent
+ return Object.assign(createAgent, { prepare })
}
diff --git a/cli/src/core/agents/externalPreflight.spec.ts b/cli/src/core/agents/externalPreflight.spec.ts
index a7f263bf0..533f9a238 100644
--- a/cli/src/core/agents/externalPreflight.spec.ts
+++ b/cli/src/core/agents/externalPreflight.spec.ts
@@ -4,11 +4,12 @@ import { engineHooks } from '../../engines/hooks.js'
import { buildEngineCommandArgv, refusePermissionFlagIfUnsupported } from '../../lib/engineLaunch.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import { createExternalPreflight } from './externalPreflight.js'
+import type { NativeLaunch } from '../../engines/nativeLaunch.js'
vi.mock('../../engines/inProcess.js', () => ({ loadEngine: vi.fn(async () => ({})) }))
vi.mock('../../engines/hooks.js', () => ({ engineHooks: { codex: { installIn: vi.fn(async () => true) } } }))
vi.mock('../../lib/engineLaunch.js', () => ({ buildEngineCommandArgv: vi.fn(() => []), refusePermissionFlagIfUnsupported: vi.fn(async () => null) }))
vi.mock('../../lib/workspaceCheck.js', () => ({ workspaceMissing: vi.fn(() => null) }))
-afterEach(() => { vi.clearAllMocks() })
+afterEach(() => { vi.clearAllMocks(); vi.mocked(refusePermissionFlagIfUnsupported).mockReset().mockResolvedValue(null) })
const session = { sessionId: 'conversation', cwd: '/fixture/work', launchArgs: ['-p', 'work'] } as never
const row = (engine = 'claude', extra = {}) => ({ engine, permissionMode: 'ask', bypassPermission: false, ...extra }) as never
function setup(over = {}) {
@@ -57,3 +58,43 @@ it('waits for profile durability before admitting a takeover and retains an unav
expect(buildEngineCommandArgv).not.toHaveBeenCalled()
expect(await setup().prepare(row('codex', { codexHome: '/fixture/profile' }), session)).toBeNull()
})
+
+it('retains a checked native snapshot through takeover instead of starting another version or hook probe', async () => {
+ let current = true
+ const launch = { current: () => current, prepareHooks: vi.fn(async () => true) } as unknown as NativeLaunch
+ const native = vi.fn(async () => ({ ok: true as const, launch }))
+ const run = setup({ native })
+ const ready = await run.prepare(row('opencode'), session)
+ expect(ready).toHaveProperty('current')
+ if (!ready || !('current' in ready)) throw Error('fixture held')
+ expect(ready.current()).toBe(true)
+ expect(run.deps.installOpencodePlugin).not.toHaveBeenCalled()
+ expect(refusePermissionFlagIfUnsupported).toHaveBeenCalledWith('opencode', expect.any(Object), undefined, launch)
+ expect(buildEngineCommandArgv).toHaveBeenCalledWith('opencode', expect.objectContaining({ native: launch }))
+ current = false
+ expect(ready.current()).toBe(false)
+})
+
+it('keeps a takeover held while native preparation or its original owner is unavailable', async () => {
+ const held = { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting for installer' }
+ const native = vi.fn(async () => held)
+ expect(await setup({ native }).prepare(row(), session)).toMatchObject({ detail: held.detail })
+ native.mockClear()
+ expect(await setup({ native }).prepare(row(), session, () => false)).not.toBeNull()
+ expect(native).not.toHaveBeenCalled()
+ const launch = { current: () => true, prepareHooks: vi.fn(async () => false) } as unknown as NativeLaunch
+ expect(await setup({ native: async () => ({ ok: true, launch }) }).prepare(row(), session)).toMatchObject({ detail: expect.stringContaining('hooks') })
+ expect(buildEngineCommandArgv).not.toHaveBeenCalled()
+})
+
+it.each(['inspection', 'permission', 'hooks', 'disabled hooks'] as const)('retains owner authority across %s', async stage => {
+ let current = true
+ const launch = { current: () => current, prepareHooks: vi.fn(async () => { if (stage === 'hooks') current = false; return true }) } as unknown as NativeLaunch
+ const native = vi.fn(async () => { if (stage === 'inspection') current = false; return { ok: true as const, launch } })
+ vi.mocked(refusePermissionFlagIfUnsupported).mockImplementationOnce(async () => { if (stage === 'permission') current = false; return null })
+ const result = await setup({ native, hooksDisabled: stage === 'disabled hooks' }).prepare(row(), session, () => current)
+ if (stage === 'disabled hooks') {
+ expect(result).toHaveProperty('current')
+ expect(launch.prepareHooks).toHaveBeenCalledWith(0, expect.any(Function))
+ } else expect(result).toMatchObject({ detail: expect.stringContaining('authority') })
+})
diff --git a/cli/src/core/agents/externalPreflight.ts b/cli/src/core/agents/externalPreflight.ts
index 5ed067ae0..5425206d7 100644
--- a/cli/src/core/agents/externalPreflight.ts
+++ b/cli/src/core/agents/externalPreflight.ts
@@ -3,27 +3,39 @@ import { engineHooks } from '../../engines/hooks.js'
import { buildEngineCommandArgv, refusePermissionFlagIfUnsupported } from '../../lib/engineLaunch.js'
import { workspaceMissing } from '../../lib/workspaceCheck.js'
import type { ExternalResumeDeps } from './externalResume.js'
+import type { LaunchOverridesDeps } from '../../lib/launchOverrides.js'
export function createExternalPreflight(deps: {
+ native?: LaunchOverridesDeps['native']
blocksFolder(cwd: string): boolean | undefined
hooksDisabled: boolean
hookPort: number
installOpencodePlugin(port: number): Promise<boolean>
}): ExternalResumeDeps['preflight'] {
- return async (row, session) => {
+ return async (row, session, owner = () => true) => {
const missing = workspaceMissing(session.cwd)
if (missing) return missing
if (deps.blocksFolder(session.cwd)) return { detail: 'Waiting for the workspace operation to finish.' }
- const refused = await refusePermissionFlagIfUnsupported(row.engine, row)
+ const changed = { detail: 'Waiting for the original external-resume request’s authority.' }
+ if (!owner()) return changed
+ const inspected = await deps.native?.(row.engine, row, { id: row.agentId, current: owner })
+ if (!owner()) return changed
+ if (inspected && !inspected.ok) return inspected
+ const native = inspected?.ok ? inspected.launch : undefined
+ const current = () => owner() && native?.current() !== false
+ const refused = await refusePermissionFlagIfUnsupported(row.engine, row, undefined, native)
+ if (!current()) return changed
if (refused) return refused
- if (row.engine === 'opencode' && !deps.hooksDisabled && !await deps.installOpencodePlugin(deps.hookPort)) {
+ if (native && !await native.prepareHooks(deps.hooksDisabled ? 0 : deps.hookPort, owner)) return { detail: 'Waiting to confirm the external conversation’s native hooks.' }
+ if (!native && row.engine === 'opencode' && !deps.hooksDisabled && !await deps.installOpencodePlugin(deps.hookPort)) {
return { detail: 'Waiting for OpenCode’s launch support to become available.' }
}
- if (row.codexHome && !deps.hooksDisabled && !await engineHooks.codex.installIn(deps.hookPort, row.codexHome)) {
+ if (!native && row.codexHome && !deps.hooksDisabled && !await engineHooks.codex.installIn(deps.hookPort, row.codexHome)) {
return { detail: 'Waiting to confirm Codex’s hooks in the selected profile.' }
}
- buildEngineCommandArgv(row.engine, { cwd: session.cwd, resumeSessionId: session.sessionId,
+ if (!current()) return changed
+ buildEngineCommandArgv(row.engine, { ...(native ? { native } : {}), cwd: session.cwd, resumeSessionId: session.sessionId,
bypassPermission: row.bypassPermission, permissionMode: row.permissionMode, extraArgs: session.launchArgs })
- return null
+ return native ? { current } : null
}
}
diff --git a/cli/src/core/agents/externalResume.spec.ts b/cli/src/core/agents/externalResume.spec.ts
index a1c66f03e..fb81c7ba4 100644
--- a/cli/src/core/agents/externalResume.spec.ts
+++ b/cli/src/core/agents/externalResume.spec.ts
@@ -146,6 +146,48 @@ it('never transfers takeover permission to a replacement owner or interrupts wor
expect(test.deps.stopOwner).toHaveBeenCalledTimes(1)
})
+it('checks the prepared executable after durably saving a signal intent before touching its original owner', async () => {
+ const actual = await vi.importActual<typeof import('./externalOwner.js')>('./externalOwner.js')
+ const test = setup(), kill = vi.fn()
+ let nativeCurrent = true
+ test.inspect.mockImplementation(async request => held(request))
+ vi.mocked(test.deps.preflight).mockResolvedValue({ current: () => nativeCurrent })
+ const save = vi.mocked(test.registry.setExternalResume).getMockImplementation()!
+ vi.mocked(test.registry.setExternalResume).mockImplementation((id, intent) => {
+ const row = save(id, intent)
+ if (intent.signal === 'prepared') nativeCurrent = false
+ return row
+ })
+ test.deps.stopOwner = (owner, control) => actual.stopExternalOwner(owner, {
+ ...control, generation: () => 'ps:1', exists: () => true,
+ job: async () => null, kill, sleep: async () => {},
+ })
+ const id = await test.stage({ takeOver: 'idle' }); await test.controller.settled()
+ expect(kill).not.toHaveBeenCalled()
+ expect(test.deps.launch).not.toHaveBeenCalled()
+ expect(test.rows.get(id)?.externalResume).toMatchObject({ phase: 'quitting', signal: 'prepared' })
+})
+
+it('holds admission when native preparation changes during the last search read', async () => {
+ const test = setup()
+ let prepared = false, current = true
+ vi.mocked(test.deps.preflight).mockImplementation(async () => { prepared = true; return { current: () => current } })
+ test.inspect.mockImplementation(async request => { if (prepared) current = false; return free(request) })
+ const id = await test.stage(); await test.controller.settled()
+ expect(test.rows.get(id)?.launch).toMatchObject({ state: 'held', detail: expect.stringContaining('native launch') })
+ expect(test.rows.get(id)?.externalResume?.phase).toBe('waiting')
+ expect(test.deps.launch).not.toHaveBeenCalled()
+})
+
+it('does not take over a terminal when its completed native preparation is already obsolete', async () => {
+ const test = setup(); test.inspect.mockImplementation(async request => held(request))
+ vi.mocked(test.deps.preflight).mockResolvedValue({ current: () => false })
+ const id = await test.stage({ takeOver: 'idle' }); await test.controller.settled()
+ expect(test.deps.stopOwner).not.toHaveBeenCalled()
+ expect(test.deps.launch).not.toHaveBeenCalled()
+ expect(test.rows.get(id)?.launch?.state).toBe('held')
+})
+
it('explicit takeover of unknown activity never manufactures a continuation prompt', async () => {
const test = setup()
test.inspect.mockImplementation(async request => ({ ...held(request), busy: true }))
diff --git a/cli/src/core/agents/externalResume.ts b/cli/src/core/agents/externalResume.ts
index b64378c11..20037a899 100644
--- a/cli/src/core/agents/externalResume.ts
+++ b/cli/src/core/agents/externalResume.ts
@@ -30,7 +30,7 @@ export interface ExternalResumeDeps {
generation(): unknown
stopped(): readonly Pick<RegisteredSession, 'sessionId' | 'externalResume'>[]
cancelled(agentId: string): boolean
- preflight(row: RegisteredSession, session: NonNullable<ExternalResumeIntent['session']>): Promise<{ detail: string } | null>
+ preflight(row: RegisteredSession, session: NonNullable<ExternalResumeIntent['session']>, current?: () => boolean): Promise<{ detail: string } | { current(): boolean } | null>
announce(row: RegisteredSession): void
launch(): void
forget(agentId: string): void
@@ -78,9 +78,11 @@ export function createExternalResumes(deps: ExternalResumeDeps) {
}
if (!commit({ ...intent, session, ...(owner ? { owner } : {}) })) return
if (owner && decision.busy && intent.takeOver === 'wait') { hold(row, activityUnknown(answer) ? ACTIVITY_UNKNOWN : 'Waiting for the conversation’s current turn to finish in its terminal.'); return }
- const refusal = await deps.preflight(row, session)
+ const refusal = await deps.preflight(row, session, current)
if (!current()) return
- if (refusal) { hold(row, refusal.detail); return }
+ if (refusal && 'detail' in refusal) { hold(row, refusal.detail); return }
+ const nativeCurrent = () => !refusal || refusal.current()
+ if (!nativeCurrent()) { hold(row, 'Waiting to confirm the prepared native launch.'); return }
if (owner) {
// Journal the exact target before a signal. A crash or a later process cannot inherit consent.
if (!commit({ ...row.externalResume!, phase: 'quitting', owner })) return
@@ -92,13 +94,13 @@ export function createExternalResumes(deps: ExternalResumeDeps) {
if (!current() || !answer.ok || !answer.session) return false
const fresh = adoptionDecision(intent.request.sessionId, intent.request.engine, intent.takeOver, answer, id => held(id, row.agentId))
interrupted = answer.busyConfirmed === true
- return fresh.ok && answer.session.sessionId === session.sessionId && answer.session.cwd === session.cwd
+ return nativeCurrent() && fresh.ok && answer.session.sessionId === session.sessionId && answer.session.cwd === session.cwd
&& answer.session.transcriptPath === session.transcriptPath
&& JSON.stringify(answer.session.launchArgs) === JSON.stringify(session.launchArgs)
&& !!answer.owner && !!answer.generation && sameOwner(owner, { process: answer.owner, generation: answer.generation })
&& (intent.takeOver === 'now' || !answer.busy)
}
- if (!await (deps.stopOwner ?? stopExternalOwner)(owner, { current, same,
+ if (!await (deps.stopOwner ?? stopExternalOwner)(owner, { current: () => current() && nativeCurrent(), same,
beforeSignal: signal => {
// KILL needs the same locked conflict check after TERM's grace period, even when the
// durable intent is unchanged. A daemon-down hook can bind another owner meanwhile.
@@ -121,6 +123,7 @@ export function createExternalResumes(deps: ExternalResumeDeps) {
// No asynchronous work may separate this final read from the durable admission.
answer = await inspect(intent.request)
if (!current()) return
+ if (!nativeCurrent()) { hold(row, 'Waiting to confirm the prepared native launch is still current.'); return }
const final = adoptionDecision(intent.request.sessionId, intent.request.engine, intent.takeOver, answer, id => held(id, row.agentId))
if (!final.ok) { hold(row, final.detail); return }
if (!answer.ok || !answer.session || answer.owner || answer.session.sessionId !== session.sessionId
diff --git a/cli/src/core/agents/fork.spec.ts b/cli/src/core/agents/fork.spec.ts
index d52d84c17..f1287720b 100644
--- a/cli/src/core/agents/fork.spec.ts
+++ b/cli/src/core/agents/fork.spec.ts
@@ -10,6 +10,8 @@ import { planFork } from '../../lib/forkAgent.js'
import { prepareInstructionWrites } from '../../scm/scmProjects.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { createAgentForker, type ForkAgentDeps } from './fork.js'
+import type { NativeLaunch } from '../../engines/nativeLaunch.js'
+import { createLaunchHelpers } from './launch.js'
vi.mock('../../dsh/installed.js', () => ({ installedDsh: vi.fn(() => undefined) }))
@@ -82,6 +84,102 @@ describe('forking an agent', () => {
})
afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+ it.each(['initial', 'source', 'inspect', 'harness', 'overrides', 'hooks', 'permission', 'instructions'] as const)(
+ 'cannot dispatch a fork whose original owner is revoked during %s', async stage => {
+ let current = stage !== 'initial'
+ const revoke = (at: string) => { if (stage === at) current = false }
+ const launch = { current: () => true, environment: { HOME: root }, opencodeMajor: 1 } as unknown as NativeLaunch
+ vi.mocked(installedDsh).mockReturnValue({ manifest: { name: 'Fixture' } } as never)
+ vi.mocked(refusePermissionFlagIfUnsupported).mockImplementation(async () => { revoke('permission'); return null })
+ vi.mocked(prepareInstructionWrites).mockImplementation(async () => revoke('instructions'))
+ const run = setup(source({ dsh: 'fixture/tools' }), {
+ authority: () => () => stage !== 'source',
+ native: async (_engine, _source, authority) => { authority.hold({ service: 'native', detail: 'Checking fixture' }); revoke('inspect'); return { ok: true, launch } },
+ dshLaunch: { launch: async () => { revoke('harness'); return { ok: true, launch: { env: {}, args: [] } } } },
+ relaunchOverrides: async () => { revoke('overrides'); return { ok: true, overrides: { native: launch, env: {}, extraArgs: [], clearEnv: [] } } },
+ prepareNative: async () => { revoke('hooks'); return true },
+ })
+ try {
+ const result = await run.fork.prepare({ agentId: 'a1', name: null, prompt: 'original prompt' },
+ { id: 'fixture', label: 'harness-claude-fixture', current: () => current, hold: vi.fn() })
+ expect(result).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ } finally {
+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
+ vi.mocked(refusePermissionFlagIfUnsupported).mockReset().mockResolvedValue(null)
+ vi.mocked(prepareInstructionWrites).mockReset().mockResolvedValue(undefined)
+ }
+ },
+ )
+
+ it('holds an unconfirmed final fork configuration before permission checks or dispatch', async () => {
+ const launch = { current: () => true, environment: { HOME: root }, opencodeMajor: 1 } as unknown as NativeLaunch
+ const run = setup(source(), {
+ native: async (_engine, _source, authority) => { authority.hold({ service: 'native', detail: 'Checking fixture' }); return { ok: true, launch } },
+ relaunchOverrides: async () => ({ ok: true, overrides: { native: launch, env: {}, extraArgs: [], clearEnv: [] } }),
+ prepareNative: async () => false,
+ })
+ expect(await run.fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ unavailable: 'native' })
+ expect(refusePermissionFlagIfUnsupported).not.toHaveBeenCalled()
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ })
+
+ it('holds unavailable native preparation without touching the source or opening a pane', async () => {
+ const native = vi.fn(async () => ({ ok: false as const, error: 'NATIVE_LAUNCH_HELD' as const, unavailable: 'native' as const, detail: 'Installing' }))
+ const run = setup(source(), { native })
+ expect(await run.fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ unavailable: 'native' })
+ expect(run.deps.relaunchOverrides).not.toHaveBeenCalled()
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ })
+
+ it('prepares final fork locations with one snapshot and retains ownership until dispatch', async () => {
+ vi.mocked(installedDsh).mockReturnValueOnce({ manifest: { name: 'Fixture' } } as never)
+ const launch = { current: () => true, opencodeMajor: 2, environment: { HOME: '/fixture/home', CODEX_HOME: '/fixture/profile' }, token: 'fixture-native' } as unknown as NativeLaunch
+ const native = vi.fn(async () => ({ ok: true as const, launch }))
+ const prepareNative = vi.fn(async () => true)
+ const relaunchOverrides = vi.fn(async () => ({ ok: true as const, overrides: { native: launch, env: { CODEX_HOME: '/fixture/profile' }, extraArgs: [], clearEnv: [] } }))
+ const run = setup(source({ engine: 'codex', dsh: 'fixture/tools' }), { native, prepareNative, relaunchOverrides })
+ let current = true
+ const authority = { id: 'fixture-operation', label: 'harness-codex-fixture', current: () => current, hold: vi.fn() }
+ const prepared = await run.fork.prepare({ agentId: 'a1', name: null, prompt: null }, authority)
+ expect(prepared.ok).toBe(true)
+ expect(native).toHaveBeenCalledOnce()
+ expect(relaunchOverrides).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), expect.any(Function), launch, authority.label)
+ expect(prepareNative).toHaveBeenCalledWith(launch, expect.any(Function), expect.objectContaining({ CODEX_HOME: '/fixture/profile', HARNESS_DSH: 'blender' }), expect.any(Array))
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ current = false
+ if (!prepared.ok) throw Error('fixture held')
+ expect(await prepared.dispatch()).toMatchObject({ error: 'AGENT_CHANGED' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
+ })
+
+ it.each(['claude', 'codex'] as const)('keeps real %s launch preparation authorized and records its final harness-selected home', async engine => {
+ const executable = await import('../../engines/kit/launchExecutable.js')
+ vi.spyOn(executable, 'captureLaunchExecutable').mockResolvedValue({ state: 'ready',
+ executable: { command: '/fixture/engine', identity: 'fixture', current: () => true },
+ environment: { HOME: root, PATH: '/fixture/bin' },
+ })
+ const { inspectNativeLaunch } = await import('../../engines/nativeLaunch.js')
+ const prepareNative = (native: NativeLaunch, current: () => boolean, environment?: Readonly<Record<string, string>>, clear?: readonly string[]) => native.prepareHooks(0, current, environment, clear)
+ const helpers = createLaunchHelpers({ authority: () => () => true, prepareApiTools: vi.fn(), setGridLaunch: vi.fn(), setTail: vi.fn(),
+ launchOverridesDeps: { native: (engine, source) => inspectNativeLaunch(engine, source), prepareNative,
+ machine: () => ({ hermesSystemManaged: false }), gridLaunch: vi.fn(), writeGridConfigDir: vi.fn(),
+ tmuxSupportsSessionEnv: async () => true, installCodexHooks: async () => true,
+ },
+ })
+ const finalHome = join(root, 'harness-codex')
+ vi.mocked(installedDsh).mockReturnValueOnce({ manifest: { name: 'Fixture' } } as never)
+ launchDsh.mockResolvedValueOnce({ ok: true, launch: { env: { CODEX_HOME: finalHome }, args: [] } })
+ const run = setup(source({ engine, codexHome: join(root, 'selected-codex'), dsh: 'fixture/tools' }), { native: (engine, source) => inspectNativeLaunch(engine, source), prepareNative, relaunchOverrides: helpers.relaunchOverrides })
+ expect(await run.fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ ok: true })
+ expect(executable.captureLaunchExecutable).toHaveBeenCalledOnce()
+ const request = vi.mocked(createAndRegisterPane).mock.calls[0]![0]
+ expect(request.current?.()).toBe(true)
+ expect(request.env?.HOME).toBe(root)
+ expect(request.env?.CODEX_HOME).toBe(finalHome)
+ if (engine === 'codex') expect(request.codexHome).toBe(finalHome)
+ })
+
it('does not open instruction files or install API notes while its harness waits for the Store', async () => {
vi.mocked(installedDsh).mockReturnValueOnce({ manifest: { name: 'Fixture' } } as never)
launchDsh.mockResolvedValueOnce({ ok: false, error: 'DSH_UNAVAILABLE', detail: 'Waiting for the Store.', unavailable: 'store' })
@@ -111,8 +209,11 @@ describe('forking an agent', () => {
expect(await setup().fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'FORK_UNSUPPORTED', detail: 'amp cannot fork' })
expect(await setup(source({ dsh: 'blender' } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })).toMatchObject({ error: 'INVALID_DSH' })
vi.mocked(installedDsh).mockReturnValue({ manifest: { name: 'Blender' } } as never)
- launchDsh.mockResolvedValueOnce({ ok: false, error: 'DSH_RUNTIME', detail: 'no runtime' } as never)
+ launchDsh.mockResolvedValueOnce({ ok: false, error: 'DSH_RUNTIME', detail: 'no runtime', thrown: 'Error: no runtime' })
expect(await setup(source({ dsh: 'blender' } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'DSH_RUNTIME', detail: 'no runtime' })
+ launchDsh.mockResolvedValueOnce({ ok: false, error: 'DSH_UNAVAILABLE', detail: 'Store unavailable', unavailable: 'store' })
+ expect(await setup(source({ dsh: 'blender' } as Partial<RegisteredSession>)).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'DSH_UNAVAILABLE', detail: 'Store unavailable', unavailable: 'store' })
+ expect(createAndRegisterPane).not.toHaveBeenCalled()
vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)
vi.mocked(refusePermissionFlagIfUnsupported).mockResolvedValueOnce({ error: 'PERMISSION_MODE_UNSUPPORTED', detail: 'no --auto' } as never)
expect(await setup().fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'PERMISSION_MODE_UNSUPPORTED', detail: 'no --auto' })
@@ -170,7 +271,7 @@ describe('forking an agent', () => {
const row = source({ engine: 'codex', codexHome: '/codex', subscriptionModel: 'gpt-6', dsh: 'blender', agent: 'reviewer' } as Partial<RegisteredSession>)
await setup(row, { relaunchOverrides }).fork({ agentId: 'a1', name: null, prompt: null })
// The harness's runtime is the fork's own and so is its named agent: neither is rebuilt from the row.
- expect(relaunchOverrides).toHaveBeenCalledWith(row, expect.objectContaining({ codexHome: '/codex', subscriptionModel: 'gpt-6', dsh: null, agent: null }))
+ expect(relaunchOverrides).toHaveBeenCalledWith(row, expect.objectContaining({ codexHome: '/codex', subscriptionModel: 'gpt-6', dsh: null, agent: null }), expect.any(Function), undefined, expect.stringContaining('harness-codex-'))
expect(vi.mocked(buildEngineLaunchArgv).mock.calls[0][1]).toMatchObject({
extraArgs: ['-c', 'model_provider="openai"', '-m', 'gpt-6', '--dsh', '--agent', 'reviewer'],
// What the harness's launch provides is never cleared under it.
diff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.ts
index 0ac6a68a0..93a34f573 100644
--- a/cli/src/core/agents/fork.ts
+++ b/cli/src/core/agents/fork.ts
@@ -27,10 +27,18 @@ import { prepareInstructionWrites, scmLaunchEnv } from '../../scm/scmProjects.js
import type { createLaunchHelpers } from './launch.js'
import { mergedLaunchEnv } from './launchEnv.js'
import type { createPaneWatcher } from './newPane.js'
+import type { NativeLaunchResult, NativeLaunchSource } from '../../engines/nativeLaunch.js'
+import type { LaunchAuthority, LaunchPreparation } from '../../lib/launchPreparation.js'
+import type { LaunchOverridesDeps } from '../../lib/launchOverrides.js'
+import type { AgentEngine } from '../../engines/types.js'
+import { nativeHookLocations } from '../../engines/kit/nativeLocations.js'
type ForkAgent = NonNullable<BackendSocket['onForkAgent']>
export interface ForkAgentDeps {
+ native?: (engine: AgentEngine, source: NativeLaunchSource, authority: LaunchAuthority) => Promise<NativeLaunchResult>
+ prepareNative?: LaunchOverridesDeps['prepareNative']
+ authority?: (agentId: string) => () => boolean
tmuxBackend: TmuxBackend | null
registry: typeof registry
mirror: Pick<TurnRecaps, 'isBusy' | 'recentAsks' | 'recent' | 'lastFullText'>
@@ -48,12 +56,18 @@ export interface ForkAgentDeps {
}
export function createAgentForker({
+ native: inspectNative, prepareNative, authority: captureAuthority,
tmuxBackend, registry, mirror, pendingForkInherit, watchNewPane, announceSession, attachDsh, prepareApiTools, relaunchOverrides, gridName, dshLaunch,
}: ForkAgentDeps) {
- const forkAgent: ForkAgent = async ({ agentId, name, prompt }) => {
+ const prepare = async ({ agentId, name, prompt }: Parameters<ForkAgent>[0], authority: LaunchAuthority): Promise<LaunchPreparation<Awaited<ReturnType<ForkAgent>>>> => {
+ const ownsSource = captureAuthority?.(agentId) ?? (() => true)
+ const owner = () => authority.current() && ownsSource()
+ const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The original fork source changed or stopped during preparation.' } as const
+ if (!owner()) return changed
if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }
- const source = registry.byAgent(agentId)
- if (!source) return { ok: false, error: 'AGENT_NOT_FOUND' }
+ const observed = registry.byAgent(agentId)
+ if (!observed) return { ok: false, error: 'AGENT_NOT_FOUND' }
+ const source = structuredClone(observed)
const sourceName = projectDisplayName(source)
if (!source.cwd) return { ok: false, error: 'CWD_NOT_FOUND', detail: `${sourceName} has no working folder on record.` }
try {
@@ -77,7 +91,12 @@ export function createAgentForker({
if (!plan.ok) return { ok: false, error: plan.error, detail: plan.detail }
const opencode = engine === 'opencode' ? opencodeLaunch : null
- const label = buildHarnessSessionLabel(engine)
+ const label = authority.label
+ const inspected = await inspectNative?.(engine, source, { ...authority, current: owner })
+ if (!owner()) return changed
+ if (inspected && !inspected.ok) return inspected
+ const native = inspected?.ok ? inspected.launch : undefined
+ const current = () => owner() && native?.current() !== false
// Fork the source's saved harness context. Workspace templates and init are not run again.
let dshEnv: Record<string, string> | undefined
let dshArgs: string[] = []
@@ -89,7 +108,9 @@ export function createAgentForker({
const cwd = source.cwd
const prepared = await dshLaunch.launch({ dsh: source.dsh, workspace: cwd, engine, key: label,
account: { privateGrid: gridName() }, forkOf: { agentId: source.agentId, dshRuntime: source.dshRuntime ?? null } })
- if (!prepared.ok) return { ok: false, error: prepared.error, detail: prepared.detail }
+ if (!current()) return changed
+ if (!prepared.ok) return { ok: false, error: prepared.error, detail: prepared.detail,
+ ...(prepared.unavailable ? { unavailable: prepared.unavailable } : {}) }
dshEnv = prepared.launch.env
dshArgs = prepared.launch.args
dshLabel = installed.manifest.name
@@ -100,15 +121,23 @@ export function createAgentForker({
// its hooks. A fork was launched without any of them, and came back on Codex's default model where a
// restart of its source came back on the source's own (e2e/forks.e2e.ts). The harness and the named
// agent are the fork's own (a new runtime, above and below), so they are not rebuilt here.
- const built = await relaunchOverrides(source, { ...source, dsh: null, agent: null })
- if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
+ const built = await relaunchOverrides(source, { ...source, dsh: null, agent: null }, owner, native, label)
+ if (!current()) return changed
+ if (!built.ok) return built
+ if (built.overrides.native && prepareNative && !await prepareNative(built.overrides.native, owner,
+ { ...built.overrides.env, ...dshEnv }, [...built.overrides.clearEnv, ...harnessEnvToClear(dshEnv)])) {
+ return { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting to confirm the fork’s final native configuration.' }
+ }
+ if (!current()) return changed
+ const dispatchCurrent = () => current() && built.overrides.native?.current() !== false
const installIfMissing = enginePathOverride(engine) ? undefined : engineInstallRecipe(engine)
// Same guard as a relaunch (`buildLaunchOverrides`): an opencode agent recorded on v1 forks on v2
// as a general session rather than handing the v2 TUI an `--agent` it exits on.
- const forkMajor = opencode ? await opencode.opencodeMajorVersion() : null
+ const forkMajor = built.overrides.native ? built.overrides.native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null
const extraArgs = [...built.overrides.extraArgs, ...dshArgs, ...(source.agent && supportsNamedAgent(engine, forkMajor) ? namedAgentArgs(engine, source.agent, forkMajor) : [])]
const firstPrompt = plan.level === 'native' ? (prompt ?? undefined) : plan.firstPrompt
const launchOptions = {
+ ...(built.overrides.native ? { native: built.overrides.native } : {}),
clearEnv: harnessEnvToClear(dshEnv),
bypassPermission: source.bypassPermission ?? false,
...(source.permissionMode ? { permissionMode: source.permissionMode } : {}),
@@ -121,16 +150,21 @@ export function createAgentForker({
}
// Same refusal as create: the clone inherits the source's permission mode, and an engine that
// has since been downgraded would hand back a pane of help text instead of a harness.
- const forkRefusal = await refusePermissionFlagIfUnsupported(engine, launchOptions)
+ const forkRefusal = await refusePermissionFlagIfUnsupported(engine, launchOptions, undefined, built.overrides.native)
+ if (!dispatchCurrent()) return changed
if (forkRefusal) {
console.warn(`[agent] fork refused · ${engine} · ${forkRefusal.detail}`)
return { ok: false, ...forkRefusal }
}
await prepareInstructionWrites(source.cwd)
+ if (!dispatchCurrent()) return changed
prepareApiTools(source.cwd, engine)
const command = buildEngineCommandArgv(engine, launchOptions)
const argv = buildEngineLaunchArgv(engine, launchOptions)
+ return { ok: true, dispatch: async () => {
+ if (!dispatchCurrent()) return changed
const result = await createAndRegisterPane({
+ current: dispatchCurrent, ...(built.overrides.native ? { nativeToken: built.overrides.native.token } : {}),
tmuxBackend,
registry,
engine,
@@ -138,12 +172,14 @@ export function createAgentForker({
sessionLabel: label,
argv,
// The SCM's environment last, after the harness context's, as at create and relaunch.
- env: mergedLaunchEnv(mergedLaunchEnv(Object.keys(built.overrides.env).length ? built.overrides.env : undefined, dshEnv), scmLaunchEnv(source.scmLaunch)),
+ env: mergedLaunchEnv(mergedLaunchEnv(Object.keys(built.overrides.env).length ? built.overrides.env : undefined, dshEnv),
+ mergedLaunchEnv(scmLaunchEnv(source.scmLaunch), built.overrides.native?.environment)),
grid: null,
gridLaunchRecord: null,
// Same folder as the source, so the same workspace binding.
scmLaunchRecord: source.scmLaunch ?? null,
- codexHome: source.codexHome ?? null,
+ codexHome: engine === 'codex' && built.overrides.native
+ ? nativeHookLocations(built.overrides.native.environment).CODEX_HOME : source.codexHome ?? null,
dshRuntime: source.dsh ? label : null,
dsh: source.dsh ?? null,
agent: source.agent ?? null,
@@ -167,6 +203,12 @@ export function createAgentForker({
void watchNewPane(engine, pending, spawned, command, installIfMissing)
console.log(`[agent] fork pane open · ${engine} · ${plan.level} · ${source.agentId} → ${pending.agentId}`)
return { ok: true, session: pending, level: plan.level }
+ } }
+ }
+ const forkAgent: ForkAgent = async input => {
+ const label = buildHarnessSessionLabel(registry.byAgent(input.agentId)?.engine ?? 'terminal')
+ const prepared = await prepare(input, { id: label, label, current: () => true, hold: () => {} })
+ return prepared.ok ? prepared.dispatch() : prepared
}
- return forkAgent
+ return Object.assign(forkAgent, { prepare })
}
diff --git a/cli/src/core/agents/heldLaunches.spec.ts b/cli/src/core/agents/heldLaunches.spec.ts
index c8d1c7ecd..1f923fd03 100644
--- a/cli/src/core/agents/heldLaunches.spec.ts
+++ b/cli/src/core/agents/heldLaunches.spec.ts
@@ -1,9 +1,11 @@
import { execFileSync } from 'node:child_process'
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import type { AgentLaunch, RegisteredSession } from '../../lib/registry.js'
import { heldLaunch, type RestoreSummary } from '../../lib/restoreAgents.js'
import { createHeldLaunches, heldFor, heldPaneArgv } from './heldLaunches.js'
+const running: ReturnType<typeof createHeldLaunches>[] = []
+afterEach(() => { for (const held of running.splice(0)) held.close() })
const HELD = heldLaunch('models')
const row = (agentId: string, launch: AgentLaunch, over: Partial<RegisteredSession> = {}) =>
({ agentId, sessionId: `s-${agentId}`, launch, ...over }) as RegisteredSession
@@ -13,7 +15,7 @@ const summary = (over: Partial<RestoreSummary> = {}): RestoreSummary => ({ resto
function setup(rows: RegisteredSession[], answer: (only: ReadonlySet<string>) => RestoreSummary = (only) => summary({ restored: [...only] })) {
const registry = new Map(rows.map((r) => [r.agentId, r]))
const asked: string[][] = []
- const restore = vi.fn(async (only: ReadonlySet<string>) => {
+ const restore = vi.fn(async (only: ReadonlySet<string>, _current: () => boolean) => {
asked.push([...only])
const result = answer(only)
for (const id of result.restored) { const r = registry.get(id); if (r) r.launch = { state: 'starting' } }
@@ -21,10 +23,63 @@ function setup(rows: RegisteredSession[], answer: (only: ReadonlySet<string>) =>
})
const log = vi.fn()
const held = createHeldLaunches({ registry: { list: () => [...registry.values()], byAgent: (id: string) => registry.get(id) } as never, restore, log })
+ running.push(held)
return { registry, asked, restore, log, held }
}
describe('agents held until a service is ready', () => {
+ it.each(['removed', 'closed'] as const)('does not restore a queued row that was %s before its preparation', async state => {
+ const h = setup([row('a', HELD)])
+ await h.held.boot(async () => {})
+ if (state === 'removed') vi.spyOn(h.registry, 'get').mockReturnValueOnce(undefined)
+ const running = h.held.restoreHeld()
+ if (state === 'closed') queueMicrotask(() => h.held.close())
+ expect(await running).toMatchObject({ restored: [] })
+ expect(h.restore).not.toHaveBeenCalled()
+ })
+
+ it('revokes the boot and every active restore authority immediately on close', async () => {
+ const h = setup([row('a', HELD)])
+ let bootCurrent!: () => boolean, flightCurrent!: () => boolean, finish!: () => void
+ await h.held.boot(async current => { bootCurrent = current; expect(current()).toBe(true) })
+ const restore = vi.fn(async (_only: ReadonlySet<string>, current: () => boolean) => {
+ flightCurrent = current
+ expect(current()).toBe(true)
+ await new Promise<void>(done => { finish = done })
+ return summary()
+ })
+ h.restore.mockImplementation(restore)
+ const pending = h.held.restoreHeld()
+ await vi.waitFor(() => expect(restore).toHaveBeenCalledOnce())
+ h.held.close()
+ expect(bootCurrent()).toBe(false)
+ expect(flightCurrent()).toBe(false)
+ finish(); await pending
+ })
+
+ it('bounds actual preparation flights and lets a later ready agent progress after one slot settles', async () => {
+ vi.useFakeTimers()
+ try {
+ const h = setup(Array.from({ length: 5 }, (_, index) => row(String(index), HELD)))
+ const complete: Array<() => void> = []
+ h.restore.mockImplementation(only => new Promise(resolve => complete.push(() => {
+ for (const id of only) h.registry.get(id)!.launch = { state: 'starting' }
+ resolve(summary({ restored: [...only] }))
+ })))
+ await h.held.boot(async () => {})
+ const first = h.held.restoreHeld()
+ await vi.advanceTimersByTimeAsync(0)
+ expect(h.restore).toHaveBeenCalledTimes(4)
+ expect(await h.held.restartHeld('4')).toMatchObject({ error: 'SERVICE_UNAVAILABLE' })
+ complete.shift()!()
+ await vi.advanceTimersByTimeAsync(500)
+ expect(h.restore).toHaveBeenCalledTimes(5)
+ complete.splice(0).forEach(done => done())
+ await first
+ expect(h.registry.get('4')?.launch).toEqual({ state: 'starting' })
+ } finally { vi.useRealTimers() }
+ })
+
it('names the service a row is held for, and none for any other', () => {
expect(heldFor(row('a', HELD))).toBe('models')
expect(heldFor(row('a', { state: 'ready' }))).toBeNull()
@@ -106,19 +161,20 @@ describe('agents held until a service is ready', () => {
} finally { vi.useRealTimers() }
})
- it('runs one pass at a time, and a pass that fails does not stop the next', async () => {
+ it('joins a flight for the same agent, and a failed flight permits the next attempt', async () => {
let release!: () => void
const order: string[] = []
const { held, restore } = setup([row('a', HELD)])
restore.mockImplementationOnce(async () => { order.push('first'); await new Promise<void>((done) => { release = done }); throw new Error('models hung up') })
await held.boot(async () => {})
- const first = held.restoreHeld()
- const second = held.restoreHeld()
+ const first = held.restoreHeld().catch(error => error)
+ const second = held.restoreHeld().catch(error => error)
await vi.waitFor(() => expect(order).toEqual(['first']))
expect(restore).toHaveBeenCalledTimes(1)
release()
- await expect(first).rejects.toThrow('models hung up')
- expect(await second).toMatchObject({ restored: ['a'] })
+ expect((await first).message).toBe('models hung up')
+ expect((await second).message).toBe('models hung up')
+ expect(await held.restoreHeld()).toMatchObject({ restored: ['a'] })
})
describe("a person's restart of a held agent", () => {
@@ -190,3 +246,50 @@ describe('agents held until a service is ready', () => {
expect(asked).toEqual([['a']])
})
})
+
+
+it('restores a sibling while another native preparation is stalled', async () => {
+ const h = setup([row('a', heldLaunch('native')), row('b', heldLaunch('native'))])
+ let finish!: (result: RestoreSummary) => void
+ h.restore.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
+ await h.held.boot(async () => {})
+ const pass = h.held.restoreHeld()
+ await vi.waitFor(() => expect(h.registry.get('b')?.launch?.state).toBe('starting'))
+ expect(h.registry.get('a')?.launch?.state).toBe('held')
+ finish(summary({ held: ['a'] }))
+ expect(await pass).toMatchObject({ restored: ['b'], held: ['a'] })
+})
+
+it('retries a native hold without a service reconnect and stops scheduling at close', async () => {
+ vi.useFakeTimers()
+ try {
+ const h = setup([row('a', heldLaunch('native'))])
+ h.restore.mockResolvedValueOnce(summary({ held: ['a'] }))
+ await h.held.boot(async () => {})
+ await h.held.restoreHeld()
+ await vi.advanceTimersByTimeAsync(2_000)
+ expect(h.restore).toHaveBeenCalledTimes(2)
+ h.registry.get('a')!.launch = heldLaunch('native')
+ h.held.close()
+ expect(await h.held.restoreHeld()).toBeNull()
+ await vi.advanceTimersByTimeAsync(10_000)
+ expect(h.restore).toHaveBeenCalledTimes(2)
+ } finally { vi.useRealTimers() }
+})
+
+it('retries a held sibling while another agent’s observation has not settled', async () => {
+ vi.useFakeTimers()
+ try {
+ const h = setup([row('a', heldLaunch('native')), row('b', heldLaunch('native'))])
+ let finish!: (result: RestoreSummary) => void
+ h.restore.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
+ .mockResolvedValueOnce(summary({ held: ['b'] }))
+ await h.held.boot(async () => {})
+ const pass = h.held.restoreHeld()
+ await vi.advanceTimersByTimeAsync(2_001)
+ expect(h.registry.get('b')?.launch?.state).toBe('starting')
+ expect(h.restore.mock.calls.map(([only]) => [...only])).toEqual([['a'], ['b'], ['b']])
+ finish(summary({ held: ['a'] }))
+ await pass
+ } finally { vi.useRealTimers() }
+})
diff --git a/cli/src/core/agents/heldLaunches.ts b/cli/src/core/agents/heldLaunches.ts
index e246e4060..8c88c044a 100644
--- a/cli/src/core/agents/heldLaunches.ts
+++ b/cli/src/core/agents/heldLaunches.ts
@@ -4,14 +4,14 @@
* A launch that asks a service for its part (a grid's or a saved API's, from models) is never waited on before the
* core is ready: the boot's restore holds the agent in a pane that says what it waits for (lib/restoreAgents.ts
* `defer`), and the pass here launches it into that pane once the core is up. A service that cannot be asked then
- * keeps it held, and the rest of that pass after it unasked. Held is never failed and never retired: discovery sees
+ * keeps it held while sibling agents continue. Held is never failed and never retired: discovery sees
* its pane alive, and every later pass tries again. A pass runs:
*
* - once the core is ready, for every held agent;
* - each time a service connects (a restarted one too), for the agents held for it;
* - when a person restarts a held agent, for that one.
*
- * One pass at a time, in order, each after the boot's: two passes over one agent would launch it twice. An agent
+ * A separate flight for each agent, after the boot: two passes never dispatch the same agent twice. An agent
* the person stopped or closed meanwhile is no longer held, and is left alone.
*/
import { sid } from '../../lib/log.js'
@@ -26,7 +26,7 @@ export function heldFor(row: Pick<RegisteredSession, 'launch'> | undefined): str
export interface HeldLaunchesDeps {
registry: Pick<typeof registry, 'list' | 'byAgent'>
/** The boot's restore, of exactly these agents, outside the registry's transaction (lib/restoreAgents.ts `only`). */
- restore: (only: ReadonlySet<string>) => Promise<RestoreSummary>
+ restore: (only: ReadonlySet<string>, current: () => boolean) => Promise<RestoreSummary>
log: (line: string) => void
}
@@ -35,50 +35,87 @@ export type HeldRestart =
| { ok: false; error: string; detail?: string }
export function createHeldLaunches({ registry, restore, log }: HeldLaunchesDeps) {
- // Closed until the boot's restore has run: an agent held since the last daemon is that pass's to look at first.
let opened!: () => void
- let queue: Promise<unknown> = new Promise<void>((done) => { opened = done })
- /** One pass at a time, in the order asked: a pass that fails does not stop the next. */
- const serial = <T>(run: () => Promise<T>): Promise<T> => {
- const next = queue.then(run)
- queue = next.catch(() => {})
- return next
- }
-
+ const ready = new Promise<void>(done => { opened = done })
+ let closed = false
+ // Closing revokes preparations already waiting on hooks or a service, too.
+ const current = () => !closed
let retryTimer: ReturnType<typeof setTimeout> | undefined
+ const active = new Map<string, Promise<RestoreSummary>>()
+ let nextAgent = 0
+ const empty = (): RestoreSummary => ({ restored: [], skipped: [], failed: [], held: [], unsurveyed: [] })
const retryContention = (summary: RestoreSummary): void => {
- if (!summary.retry || retryTimer) return
+ if (closed || retryTimer || (!summary.retry && !summary.held.length)) return
retryTimer = setTimeout(() => {
retryTimer = undefined
- void restoreHeld().catch(error => log(`[restore] core contention retry failed: ${String(error)}`))
- }, 500)
+ void restoreHeld(undefined, false).catch(error => {
+ log(`[restore] core contention retry failed: ${String(error)}`)
+ retryContention({ ...empty(), retry: true })
+ })
+ }, summary.retry ? 500 : 2_000)
retryTimer.unref?.()
}
-
- /** The agents held (for `service`, or for any), launched now. */
- const restoreHeld = (service?: string): Promise<RestoreSummary | null> => serial(async () => {
- const held = new Set(registry.list().filter((row) => {
+ // One flight per agent, four across the core. A stalled native home or service
+ // cannot serialize every sibling behind it. Additional callers join the same
+ // observation; a later timer retries failures with fresh registry ownership.
+ const restoreOne = (agentId: string): Promise<RestoreSummary> => {
+ const existing = active.get(agentId)
+ if (existing) return existing
+ if (closed || !heldFor(registry.byAgent(agentId))) return Promise.resolve(empty())
+ if (active.size >= 4) {
+ const summary: RestoreSummary = { ...empty(), held: [agentId], retry: true }
+ retryContention(summary)
+ return Promise.resolve(summary)
+ }
+ const flight = Promise.resolve().then(() => closed ? empty() : restore(new Set([agentId]), current)).then(summary => {
+ active.delete(agentId)
+ retryContention(summary)
+ return summary
+ }, error => {
+ active.delete(agentId)
+ retryContention({ ...empty(), retry: true })
+ throw error
+ })
+ active.set(agentId, flight)
+ return flight
+ }
+ const restoreHeld = async (service?: string, joinRunning = true): Promise<RestoreSummary | null> => {
+ await ready
+ if (closed) return null
+ const held = registry.list().filter(row => {
const holder = heldFor(row)
- return holder !== null && (service === undefined || holder === service)
- }).map((row) => row.agentId))
- if (!held.size) return null
- const summary = await restore(held)
+ return holder !== null && (service === undefined || holder === service) && (joinRunning || !active.has(row.agentId))
+ }).map(row => row.agentId)
+ if (!held.length) return null
+ const offset = nextAgent % held.length
+ const ordered = [...held.slice(offset), ...held.slice(0, offset)]
+ nextAgent = (offset + 4) % held.length
+ const summary = empty()
+ const outcomes = await Promise.allSettled(ordered.map(restoreOne))
+ let failure: unknown, rejected = false
+ for (const outcome of outcomes) {
+ if (outcome.status === 'rejected') { failure = outcome.reason; rejected = true; summary.retry = true; continue }
+ const result = outcome.value
+ for (const key of ['restored', 'skipped', 'failed', 'held', 'unsurveyed'] as const) (summary[key] as unknown[]).push(...result[key])
+ if (result.retry) summary.retry = true
+ }
retryContention(summary)
- log(`[restore] held · ${service ?? 'every service'} · launched ${summary.restored.length} of ${held.size}`
+ if (rejected) throw failure
+ log(`[restore] held · ${service ?? 'every service'} · launched ${summary.restored.length} of ${held.length}`
+ (summary.held.length ? ` · ${summary.held.length} still waiting` : ''))
return summary
- })
+ }
/** A person's restart of a held agent: launched as a pass would, or why not. Null for an agent that is not held,
* which a restart handles as it always has. */
const restartHeld = (agentId: string): Promise<HeldRestart> | null => {
if (!heldFor(registry.byAgent(agentId))) return null
- return serial(async () => {
+ return ready.then(async () => {
// Asked again in turn: a pass before this one may have launched it, or the person closed it.
const before = registry.byAgent(agentId)
- if (!before) return { ok: false, error: 'AGENT_NOT_FOUND' }
+ if (!before || closed) return { ok: false, error: 'AGENT_NOT_FOUND' }
if (!heldFor(before)) return { ok: true, session: before, resumed: !!before.sessionId }
- const summary = await restore(new Set([agentId]))
+ const summary = await restoreOne(agentId)
retryContention(summary)
const now = registry.byAgent(agentId)
if (!now) return { ok: false, error: 'AGENT_NOT_FOUND' }
@@ -95,11 +132,12 @@ export function createHeldLaunches({ registry, restore, log }: HeldLaunchesDeps)
return {
/** The boot's restore, before any pass here: they wait for it, whether it restores, fails or has nothing to do. */
- boot: async <T>(run: () => Promise<T>): Promise<T> => {
- try { return await run() } finally { opened() }
+ boot: async <T>(run: (current: () => boolean) => Promise<T>): Promise<T> => {
+ try { return await run(current) } finally { opened() }
},
restoreHeld,
restartHeld,
+ close: () => { closed = true; clearTimeout(retryTimer); opened() },
}
}
diff --git a/cli/src/core/agents/launch.spec.ts b/cli/src/core/agents/launch.spec.ts
index 37b220f2d..29cd50361 100644
--- a/cli/src/core/agents/launch.spec.ts
+++ b/cli/src/core/agents/launch.spec.ts
@@ -38,6 +38,12 @@ function setup() {
describe('relaunch helpers', () => {
afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+ it('preserves an unknown native permission observation as a launch hold', async () => {
+ const { helpers } = setup()
+ vi.mocked(dropPermissionFlagIfUnsupported).mockResolvedValueOnce({ choice: { bypassPermission: false }, droppedFlag: null, nativeHold: 'Waiting for help.' })
+ expect(await helpers.downgradedPermission(session(), true, 'restore')).toEqual({ bypassPermission: false, nativeHold: 'Waiting for help.' })
+ })
+
it('rejects preparation that was already revoked before dispatch', async () => {
const { deps } = setup()
deps.authority = () => () => false
@@ -101,10 +107,10 @@ describe('relaunch helpers', () => {
expect(deps.prepareApiTools).toHaveBeenCalledWith('/work', 'claude')
expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({
dsh: 'blender', dshRuntime: null, cwd: '/work', agent: 'reviewer', gridLaunch: null,
- }), 'a1', expect.any(Function))
+ }), 'a1', expect.any(Function), undefined)
const grid = { networkId: 'grid-1', networkName: 'Home grid' }
await helpers.relaunchOverrides(session({ dsh: undefined, dshRuntime: undefined, agent: undefined } as Partial<RegisteredSession>), { gridLaunch: grid } as never)
- expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({ dsh: null, agent: null, gridLaunch: grid }), 'a1', expect.any(Function))
+ expect(buildLaunchOverrides).toHaveBeenLastCalledWith(deps.launchOverridesDeps, 'claude', expect.objectContaining({ dsh: null, agent: null, gridLaunch: grid }), 'a1', expect.any(Function), undefined)
})
it('records the web-search decision a relaunch made, when it made one', () => {
@@ -133,7 +139,7 @@ describe('relaunch helpers', () => {
const { helpers } = setup()
vi.mocked(dropPermissionFlagIfUnsupported).mockResolvedValueOnce({ choice: { bypassPermission: false }, droppedFlag: '--permission-mode' } as never)
expect(await helpers.downgradedPermission(session({ permissionMode: 'plan' } as Partial<RegisteredSession>), true, 'restart')).toEqual({ bypassPermission: false })
- expect(dropPermissionFlagIfUnsupported).toHaveBeenCalledWith('claude', { permissionMode: 'plan', bypassPermission: true })
+ expect(dropPermissionFlagIfUnsupported).toHaveBeenCalledWith('claude', { permissionMode: 'plan', bypassPermission: true }, undefined, undefined)
expect(String(warn.mock.calls[0][0])).toContain('does not take --permission-mode · starting in Ask · update claude to get plan back')
vi.mocked(dropPermissionFlagIfUnsupported).mockResolvedValueOnce({ choice: { bypassPermission: true }, droppedFlag: '--dangerously-skip-permissions' } as never)
await helpers.downgradedPermission(session(), true, 'retarget')
diff --git a/cli/src/core/agents/launch.ts b/cli/src/core/agents/launch.ts
index e84c9ff40..6d800fc87 100644
--- a/cli/src/core/agents/launch.ts
+++ b/cli/src/core/agents/launch.ts
@@ -1,3 +1,4 @@
+import type { NativeLaunch } from '../../engines/nativeLaunch.js'
/**
* Relaunch helpers: what a restart, a retarget, a restore or a resume needs to bring an agent's pane
* back. Its launch overrides, rebuilt from the row (an API's key as saved now); the web-search decision
@@ -47,13 +48,13 @@ export function createLaunchHelpers({ authority, prepareApiTools, launchOverride
// An agent on a saved API's model relaunches with that API's endpoint and key as saved now, so a key
// pasted since takes effect, and a removed API is refused rather than kept on its old key: the models
// service reads them as it builds the launch (`buildLaunchOverrides`, `refresh`).
- const relaunchOverrides = async (session: RegisteredSession, source: LaunchSource = session, operationCurrent: () => boolean = () => true): Promise<LaunchOverridesResult> => {
+ const relaunchOverrides = async (session: RegisteredSession, source: LaunchSource = session, operationCurrent: () => boolean = () => true, native?: NativeLaunch, configKey = session.agentId): Promise<LaunchOverridesResult> => {
const dispatchCurrent = authority(session.agentId)
const current = () => operationCurrent() && dispatchCurrent()
session = structuredClone(session)
const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during launch preparation.' } as const
if (!current()) return changed
- const result = await buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, ...source, gridLaunch: source.gridLaunch ?? null }, session.agentId, current)
+ const result = await buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, dshRuntime: session.dshRuntime ?? null, cwd: session.cwd, agent: session.agent ?? null, scmLaunch: session.scmLaunch ?? null, ...source, gridLaunch: source.gridLaunch ?? null }, configKey, current, native)
if (!current()) return changed
if (!result.ok && (result.unavailable || result.error === 'AGENT_CHANGED')) return result
// Saved-API instructions remain available after an ordinary semantic refusal, as before.
@@ -97,16 +98,17 @@ export function createLaunchHelpers({ authority, prepareApiTools, launchOverride
session: RegisteredSession,
bypassPermission: boolean,
what: string,
- ): Promise<{ permissionMode?: string | null; bypassPermission?: boolean }> => {
- const { choice, droppedFlag } = await dropPermissionFlagIfUnsupported(session.engine, {
+ native?: NativeLaunch,
+ ): Promise<{ permissionMode?: string | null; bypassPermission?: boolean; nativeHold?: string }> => {
+ const { choice, droppedFlag, nativeHold } = await dropPermissionFlagIfUnsupported(session.engine, {
permissionMode: session.permissionMode ?? null,
bypassPermission,
- })
+ }, undefined, native)
if (droppedFlag) {
console.warn(`[agent] ${what} ${sid(session.agentId)} · ${session.engine} does not take ${droppedFlag}`
+ ` · starting in Ask · update ${session.engine} to get ${session.permissionMode ?? 'Auto'} back`)
}
- return choice
+ return { ...choice, ...(nativeHold ? { nativeHold } : {}) }
}
const prepareSessionResume = (session: RegisteredSession): void => {
diff --git a/cli/src/core/agents/launchAuthority.ts b/cli/src/core/agents/launchAuthority.ts
index 7f1fc2ff0..3e7014dd7 100644
--- a/cli/src/core/agents/launchAuthority.ts
+++ b/cli/src/core/agents/launchAuthority.ts
@@ -14,10 +14,10 @@ export function createLaunchAuthority(deps: {
revision(id: string): number
cancelled(id: string): boolean
}) {
- return (id: string): (() => boolean) => {
+ return (id: string, expected?: RegisteredSession): (() => boolean) => {
// The requested launch may be a stopped row or a projected terminal fallback. Its owner's
// predicate grants that operation; this extra fence watches the live table as dispatch found it.
- const target = identity(deps.byAgent(id)), revision = deps.revision(id)
+ const target = identity(expected ?? deps.byAgent(id)), revision = deps.revision(id)
return () => !deps.cancelled(id) && deps.revision(id) === revision && identity(deps.byAgent(id)) === target
}
}
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index 8feccfc5f..1c2662eda 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -14,6 +14,7 @@ import { parseNewAgentModel } from '../../lib/newAgentModel.js'
import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from '../../lib/projectFolder.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { createLaunchRequests, type CreateAgent, type ForkAgent, type LaunchRequestDeps, type RestartAgent, type ResumeAgent } from './launches.js'
+import * as pendingLaunches from './pendingLaunches.js'
/**
* The requests that start an agent's process, answered by the core: every refusal before a pane exists,
@@ -102,6 +103,108 @@ function setup(over: Partial<LaunchRequestDeps> = {}, launches: { create?: Creat
}
describe('agent_create, refused before any pane exists', () => {
+ it('keeps a selected model pending before native preparation, then dispatches its fresh resolution once', async () => {
+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'fixture-model', grid: 'fixture-grid' } })
+ const grid = { networkId: 'fixture', networkName: 'Fixture', baseUrl: 'http://fixture.invalid', apiKey: 'fixture' }
+ resolveNewAgentModel.mockResolvedValueOnce(null).mockResolvedValue(grid)
+ 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 run = setup({ prepareCreate })
+ const input = { creationId: CREATION, engine: 'claude', cwd: '/fixture/work', prompt: 'original prompt' }
+ await run.ask(input)
+ await vi.waitFor(() => expect(run.replies[0]).toMatchObject({ state: 'pending', held: { service: 'models' } }))
+ expect(prepareCreate).not.toHaveBeenCalled()
+ await run.ask(input)
+ await vi.waitFor(() => expect(run.replies[1]).toMatchObject({ state: 'created' }))
+ expect(prepareCreate).toHaveBeenCalledWith(expect.objectContaining({ grid, prompt: 'original prompt' }), expect.any(Object), { local: true })
+ expect(dispatch).toHaveBeenCalledOnce()
+ })
+
+ it('names models when its selected-model request rejects before native preparation', async () => {
+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'fixture-model', grid: 'fixture-grid' } })
+ const prepareCreate = vi.fn()
+ const run = setup({ prepareCreate, modelTarget: async () => { throw Error('models disconnected') } })
+ await run.ask({ creationId: CREATION, engine: 'claude', cwd: '/fixture/work' })
+ await vi.waitFor(() => expect(run.replies[0]).toMatchObject({ state: 'pending', held: { service: 'models' } }))
+ expect(prepareCreate).not.toHaveBeenCalled()
+ })
+
+ it.each(['model', 'native'] as const)('retains durable cancellation while %s preparation settles', async phase => {
+ vi.mocked(parseNewAgentModel).mockReturnValue({ state: 'ok', selection: { model: 'fixture-model', grid: 'fixture-grid' } })
+ const dispatch = vi.fn(async () => ({ ok: true as const, session: session('new-agent') }))
+ const run = setup({
+ modelTarget: async () => {
+ if (phase === 'model') run.deps.receipts.cancelIntent(CREATION)
+ return { networkId: 'fixture', networkName: 'Fixture', baseUrl: 'http://fixture.invalid', apiKey: 'fixture' }
+ },
+ prepareCreate: async () => {
+ run.deps.receipts.cancelIntent(CREATION)
+ return { ok: true, dispatch }
+ },
+ })
+ await run.ask({ creationId: CREATION, engine: 'claude', cwd: '/fixture/work' })
+ await vi.waitFor(() => expect(run.replies[0]).toMatchObject({ state: 'cancelled' }))
+ expect(dispatch).not.toHaveBeenCalled()
+ })
+
+ it.each(['refused', 'bare refusal', 'held', 'uncertain dispatch'] as const)('records native preparation outcomes truthfully: %s', async outcome => {
+ const dispatch = vi.fn(async () => ({ ok: false as const, error: 'SPAWN_FAILED' }))
+ const run = setup({ prepareCreate: async () => outcome === 'uncertain dispatch' ? { ok: true, dispatch }
+ : outcome === 'held' ? { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native' }
+ : { ok: false, error: 'PERMISSION_MODE_UNSUPPORTED', ...(outcome === 'refused' ? { detail: 'Unsupported fixture mode.' } : {}) } })
+ const payload = { creationId: CREATION, engine: 'claude', cwd: '/fixture/work' }
+ await run.ask(payload)
+ await vi.waitFor(() => expect(run.replies).toHaveLength(1))
+ expect(run.replies[0]).toMatchObject(outcome === 'held' ? { state: 'pending', held: { service: 'native', detail: 'Waiting for launch preparation.' } }
+ : outcome === 'uncertain dispatch' ? { state: 'unconfirmed' } : { state: 'failed', failure: { code: 'PERMISSION_MODE_UNSUPPORTED' } })
+ await run.ask(payload)
+ await vi.waitFor(() => expect(run.replies).toHaveLength(2))
+ expect(dispatch).toHaveBeenCalledTimes(outcome === 'uncertain dispatch' ? 1 : 0)
+ })
+
+ it('fences a prepared native dispatch if receipt authority changes before invocation', 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) })
+ const dispatch = vi.fn(async () => ({ ok: true as const, session: session('new-agent') }))
+ setup({ prepareCreate: async () => ({ ok: true, dispatch }) })
+ let current = true
+ const ready = await prepare({ kind: 'native-create-v1', input: { engine: 'claude', cwd: '/fixture/work' },
+ label: 'harness-claude-fixture', local: false }, { id: CREATION, current: () => current, hold: vi.fn() })
+ expect(ready).not.toBeNull()
+ current = false
+ expect(await ready!()).toEqual({ state: 'unconfirmed' })
+ expect(dispatch).not.toHaveBeenCalled()
+ expect(preTrustClaudeProject).not.toHaveBeenCalled()
+ })
+
+ it('recovers native and later service holds with the same request label and original authority', async () => {
+ const dispatch = vi.fn(async () => ({ ok: true as const, session: session('new-agent') }))
+ const prepareCreate = vi.fn<NonNullable<LaunchRequestDeps['prepareCreate']>>().mockResolvedValueOnce({ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting for installation.' })
+ .mockResolvedValueOnce({ ok: false, error: 'GRID_UNAVAILABLE', unavailable: 'models', detail: 'Waiting for models.' })
+ .mockImplementation(async (_input, authority) => ({ ok: true, dispatch: async () => { expect(authority.current()).toBe(true); return dispatch() } }))
+ const first = setup({ prepareCreate })
+ const input = { creationId: CREATION, engine: 'codex', cwd: '/fixture/work', codexHome: '/fixture/profile', prompt: 'fixture first prompt' }
+ await first.ask(input, false)
+ await vi.waitFor(() => expect(first.replies[0]).toMatchObject({ state: 'pending', held: { service: 'native' } }))
+ const label = prepareCreate.mock.calls[0]![1].label
+ const saved = first.deps.receipts.pendingIntent(CREATION)!
+ expect(saved.request).toMatchObject({ local: false, label, input: { prompt: 'fixture first prompt', codexHome: '/fixture/profile' } })
+ first.requests.stop()
+ const second = setup({ prepareCreate, receipts: first.deps.receipts })
+ await second.ask(input, true)
+ await vi.waitFor(() => expect(second.replies[0]).toMatchObject({ state: 'pending', held: { service: 'models' } }))
+ await second.ask(input, true)
+ await vi.waitFor(() => expect(dispatch).toHaveBeenCalledOnce())
+ expect(prepareCreate.mock.calls.every(([, authority]) => authority.label === label && authority.id === CREATION)).toBe(true)
+ expect(first.create).not.toHaveBeenCalled()
+ expect(second.create).not.toHaveBeenCalled()
+ expect(first.deps.receipts.status(CREATION)).toEqual({ state: 'created', agentId: 'new-agent' })
+ expect(preTrustCodexProject).not.toHaveBeenCalled()
+ await second.ask(input)
+ await settle()
+ expect(dispatch).toHaveBeenCalledOnce()
+ })
it('an engine it does not know, a folder it cannot read, or a cwd that is not an absolute path', async () => {
const { ask, create } = setup()
expect(await ask({ cwd: '/w' })).toStrictEqual({ error: 'INVALID_ENGINE' })
@@ -524,8 +627,10 @@ describe('durable model request validation', () => {
})
it('holds unfamiliar or incomplete saved intent without preparing a project or dispatching', async () => {
- const { deps, requests, create } = setup()
- const records = [{ kind: 'future-kind' }, { kind: 'model-create-v1', local: true, input: {}, selection: {} }]
+ 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' }]
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)
@@ -537,6 +642,7 @@ describe('durable model request validation', () => {
expect(resolveNewAgentModel).not.toHaveBeenCalled()
expect(prepareProjectFolder).not.toHaveBeenCalled()
expect(create).not.toHaveBeenCalled()
+ expect(prepareCreate).not.toHaveBeenCalled()
})
it('holds recovery while no local creator is available', async () => {
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index 5e2539f7f..7b4c88c96 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -29,6 +29,8 @@ import { parseNewAgentModel, type NewAgentModel } from '../../lib/newAgentModel.
import { parseProjectFolder, prepareProjectFolder, projectsRoot, ProjectFolderError, type ProjectFolder } from '../../lib/projectFolder.js'
import type { ScmLaunchRecord } from '../../scm/types.js'
import type { RegisteredSession } from '../../lib/registry.js'
+import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'
+import type { LaunchAuthority, LaunchPreparation } from '../../lib/launchPreparation.js'
import { createPendingLaunches } from './pendingLaunches.js'
/** Creates an agent (core/agents/create.ts). The orchestrator creates through the same one. */
@@ -52,6 +54,7 @@ export interface LaunchRequestDeps {
receipts: Pick<AgentCreationReceipts, 'run' | 'status' | 'has' | 'runIntent' | 'pendingIntents' | 'pendingIntent' | 'cancelIntent'>
/** Each launch, read when a request comes in: null on a machine that cannot launch agents. */
createAgent: () => CreateAgent | null
+ prepareCreate?: (input: Parameters<CreateAgent>[0], authority: LaunchAuthority, context?: { local: boolean }) => Promise<LaunchPreparation<Awaited<ReturnType<CreateAgent>>>>
forkAgent: () => ForkAgent | null
resumeAgent: () => ResumeAgent | null
restartAgent: () => RestartAgent | null
@@ -66,7 +69,7 @@ export interface LaunchRequestDeps {
type Reply = (result: Record<string, unknown>) => void
-export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget }: LaunchRequestDeps) {
+export function createLaunchRequests({ receipts, createAgent, prepareCreate, forkAgent, resumeAgent, restartAgent, byAgent, toProject, modelTarget }: LaunchRequestDeps) {
type CreateInput = Parameters<CreateAgent>[0]
const validateInstalled = async (input: CreateInput, known?: ReturnType<typeof installedDsh>): Promise<{ error: string; detail: string } | null> => {
if (input.dsh) {
@@ -139,7 +142,38 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeA
}
const modelHold = { service: 'models', detail: 'Waiting for the selected model. This request is saved and will continue when it is available.' }
- const pending = createPendingLaunches({ receipts, prepare: async saved => {
+ const launchHold = { service: 'launch', detail: 'Waiting for launch preparation. This request is saved and will continue when its dependencies are available.' }
+ const pending = createPendingLaunches({ receipts, prepare: async (saved, authority) => {
+ if (saved.kind === 'native-create-v1') {
+ if (!prepareCreate || typeof saved.local !== 'boolean' || !saved.input || typeof saved.input !== 'object'
+ || typeof saved.label !== 'string' || !/^harness-[a-z0-9-]+$/.test(saved.label)) return null
+ const input = structuredClone(saved.input) as CreateInput
+ if (!ENGINES.includes(input.engine) || typeof input.cwd !== 'string' || input.resumeSessionId) return null
+ if (saved.selection) {
+ authority.hold(modelHold)
+ const target = await modelTarget(saved.selection as NewAgentModel)
+ if (!authority.current()) return null
+ if (!target) { authority.hold(modelHold); return null }
+ input.grid = target
+ authority.hold(launchHold)
+ }
+ const ready = await prepareCreate(input, { ...authority, label: saved.label }, { local: saved.local })
+ if (!authority.current()) return null
+ if (!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) } : {}) })
+ }
+ return async () => {
+ if (!authority.current()) return { state: 'unconfirmed' }
+ // All preparation, including local workspace trust, precedes the claim.
+ // A trust write here would invalidate Codex's final config proof.
+ const result = await ready.dispatch()
+ if (result.ok) return { state: 'created', agentId: result.session.agentId }
+ // Dispatch's outcome is uncertain once its exclusive claim is durable.
+ // In particular, a stale guard must never reopen that claim for replay.
+ return { state: 'unconfirmed' }
+ }
+ }
// A future intent kind cannot be interpreted as this one. Keep unknown or
// damaged requests held instead of guessing at their launch choices.
if (saved.kind !== 'model-create-v1' || typeof saved.local !== 'boolean'
@@ -325,11 +359,15 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeA
const create = onCreateAgent
try {
const fingerprint = creationFingerprint(projectFolder ? { ...fingerprintInput, projectFolder } : fingerprintInput)
- if (model.state !== 'ok' && !receipts.has(creationId, fingerprint)) {
+ const durableNative = !!prepareCreate && !projectFolder && !resumeSessionId
+ if (!durableNative && model.state !== 'ok' && !receipts.has(creationId, fingerprint)) {
const refusal = await validateInstalled(input, installed)
if (refusal) { reply(refusal); return }
}
- const operation = model.state === 'ok'
+ const operation = durableNative
+ ? pending.start(creationId, fingerprint, { kind: 'native-create-v1', input,
+ 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)
: receipts.run(creationId, fingerprint, () => executeCreate(input, projectFolder, asker.local, create, true))
void operation.then(async (status) => {
diff --git a/cli/src/core/agents/nativeCreate.spec.ts b/cli/src/core/agents/nativeCreate.spec.ts
new file mode 100644
index 000000000..a5ee5cefd
--- /dev/null
+++ b/cli/src/core/agents/nativeCreate.spec.ts
@@ -0,0 +1,81 @@
+/** The real receipt → create → native hook proof → trust composition, with no real pane. */
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { CreateAgentDeps } from './create.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+
+const spawn = vi.hoisted(() => vi.fn())
+vi.mock('../../lib/createAgentPane.js', () => ({ createAndRegisterPane: spawn }))
+let root: string
+let stop: (() => void) | undefined
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'native-create-composition-'))
+ for (const key of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'HARNESS_AUTH_DIR', 'HARNESS_HOOK_ROUTES_DIR', 'CODEX_HOME']) {
+ const value = join(root, key.toLowerCase())
+ mkdirSync(value, { recursive: true }); vi.stubEnv(key, value)
+ }
+ for (const key of ['XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'ZDOTDIR', 'CODEX_PATH', 'CLAUDE_CONFIG_DIR', 'HARNESS_OS']) vi.stubEnv(key, '')
+ const bin = join(root, 'bin'); mkdirSync(bin)
+ writeFileSync(join(bin, 'codex'), '#!/bin/sh\nif [ "$1" = --version ]; then printf "codex-cli 0.160.0\\n"; else printf "%s\\n" "--no-daemon --approve-for-me"; fi\n', { mode: 0o700 })
+ vi.stubEnv('SHELL', '/bin/sh'); vi.stubEnv('PATH', bin)
+ writeFileSync(join(process.env.CODEX_HOME!, 'config.toml'), 'model_provider = "openai"\n')
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.resetModules(); spawn.mockReset()
+})
+afterEach(() => {
+ stop?.(); stop = undefined
+ vi.restoreAllMocks(); vi.unstubAllEnvs()
+ rmSync(root, { recursive: true, force: true })
+})
+
+it('records Claude trust at its captured shell home when that shell omitted CLAUDE_CONFIG_DIR', async () => {
+ const { folderTrust } = await import('../../engines/launchPrep.js')
+ const selected = join(root, 'selected-home'); mkdirSync(selected)
+ const config = join(selected, '.claude.json'); writeFileSync(config, '{}\n')
+ const ambient = join(process.env.HOME!, '.claude.json'); writeFileSync(ambient, '{}\n')
+ expect(folderTrust('claude', null, { HOME: selected })!.record('/fixture/work')).toBe('trusted')
+ expect(JSON.parse(readFileSync(config, 'utf8')).projects['/fixture/work'].hasTrustDialogAccepted).toBe(true)
+ expect(readFileSync(ambient, 'utf8')).toBe('{}\n')
+})
+
+it.each([true, false])('completes native Codex preparation before its dispatch claim with saved local authority %s', async local => {
+ const { createAgentCreator } = await import('./create.js')
+ const { createLaunchRequests } = await import('./launches.js')
+ const { AgentCreationReceipts } = await import('../../lib/agentCreationReceipt.js')
+ const { inspectNativeLaunch } = await import('../../engines/nativeLaunch.js')
+ const { projectsRoot } = await import('../../lib/projectFolder.js')
+ const cwd = join(projectsRoot(), 'workspace'); mkdirSync(cwd, { recursive: true })
+ const config = join(process.env.CODEX_HOME!, 'config.toml')
+ const pending = { agentId: 'fixture-agent', engine: 'codex', cwd, sessionId: '', runtimes: [] } as unknown as RegisteredSession
+ spawn.mockImplementation(async (options: { current(): boolean; argv: string[] }) => {
+ expect(options.current()).toBe(true)
+ expect(readFileSync(config, 'utf8').includes('trust_level = "trusted"')).toBe(local)
+ expect(options.argv.join(' ')).toContain('original prompt')
+ return { ok: true, pending, spawned: { runtime: { backend: 'tmux', paneId: '%fixture' } } }
+ })
+ const creator = createAgentCreator({ native: (engine, source) => inspectNativeLaunch(engine, source),
+ tmuxBackend: {} as CreateAgentDeps['tmuxBackend'], registry: {} as CreateAgentDeps['registry'],
+ externalResume: async () => { throw Error('unexpected external resume') }, watchNewPane: async () => {},
+ announceSession: () => {}, attachDsh: () => {}, prepareApiTools: () => {},
+ hookPort: 19473, hooksDisabled: false, installOpencodePlugin: async () => true,
+ gridLaunchMachine: () => ({}) as never, buildGridLaunch: async () => { throw Error('unexpected grid') },
+ terminalHintMachineName: () => 'Fixture', blocksFolder: () => false, gridSetup: () => null, privateGridName: async () => null,
+ dshLaunch: { launch: async () => { throw Error('unexpected DSH') }, materialize: async () => { throw Error('unexpected DSH') } },
+ })
+ const receipts = new AgentCreationReceipts(join(root, 'receipts'))
+ const requests = createLaunchRequests({ receipts, createAgent: () => creator, prepareCreate: creator.prepare,
+ forkAgent: () => null, resumeAgent: () => null, restartAgent: () => null,
+ byAgent: () => pending, toProject: async () => ({ agentId: pending.agentId }) as never, modelTarget: async () => null })
+ stop = requests.stop
+ const replies: Record<string, unknown>[] = []
+ const input = { creationId: 'native_trust_fixture_1', engine: 'codex', cwd, bypassPermission: false, prompt: 'original prompt' }
+ await requests.create(input, { local }, result => { replies.push(result) })
+ await vi.waitFor(() => expect(replies[0]).toMatchObject({ state: 'created' }), { timeout: 10_000 })
+ expect(spawn).toHaveBeenCalledOnce()
+ await requests.create(input, { local: !local }, result => { replies.push(result) })
+ await vi.waitFor(() => expect(replies[1]).toMatchObject({ state: 'created' }))
+ expect(spawn).toHaveBeenCalledOnce()
+ expect(readFileSync(config, 'utf8').includes('trust_level = "trusted"')).toBe(local)
+}, 20_000)
diff --git a/cli/src/core/agents/newPane.spec.ts b/cli/src/core/agents/newPane.spec.ts
index 8ba270839..6aaf132b3 100644
--- a/cli/src/core/agents/newPane.spec.ts
+++ b/cli/src/core/agents/newPane.spec.ts
@@ -12,7 +12,7 @@ vi.mock('../../lib/tmux.js', async (real) => ({
}))
vi.mock('../../lib/engineLaunch.js', async (real) => ({ ...await real<object>(), commandAvailableInInteractiveShell: vi.fn(async () => true) }))
-const pending = { agentId: 'a1', sessionId: '', engine: 'claude' } as RegisteredSession
+const pending = { agentId: 'a1', sessionId: '', engine: 'claude', runtimes: [{ backend: 'tmux', paneId: '%7' }] } as RegisteredSession
const runtime = { backend: 'tmux', paneId: '%7' }
const spawned = { runtime } as never
const identity = { pid: 99, startMarker: 'now' }
@@ -37,6 +37,23 @@ function setup(over: Partial<PaneWatcherDeps> = {}) {
}
describe('watching a new pane', () => {
+ it.each(['held', 'row removed', 'not held', 'unknown', 'no probe'] as const)('retains a post-rc native guard hold without failing or archiving: %s', async result => {
+ const entry = { ...pending, launch: { state: 'starting', nativeToken: 'fixture-native' } } as RegisteredSession
+ const waitingPane = vi.fn(async () => result === 'unknown' ? 'unknown' as const : result === 'held' || result === 'row removed')
+ const { deps, rows, watch } = setup(result === 'no probe' ? {} : { waitingPane })
+ rows.set('a1', entry)
+ if (result === 'row removed') vi.mocked(deps.registry.setLaunch).mockReturnValue(null)
+ const watching = watch('claude', entry, spawned, ['claude'], undefined, 1)
+ await vi.advanceTimersByTimeAsync(50)
+ await watching
+ expect(deps.retainExitedSession).not.toHaveBeenCalled()
+ expect(deps.registry.releaseEngine).not.toHaveBeenCalled()
+ if (result === 'held' || result === 'row removed') {
+ expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', expect.objectContaining({ state: 'held', service: 'native', nativeToken: 'fixture-native' }))
+ expect(deps.announceSession).toHaveBeenCalledTimes(result === 'held' ? 1 : 0)
+ } else expect(deps.registry.setLaunch).toHaveBeenCalledWith('a1', expect.objectContaining({ state: 'held', service: 'native', nativeToken: 'fixture-native' }))
+ })
+
beforeEach(() => {
vi.useFakeTimers()
vi.spyOn(console, 'log').mockImplementation(() => {})
@@ -48,6 +65,58 @@ describe('watching a new pane', () => {
})
afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
+ it.each(['token', 'route', 'binding', 'removed', 'stopped', 'ready'] as const)('discards a delayed native hold after its %s changes', async change => {
+ const entry = { ...pending, launch: { state: 'starting', nativeToken: 'original' } } as RegisteredSession
+ let finish!: (waiting: true) => void
+ const waitingPane = vi.fn(() => new Promise<true>(done => { finish = done }))
+ const { deps, rows, watch } = setup({ waitingPane })
+ rows.set('a1', entry)
+ const watching = watch('claude', entry, spawned, ['claude'], undefined)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(waitingPane).toHaveBeenCalledOnce()
+ const replacement = structuredClone(entry)
+ if (change === 'token') replacement.launch = { state: 'starting', nativeToken: 'replacement' }
+ if (change === 'route') replacement.runtimes = [{ backend: 'tmux', paneId: '%8' }]
+ if (change === 'binding') replacement.sessionId = 'new-conversation'
+ if (change === 'stopped') replacement.active = false
+ if (change === 'ready') replacement.launch = { state: 'ready' }
+ if (change === 'removed') rows.delete('a1'); else rows.set('a1', replacement)
+ finish(true)
+ await watching
+ expect(deps.registry.setLaunch).not.toHaveBeenCalled()
+ expect(deps.announceSession).not.toHaveBeenCalled()
+ expect(rows.get('a1')).toEqual(change === 'removed' ? undefined : replacement)
+ })
+
+ it.each(['before probe', 'process', 'state', 'installed', 'capture', 'clear', 'sleep'] as const)(
+ 'fences native watcher effects when superseded at %s', async stage => {
+ const entry = { ...pending, launch: { state: 'starting', nativeToken: 'original' } } as RegisteredSession
+ const { deps, rows, watch } = setup()
+ rows.set('a1', entry)
+ const replace = () => rows.set('a1', { ...entry, launch: { state: 'starting', nativeToken: 'replacement' } })
+ if (stage === 'before probe') replace()
+ if (stage === 'process') vi.mocked(resolvePaneEngineProcess).mockImplementationOnce(async () => { replace(); return identity as never })
+ if (stage === 'state') vi.mocked(tmuxPaneState).mockImplementationOnce(async () => { replace(); return 'gone' })
+ if (stage === 'installed') {
+ vi.mocked(tmuxPaneState).mockResolvedValueOnce({ dead: true, engineExit: null } as never)
+ vi.mocked(commandAvailableInInteractiveShell).mockImplementationOnce(async () => { replace(); return false })
+ }
+ if (stage === 'capture' || stage === 'clear') {
+ vi.mocked(tmuxPaneState).mockResolvedValueOnce({ dead: false, engineExit: 2 } as never)
+ if (stage === 'capture') vi.mocked(deps.captureTerminal).mockImplementationOnce(async () => { replace(); return 'old exit' })
+ else vi.mocked(clearPaneRemainOnExit).mockImplementationOnce(async () => { replace() })
+ }
+ const watching = watch('claude', entry, spawned, ['claude'], undefined, 1)
+ await vi.advanceTimersByTimeAsync(0)
+ if (stage === 'sleep') replace()
+ await vi.advanceTimersByTimeAsync(50)
+ await watching
+ expect(deps.registry.setLaunch).not.toHaveBeenCalled()
+ expect(deps.registry.updateProcessIdentity).not.toHaveBeenCalled()
+ expect(deps.registry.releaseEngine).not.toHaveBeenCalled()
+ expect(deps.retainExitedSession).not.toHaveBeenCalled()
+ })
+
it('marks the agent ready once its engine process shows up, and asks discovery to bind it', async () => {
const { deps, watch } = setup()
vi.mocked(resolvePaneEngineProcess).mockResolvedValueOnce(null).mockResolvedValueOnce(identity as never)
@@ -127,7 +196,7 @@ describe('watching a new pane', () => {
await watch('claude', pending, spawned, ['claude'], undefined)
expect(deps.registry.releaseEngine).toHaveBeenCalledWith('a1')
expect(deps.announceSession).toHaveBeenCalledWith(expect.objectContaining({ engine: 'terminal' }))
- expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%7')
+ expect(clearPaneRemainOnExit).toHaveBeenCalledWith('%7', expect.any(Function))
expect(warn.mock.calls.map(([line]) => String(line)).some((line) => line.includes('exited (2) before ready · agent a1 kept as a terminal'))).toBe(true)
// A hook bound a conversation meanwhile: that conversation is kept, the engine not released.
rows.set('a1', { ...pending, sessionId: 's1' } as RegisteredSession)
diff --git a/cli/src/core/agents/newPane.ts b/cli/src/core/agents/newPane.ts
index 4891e187a..c01890fcc 100644
--- a/cli/src/core/agents/newPane.ts
+++ b/cli/src/core/agents/newPane.ts
@@ -14,6 +14,7 @@ import { sid } from '../../lib/log.js'
import type { registry, RegisteredSession } from '../../lib/registry.js'
import type { TerminalRuntimeRef, TmuxRuntimeRef } from '../../lib/terminalTypes.js'
import { clearPaneRemainOnExit, resolvePaneEngineProcess, tmuxPaneState } from '../../lib/tmux.js'
+import { createLaunchAuthority } from './launchAuthority.js'
export interface PaneWatcherDeps {
registry: Pick<typeof registry, 'byAgent' | 'updateProcessIdentity' | 'setLaunch' | 'setTerminalAvailable' | 'releaseEngine'>
@@ -21,6 +22,7 @@ export interface PaneWatcherDeps {
/** Ask the reconciler to bind what now runs in a pane (TerminalAgentReconciler.triggerHint). */
triggerHint: (runtime: TerminalRuntimeRef, engine: AgentEngine) => Promise<void>
captureTerminal: (target: string, historyLines?: number) => Promise<string | null>
+ waitingPane?: (runtime: TmuxRuntimeRef, token: string) => Promise<boolean | 'unknown'>
retainExitedSession: (session: RegisteredSession, announce: boolean) => void
}
@@ -29,7 +31,7 @@ const sleep = (ms: number): Promise<void> => new Promise((resolve) => {
timer.unref?.()
})
-export function createPaneWatcher({ registry, announceSession, triggerHint, captureTerminal, retainExitedSession }: PaneWatcherDeps) {
+export function createPaneWatcher({ registry, announceSession, triggerHint, captureTerminal, retainExitedSession, waitingPane }: PaneWatcherDeps) {
/**
* Watch a pane this daemon just opened until its engine process shows up (ready), dies (failed), or
* ten minutes pass. Shared by create and fork: the two open panes the same way and wait the same way.
@@ -37,10 +39,16 @@ export function createPaneWatcher({ registry, announceSession, triggerHint, capt
const watchNewPane = async (engine: AgentEngine, pending: RegisteredSession, spawned: { runtime: TmuxRuntimeRef }, command: string[], installIfMissing: ReturnType<typeof engineInstallRecipe> | undefined, budgetMs = 10 * 60_000): Promise<void> => {
const startedAt = Date.now()
let delayMs = 50
+ const nativeToken = pending.launch?.state === 'starting' ? pending.launch.nativeToken : undefined
+ // A delayed probe belongs to this launch, including its original route and
+ // binding. Stop, a newer launch or discovery can supersede it while tmux waits.
+ const current = nativeToken ? createLaunchAuthority({ byAgent: id => registry.byAgent(id),
+ revision: () => 0, cancelled: () => false })(pending.agentId, pending) : () => true
try {
while (Date.now() - startedAt < budgetMs) {
- if (!registry.byAgent(pending.agentId)) return
+ if (!registry.byAgent(pending.agentId) || !current()) return
const processIdentity = await resolvePaneEngineProcess(spawned.runtime.paneId, engine)
+ if (!current()) return
if (processIdentity) {
registry.updateProcessIdentity(pending.agentId, processIdentity)
const ready = registry.setLaunch(pending.agentId, { state: 'ready' })
@@ -53,6 +61,7 @@ export function createPaneWatcher({ registry, announceSession, triggerHint, capt
return
}
const paneState = await tmuxPaneState(spawned.runtime.paneId)
+ if (!current()) return
if (paneState === 'gone') {
registry.setTerminalAvailable(pending.agentId, false)
announceSession(pending)
@@ -65,8 +74,17 @@ export function createPaneWatcher({ registry, announceSession, triggerHint, capt
delayMs = Math.min(delayMs * 2, 750)
continue
}
+ const waiting = nativeToken && await waitingPane?.(spawned.runtime, nativeToken)
+ if (!current()) return
+ if (waiting === true) {
+ const held = registry.setLaunch(pending.agentId, { state: 'held', service: 'native', nativeToken,
+ detail: 'The engine did not start because its executable or native hooks changed. The original launch is held for recovery.' })
+ if (held) announceSession(held)
+ return
+ }
if (paneState.dead) {
const installed = await commandAvailableInInteractiveShell(command[0], undefined, installIfMissing)
+ if (!current()) return
const error = installed ? 'ENGINE_DID_NOT_START' : 'ENGINE_NOT_INSTALLED'
const detail = installed
? `${engine} exited before its engine process became ready. See the terminal output for details.`
@@ -92,6 +110,7 @@ export function createPaneWatcher({ registry, announceSession, triggerHint, capt
// the pane is alive and about to become a terminal. That is the sentence this state
// selects ("started and exited with status N"), and it is the true one here.
const captured = await captureTerminal(pending.agentId, 40)
+ if (!current()) return
console.warn(`[agent] create · ${engine} · agent ${sid(pending.agentId)} · `
+ describeAgentCreateFailure({
state: { dead: true, exitStatus: paneState.engineExit, command: engine },
@@ -101,7 +120,8 @@ export function createPaneWatcher({ registry, announceSession, triggerHint, capt
processes: [],
elapsedMs: Date.now() - startedAt,
}))
- await clearPaneRemainOnExit(spawned.runtime.paneId)
+ await clearPaneRemainOnExit(spawned.runtime.paneId, current)
+ if (!current()) return
// A hook may have bound a conversation while this watcher was awaiting its probe.
// Archive the current row, not the pre-hook pending snapshot.
const row = registry.byAgent(pending.agentId)
@@ -116,8 +136,11 @@ export function createPaneWatcher({ registry, announceSession, triggerHint, capt
await sleep(delayMs)
delayMs = Math.min(delayMs * 2, 750)
}
+ if (!current()) return
const detail = `${engine} did not expose an engine process within ${Math.round(budgetMs / 60_000)} minutes. The terminal remains available.`
- const failed = registry.setLaunch(pending.agentId, { state: 'failed', error: 'START_TIMEOUT', detail })
+ const failed = registry.setLaunch(pending.agentId, nativeToken
+ ? { state: 'held', service: 'native', nativeToken, detail: 'Waiting to confirm the native engine process. The original launch and terminal are preserved.' }
+ : { state: 'failed', error: 'START_TIMEOUT', detail })
if (failed) announceSession(failed)
console.warn(`[agent] create timed out · ${engine} · agent ${pending.agentId}`)
} catch (error) {
diff --git a/cli/src/core/agents/pendingLaunches.spec.ts b/cli/src/core/agents/pendingLaunches.spec.ts
index cd343fbe7..15117d5bb 100644
--- a/cli/src/core/agents/pendingLaunches.spec.ts
+++ b/cli/src/core/agents/pendingLaunches.spec.ts
@@ -26,6 +26,26 @@ function setup(prepare = vi.fn<Parameters<typeof createPendingLaunches>[0]['prep
return { pending, store, prepare }
}
+it('cannot replace a saved hold after the core has revoked its preparation', async () => {
+ let finish!: (value: PreparedCreation) => void
+ let authority!: Parameters<Parameters<typeof createPendingLaunches>[0]['prepare']>[1]
+ const prepare = vi.fn<Parameters<typeof createPendingLaunches>[0]['prepare']>((_request, current) => {
+ authority = current
+ return new Promise(resolve => { finish = resolve })
+ })
+ const { pending, store } = setup(prepare)
+ const running = pending.start(id(0), fingerprint, request, held)
+ await vi.waitFor(() => expect(prepare).toHaveBeenCalledOnce())
+ const nativeHold = { service: 'native', detail: 'Waiting for the original executable.' }
+ authority.hold(nativeHold)
+ expect(store.status(id(0))).toEqual({ state: 'pending', held: nativeHold })
+ pending.stop()
+ authority.hold({ service: 'obsolete', detail: 'A late answer' })
+ finish(null)
+ await running
+ expect(store.status(id(0))).toEqual({ state: 'pending', held: nativeHold })
+})
+
it('opens recovery after readiness, preserves pending intent and completes it once', async () => {
const effect = vi.fn(async () => created)
const prepare = vi.fn(async () => effect)
@@ -128,7 +148,7 @@ it('does not claim work yielded after shutdown or execute work stopped just afte
const effect = vi.fn(async () => created)
const second = setup(vi.fn(async () => effect), { ...receipts, runIntent: async (_id, _fingerprint, request, _held, prepare) => {
- const ready = await prepare(request)
+ const ready = await prepare(request, { id: _id, current: () => true, hold: () => {} })
second.pending.stop()
return ready!()
} })
diff --git a/cli/src/core/agents/pendingLaunches.ts b/cli/src/core/agents/pendingLaunches.ts
index b307be95b..46357851d 100644
--- a/cli/src/core/agents/pendingLaunches.ts
+++ b/cli/src/core/agents/pendingLaunches.ts
@@ -1,4 +1,4 @@
-import type { AgentCreationOutcome, AgentCreationReceipts, CreationHold, PendingCreationIntent } from '../../lib/agentCreationReceipt.js'
+import type { AgentCreationOutcome, AgentCreationReceipts, CreationAuthority, CreationHold, PendingCreationIntent } from '../../lib/agentCreationReceipt.js'
export type PreparedCreation = (() => Promise<AgentCreationOutcome>) | null
export type IntentReceipts = Pick<AgentCreationReceipts, 'runIntent' | 'pendingIntents' | 'pendingIntent' | 'cancelIntent'>
@@ -7,7 +7,7 @@ export type IntentReceipts = Pick<AgentCreationReceipts, 'runIntent' | 'pendingI
* service calls and never replays an effect whose durable claim already exists. */
export function createPendingLaunches({ receipts, prepare }: {
receipts: IntentReceipts
- prepare: (request: Record<string, unknown>) => Promise<PreparedCreation>
+ prepare: (request: Record<string, unknown>, authority: CreationAuthority) => Promise<PreparedCreation>
}) {
let stopped = false
let opened = false
@@ -30,32 +30,35 @@ export function createPendingLaunches({ receipts, prepare }: {
else crowded = true // The complete request is already durable on disk.
}
- const prepareOne = async (id: string, request: Record<string, unknown>): Promise<PreparedCreation> => {
+ const prepareOne = async (id: string, request: Record<string, unknown>, authority: CreationAuthority): Promise<PreparedCreation> => {
active++
+ let expired = false
+ const current = () => !stopped && !expired && authority.current()
+ const boundedAuthority: CreationAuthority = { id, current, hold: reason => { if (current()) authority.hold(reason) } }
let deadline: ReturnType<typeof setTimeout> | undefined
try {
const ready = await Promise.race([
// Retain a timed-out service's slot until its promise settles instead
// of accumulating unlimited abandoned preparations during an outage.
- Promise.resolve().then(() => prepare(request)).catch(() => null).finally(() => { active--; preparing.delete(id) }),
+ Promise.resolve().then(() => prepare(request, boundedAuthority)).catch(() => null).finally(() => { active--; preparing.delete(id) }),
// launchTarget permits three minutes for credential preparation. The
// receipt answers pending after five seconds without ending this work.
- new Promise<null>(resolve => { deadline = setTimeout(() => resolve(null), 185_000); deadline.unref?.() }),
+ new Promise<null>(resolve => { deadline = setTimeout(() => { expired = true; resolve(null) }, 185_000); deadline.unref?.() }),
])
- return stopped || !ready ? null : () => stopped ? Promise.resolve({ state: 'unconfirmed' }) : ready()
+ return !current() || !ready ? null : () => !current() ? Promise.resolve({ state: 'unconfirmed' }) : ready()
} finally { clearTimeout(deadline) }
}
- const bounded = (id: string, request: Record<string, unknown>): Promise<PreparedCreation> => {
+ const bounded = (id: string, request: Record<string, unknown>, authority: CreationAuthority): Promise<PreparedCreation> => {
if (stopped) return Promise.resolve(null)
const existing = preparing.get(id)
if (existing) return existing
if (active >= 4) return Promise.resolve(null)
- const result = prepareOne(id, request)
+ const result = prepareOne(id, request, authority)
preparing.set(id, result)
return result
}
const start = (id: string, fingerprint: string, request: Record<string, unknown>, held: CreationHold) => {
- const result = receipts.runIntent(id, fingerprint, request, held, saved => bounded(id, saved))
+ const result = receipts.runIntent(id, fingerprint, request, held, (saved, authority) => bounded(id, saved, authority))
remember(id, Date.now() + 2_000)
// Under backlog pressure, a settled hold gives its window slot to the next
// disk entry. The cursor finishes that pass before revisiting earlier IDs;
diff --git a/cli/src/core/agents/restart.spec.ts b/cli/src/core/agents/restart.spec.ts
index f5dc81530..b16b33fac 100644
--- a/cli/src/core/agents/restart.spec.ts
+++ b/cli/src/core/agents/restart.spec.ts
@@ -76,6 +76,51 @@ describe('restarting an agent', () => {
beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })
afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+ it.each(['starting', 'held'] as const)('does not replace an unbound native %s launch with a generic fresh restart', async state => {
+ const run = setup(agent({ sessionId: '', launch: state === 'starting' ? { state, nativeToken: 'original' }
+ : { state, nativeToken: 'original', service: 'native', detail: 'Original request held' } }))
+ expect(await run.restart('a1')).toMatchObject({ ok: false, error: 'NATIVE_LAUNCH_HELD' })
+ expect(run.deps.restartHeld).not.toHaveBeenCalled()
+ expect(run.deps.relaunchOverrides).not.toHaveBeenCalled()
+ expect(restartAgent).not.toHaveBeenCalled()
+ })
+
+ it.each(['inspection', 'permission', 'snapshot'] as const)('preserves the live process when restart loses %s evidence', async stage => {
+ let nativeCurrent = true
+ const launch = { current: () => nativeCurrent } as never
+ const run = setup(agent(), {
+ native: async () => { if (stage === 'inspection') run.state.live = false; return { ok: true, launch } },
+ relaunchOverrides: async () => ({ ok: true, overrides: { native: launch, env: {}, extraArgs: [], clearEnv: [] } }),
+ downgradedPermission: async () => {
+ if (stage === 'snapshot') nativeCurrent = false
+ return { bypassPermission: false, ...(stage === 'permission' ? { nativeHold: 'Waiting for native flags.' } : {}) }
+ },
+ })
+ expect(await run.restart('a1')).toMatchObject({ ok: false, error: stage === 'inspection' ? 'AGENT_CHANGED' : 'NATIVE_LAUNCH_HELD' })
+ expect(restartAgent).not.toHaveBeenCalled()
+ expect(run.deps.registry.updateProcessIdentity).not.toHaveBeenCalled()
+ })
+
+ it('holds native installation before killing the live process, without an independent shell probe', async () => {
+ const native = vi.fn(async () => ({ ok: false as const, error: 'NATIVE_LAUNCH_HELD' as const, unavailable: 'native' as const, detail: 'Waiting for installation' }))
+ const run = setup(agent(), { native })
+ expect(await run.restart('a1')).toMatchObject({ unavailable: 'native' })
+ expect(commandAvailableInInteractiveShell).not.toHaveBeenCalled()
+ expect(run.deps.relaunchOverrides).not.toHaveBeenCalled()
+ expect(restartAgent).not.toHaveBeenCalled()
+ })
+
+ it('passes its one native snapshot through restart preparation and permission checks', async () => {
+ const launch = { current: () => true } as never
+ const run = setup(agent(), { native: async () => ({ ok: true, launch }),
+ relaunchOverrides: vi.fn(async () => ({ ok: true as const, overrides: { native: launch, env: {}, extraArgs: [], clearEnv: [] } })),
+ })
+ expect(await run.restart('a1')).toMatchObject({ ok: true })
+ expect(commandAvailableInInteractiveShell).not.toHaveBeenCalled()
+ expect(run.deps.relaunchOverrides).toHaveBeenCalledWith(expect.any(Object), expect.any(Object), expect.any(Function), launch)
+ expect(run.deps.downgradedPermission).toHaveBeenCalledWith(expect.any(Object), true, 'restart', launch)
+ })
+
it('never starts a fresh conversation when an admitted external resume fails', async () => {
const actual = await vi.importActual<typeof import('../../lib/restartAgent.js')>('../../lib/restartAgent.js')
vi.mocked(restartAgent).mockImplementationOnce(actual.restartAgent)
@@ -252,7 +297,7 @@ describe('restarting an agent', () => {
expect(await run.restart('a1')).toEqual({ ok: true, session: agent(), resumed: true })
expect(bypassPermissionFor).toHaveBeenCalledWith(agent(), expect.any(Function))
expect(run.deps.liveBypassPermission).toHaveBeenCalledWith(agent())
- expect(run.deps.downgradedPermission).toHaveBeenCalledWith(agent(), true, 'restart')
+ expect(run.deps.downgradedPermission).toHaveBeenCalledWith(agent(), true, 'restart', undefined)
expect(run.deps.paneSwapDeps).toHaveBeenCalledWith(agent(), runtime, { env: { GRID_KEY: 'k' } }, 'auto', expect.any(Function))
const [target, bypass, swapDeps] = vi.mocked(restartAgent).mock.calls[0]
expect(target).toEqual({ engine: 'claude', sessionId: 's1' })
diff --git a/cli/src/core/agents/restart.ts b/cli/src/core/agents/restart.ts
index 5e46ea43d..f3b891d72 100644
--- a/cli/src/core/agents/restart.ts
+++ b/cli/src/core/agents/restart.ts
@@ -22,6 +22,7 @@ import { workspaceMissing } from '../../lib/workspaceCheck.js'
import type { createLaunchHelpers } from './launch.js'
import type { RestartAgent } from './launches.js'
import type { PaneSwap } from './swap.js'
+import type { LaunchOverridesDeps } from '../../lib/launchOverrides.js'
type LaunchHelpers = ReturnType<typeof createLaunchHelpers>
@@ -46,6 +47,7 @@ async function engineInstalled(engine: AgentEngine): Promise<boolean | null> {
type RestartAgentHandler = RestartAgent
export interface RestartDeps {
+ native?: LaunchOverridesDeps['native']
restartJobs: PaneSwap['restartJobs']
registry: typeof registry
/** Whether a purge holds this agent (PurgeAgentService.busy). */
@@ -71,6 +73,7 @@ export interface RestartDeps {
}
export function createAgentRestarter({
+ native: inspectNative,
restartJobs, registry, purgeBusy, stopJobs, pinnedControls, tmuxBackend, sameRestartTarget, agentReconciler,
terminalHintMachineName, announceSession, refreshGridAssignment, relaunchOverrides, downgradedPermission, refreshGridWebSearch,
liveBypassPermission, paneSwapDeps, restartHeld,
@@ -98,6 +101,9 @@ export function createAgentRestarter({
if (purgeBusy(agentId) || stopJobs.has(agentId) || pinnedControls.has(agentId)) return { ok: false, error: 'AGENT_BUSY' }
const session = registry.resolve(agentId)
if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }
+ if (!session.sessionId && (session.launch?.state === 'held' || session.launch?.state === 'starting') && session.launch.nativeToken) {
+ return { ok: false, error: 'NATIVE_LAUNCH_HELD', detail: 'The original launch is held for recovery. Its first prompt or fork cannot be replaced by a fresh launch.' }
+ }
const held = restartHeld(session.agentId)
if (held) return held
if (!session.tmuxPane || !tmuxBackend) return { ok: false, error: 'RESTART_UNSUPPORTED_BACKEND' }
@@ -149,7 +155,11 @@ export function createAgentRestarter({
// cannot come back. Asked anyway, the swap killed the working agent and gave up twenty seconds
// later with "did not come back up" (updates.e2e.ts, round 24). Asked here, before anything is
// touched, the agent goes on running and the person is told why.
- const installed = await engineInstalled(engine)
+ const inspected = await inspectNative?.(engine, session, { id: session.agentId, current })
+ if (!current()) return changed
+ if (inspected && !inspected.ok) return inspected
+ const native = inspected?.ok ? inspected.launch : undefined
+ const installed = native ? true : await engineInstalled(engine)
if (!current()) return changed
if (installed === false) {
console.warn(`[restart] ${sid(session.agentId)} refused · ${engine} is not installed`)
@@ -161,18 +171,20 @@ export function createAgentRestarter({
// half, and an agent moved here by a retarget has nothing in the session env at all), or its
// Codex profile. Refused before anything is killed, so a restart that cannot honour the grid
// leaves the running process alone.
- const built = await relaunchOverrides(session, session, current)
+ const built = await relaunchOverrides(session, session, current, native)
if (!current()) return changed
- if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
+ if (!built.ok) return built
agentReconciler.holdRoute(routeKey)
try {
const restartPermission = await downgradedPermission(session,
- await bypassPermissionFor(session, () => liveBypassPermission(session)), 'restart')
+ await bypassPermissionFor(session, () => liveBypassPermission(session)), 'restart', built.overrides.native)
+ if (restartPermission.nativeHold || built.overrides.native?.current() === false) return { ok: false, error: 'NATIVE_LAUNCH_HELD', detail: restartPermission.nativeHold ?? 'Waiting for fresh executable and hook evidence.' }
+ const dispatchCurrent = () => current() && built.overrides.native?.current() !== false
const outcome = await restartAgent(
{ engine, sessionId: session.sessionId, ...(session.resumeOnly ? { resumeOnly: true as const } : {}) },
restartPermission.bypassPermission === true,
- { ...paneSwapDeps(session, runtime, built.overrides, restartPermission.permissionMode ?? null, current), isCurrent: current },
+ { ...paneSwapDeps(session, runtime, built.overrides, restartPermission.permissionMode ?? null, dispatchCurrent), isCurrent: dispatchCurrent },
)
if (!current()) return changed
diff --git a/cli/src/core/agents/restoreLaunch.spec.ts b/cli/src/core/agents/restoreLaunch.spec.ts
index a606ab1a0..3b835a41c 100644
--- a/cli/src/core/agents/restoreLaunch.spec.ts
+++ b/cli/src/core/agents/restoreLaunch.spec.ts
@@ -4,6 +4,7 @@ import type { LaunchOverridesResult } from '../../lib/launchOverrides.js'
import { createRestoreLaunch } from './restoreLaunch.js'
import { createLaunchHelpers } from './launch.js'
import { createLaunchAuthority } from './launchAuthority.js'
+import type { NativeLaunch } from '../../engines/nativeLaunch.js'
const entry = { agentId: 'agent', sessionId: 'conversation', cwd: '/workspace' } as RegisteredSession
const built: Extract<LaunchOverridesResult, { ok: true }> = { ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } }
@@ -19,6 +20,21 @@ const setup = () => {
}
describe('restore preparation keeps session authority in core', () => {
+ it.each(['unknown flags', 'changed executable', 'ready'] as const)('preserves native preparation evidence through restore: %s', async stage => {
+ const { deps, build } = setup()
+ const native = { current: () => stage !== 'changed executable' } as NativeLaunch
+ deps.relaunchOverrides.mockResolvedValue({ ok: true, overrides: { ...built.overrides, native } })
+ if (stage === 'unknown flags') deps.downgradedPermission.mockResolvedValue({ bypassPermission: false, nativeHold: 'Waiting for executable help.' } as never)
+ const result = await build(entry, { current: () => true })
+ expect(deps.downgradedPermission).toHaveBeenCalledWith(entry, native)
+ if (stage === 'ready') expect(result).toEqual({ argv: ['engine'] })
+ else {
+ expect(result).toMatchObject({ held: 'native' })
+ expect(deps.launch).not.toHaveBeenCalled()
+ expect(deps.refreshGridWebSearch).not.toHaveBeenCalled()
+ }
+ })
+
it.each(['dead process', 'terminal fallback', 'fresh fallback'] as const)('composes preparation for a legitimate %s projection', async projection => {
const live = { ...entry, engine: 'claude', active: true, launch: { state: 'ready' },
processIdentity: { pid: 42, startMarker: 'old' }, runtimes: [{ backend: 'tmux', paneId: '%7' }],
diff --git a/cli/src/core/agents/restoreLaunch.ts b/cli/src/core/agents/restoreLaunch.ts
index 8f8809af8..72f472846 100644
--- a/cli/src/core/agents/restoreLaunch.ts
+++ b/cli/src/core/agents/restoreLaunch.ts
@@ -7,7 +7,7 @@ import type { RestoreAgentsDeps, RestoreLaunch } from '../../lib/restoreAgents.j
interface RestoreLaunchDeps {
workspaceMissing(cwd: string | null | undefined): { error: string; detail: string } | null
relaunchOverrides(entry: RegisteredSession, source: RegisteredSession, current: () => boolean): Promise<LaunchOverridesResult>
- downgradedPermission(entry: RegisteredSession): Promise<{ permissionMode?: string | null; bypassPermission?: boolean }>
+ downgradedPermission(entry: RegisteredSession, native?: LaunchOverrides['native']): Promise<{ permissionMode?: string | null; bypassPermission?: boolean; nativeHold?: string }>
prepareSessionResume(entry: RegisteredSession): void
refreshGridWebSearch(agentId: string, overrides: LaunchOverrides): void
launch(entry: RegisteredSession, opts: { resumeSessionId?: string }, overrides: LaunchOverrides,
@@ -26,8 +26,10 @@ export function createRestoreLaunch(deps: RestoreLaunchDeps): RestoreAgentsDeps[
if (!built.ok) return built.unavailable
? { held: built.unavailable, detail: built.detail, holdScope: built.holdScope }
: { error: built.error, detail: built.detail }
- const permission = await deps.downgradedPermission(entry)
+ const permission = await deps.downgradedPermission(entry, built.overrides.native)
if (!current()) return { cancelled: true }
+ if (permission.nativeHold) return { held: 'native', detail: permission.nativeHold }
+ if (built.overrides.native?.current() === false) return { held: 'native', detail: 'Waiting for fresh executable and hook evidence.' }
// These writes are synchronous and belong to the core. Neither a stopped conversation's
// transcript/tail nor a replacement binding's grid may be changed by an old Store answer.
if (opts.resumeSessionId) {
diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.ts
index ff9acdd15..1f153e21f 100644
--- a/cli/src/core/agents/retarget.spec.ts
+++ b/cli/src/core/agents/retarget.spec.ts
@@ -13,6 +13,7 @@ import { workspaceMissing } from '../../lib/workspaceCheck.js'
import { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'
import { terminalRouteKey } from '../../lib/terminalRuntime.js'
import { createAgentRetargeter, type RetargetDeps } from './retarget.js'
+import type { NativeLaunch } from '../../engines/nativeLaunch.js'
vi.mock('../../engines/launchControl.js', async (real) => ({
...await real<object>(),
@@ -87,6 +88,73 @@ describe('retargeting an agent', () => {
})
afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks() })
+ it('holds an unavailable native retarget before inspecting or mutating the pane', async () => {
+ const held = { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting for native evidence.' } as const
+ const run = setup(agent(), { launchOverridesDeps: { native: async () => held } as never })
+ expect(await run.retarget({ agentId: 'a1', grid })).toEqual(held)
+ expect(run.deps.captureTerminal).not.toHaveBeenCalled()
+ expect(restartAgent).not.toHaveBeenCalled()
+ })
+
+ it.each(['ready', 'permission', 'snapshot'] as const)('keeps retarget native write and dispatch on one snapshot: %s', async mode => {
+ let nativeCurrent = true
+ const launch = { current: () => nativeCurrent, executable: '/fixture/native/opencode', environment: { HOME: '/fixture/home' }, opencodeMajor: 2 } as unknown as NativeLaunch
+ const run = setup(agent({ engine: 'opencode' }), {
+ launchOverridesDeps: { native: async () => ({ ok: true, launch }) } as never,
+ relaunchOverrides: async () => ({ ok: true, overrides: { native: launch, env: { HOME: '/fixture/home' }, extraArgs: [], clearEnv: [], sessionModel: 'fixture/model' } }),
+ downgradedPermission: async () => {
+ if (mode === 'snapshot') nativeCurrent = false
+ return { bypassPermission: false, ...(mode === 'permission' ? { nativeHold: 'Waiting for native permission flags.' } : {}) }
+ },
+ })
+ vi.mocked(applyOpencodeSessionModel).mockImplementationOnce(async (_input, options) => {
+ expect(_input.dbPath).toBe('/fixture/home/.local/share/opencode/opencode.db')
+ expect(options?.current?.()).toBe(true)
+ expect(options).toMatchObject({ executable: launch.executable, environment: { HOME: '/fixture/home' } })
+ return { ok: true }
+ })
+ const result = await run.retarget({ agentId: 'a1', grid })
+ expect(opencodeMajorVersion).not.toHaveBeenCalled()
+ if (mode === 'ready') {
+ expect(result).toEqual({ ok: true })
+ expect(restartAgent).toHaveBeenCalledOnce()
+ } else {
+ expect(result).toMatchObject({ ok: false, error: 'NATIVE_LAUNCH_HELD' })
+ expect(restartAgent).not.toHaveBeenCalled()
+ }
+ const current = vi.mocked(applyOpencodeSessionModel).mock.calls[0]![1]!.current!
+ nativeCurrent = false
+ expect(current()).toBe(false)
+ nativeCurrent = true
+ vi.mocked(run.deps.registry.byAgent).mockReturnValue(undefined)
+ expect(current()).toBe(false)
+ })
+
+ it.each(['prepared', 'clearing', 'hold-open'] as const)('keeps the live process when native proof changes during %s', async phase => {
+ const actual = await vi.importActual<typeof import('../../lib/restartAgent.js')>('../../lib/restartAgent.js')
+ vi.mocked(restartAgent).mockImplementationOnce(actual.restartAgent)
+ let valid = true
+ const native = { current: () => valid } as NativeLaunch
+ const terminate = vi.fn(async () => 'gone' as const), respawn = vi.fn(async () => ({ ok: true }))
+ const run = setup(agent(), { launchOverridesDeps: { native: async () => ({ ok: true, launch: native }) } as never,
+ relaunchOverrides: async () => {
+ if (phase === 'prepared') valid = false
+ return { ok: true, overrides: { native, env: {}, extraArgs: [], clearEnv: [] } }
+ },
+ paneSwapDeps: () => ({ holdOpen: async () => { valid = false; return { ok: true } }, terminate, respawn,
+ waitForProcess: async () => null, buildArgv: () => ['fixture-engine'], log: () => {} }),
+ })
+ if (phase === 'clearing') vi.mocked(run.deps.tmuxBackend!.clearEnv).mockImplementationOnce(async (_pane, _vars, current) => {
+ valid = false
+ expect(current?.()).toBe(false)
+ return { state: 'succeeded', dispatch: 'executed' }
+ })
+ expect(await run.retarget({ agentId: 'a1', grid: null })).toMatchObject({ ok: false })
+ expect(terminate).not.toHaveBeenCalled()
+ expect(respawn).not.toHaveBeenCalled()
+ vi.mocked(restartAgent).mockReset().mockResolvedValue({ ok: true, resumed: true, processIdentity: { pid: 2, startMarker: 'new', executable: '/bin/claude' } })
+ })
+
it('keeps an admitted external conversation when its retarget resume fails', async () => {
const actual = await vi.importActual<typeof import('../../lib/restartAgent.js')>('../../lib/restartAgent.js')
vi.mocked(restartAgent).mockImplementationOnce(actual.restartAgent)
diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.ts
index 5e56b5a2e..4077af975 100644
--- a/cli/src/core/agents/retarget.ts
+++ b/cli/src/core/agents/retarget.ts
@@ -32,6 +32,7 @@ import { workspaceMissing } from '../../lib/workspaceCheck.js'
import type { createLaunchHelpers } from './launch.js'
import type { PaneSwap } from './swap.js'
import { createLaunchAuthority } from './launchAuthority.js'
+import { nativeOpencodeStore } from '../../engines/kit/nativeLocations.js'
type LaunchHelpers = ReturnType<typeof createLaunchHelpers>
@@ -135,7 +136,11 @@ export function createAgentRetargeter({
codexHome: session.codexHome,
...(grid ? {} : { subscriptionModel: remembered }),
}
- const valid = await validateLaunchOverrides(launchOverridesDeps, session.engine, target)
+ const inspected = await launchOverridesDeps.native?.(session.engine, session, { id: session.agentId, current })
+ if (!current()) return changed()
+ if (inspected && !inspected.ok) return inspected
+ const native = inspected?.ok ? inspected.launch : undefined
+ const valid = await validateLaunchOverrides(launchOverridesDeps, session.engine, target, native)
if (!current()) return changed()
if (!valid.ok) return { ok: false, error: valid.error, detail: valid.detail }
// A resumed opencode session takes its model from its own rows in opencode.db, not from `-m`
@@ -149,7 +154,7 @@ export function createAgentRetargeter({
const rewritesOpencodeSession = session.engine === 'opencode' && !!session.sessionId
&& (!!grid || !!remembered?.includes('/'))
const opencode = session.engine === 'opencode' ? opencodeLaunch : null
- const opencodeMajor = opencode ? await opencode.opencodeMajorVersion() : null
+ const opencodeMajor = native ? native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null
if (!current()) return changed()
if (rewritesOpencodeSession && opencode && !opencode.isOpencodeV2(opencodeMajor) && !binaryOnPath('sqlite3')) {
return {
@@ -187,9 +192,13 @@ export function createAgentRetargeter({
// (clearing uses set-environment, which every supported tmux has). Built from the override the
// desktop just sent, never from the row: the row is what this call REPLACES. After the refusal
// guards, so a refused move leaves the live process's own configuration untouched.
- const built = await relaunchOverrides(session, target, current)
+ const built = await relaunchOverrides(session, target, current, native)
if (!current()) return changed()
if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
+ const dispatchCurrent = () => current() && native?.current() !== false && built.overrides.native?.current() !== false
+ const preparationChanged = () => current()
+ ? failed('NATIVE_LAUNCH_HELD', 'Waiting for fresh executable and hook evidence.') : changed()
+ if (!dispatchCurrent()) return preparationChanged()
// ⚠️ THE AGENT MUST ADOPT THE NEW PROCESS, OR IT STOPS BEING THE SAME AGENT.
//
@@ -233,13 +242,13 @@ export function createAgentRetargeter({
if (model) {
nativeEffect = 'uncertain'
const written = await opencode.applyOpencodeSessionModel({
- opencodeMajor, dbPath: opencodeDb, sessionId: session.sessionId, model, cwd: session.cwd ?? undefined,
+ opencodeMajor, dbPath: native ? nativeOpencodeStore(native.environment) : opencodeDb, sessionId: session.sessionId, model, cwd: session.cwd ?? undefined,
// (A model of opencode's own is looked for in its catalogue; a grid's provider lives in
// the pane's own config, which the service never reads.)
checkCatalog: !grid,
- }, { current })
+ }, { current: dispatchCurrent, ...(native?.executable ? { executable: native.executable, environment: { ...built.overrides.env, ...native.environment } } : {}) })
nativeEffect = written.ok ? 'applied' : (written.effect ?? 'none')
- if (!current()) return changed()
+ if (!dispatchCurrent()) return preparationChanged()
if (!written.ok) {
console.warn(`[grid] retarget ${sid(session.agentId)} refused · ${written.code} · ${written.detail}`)
return { ok: false, error: written.code, detail: written.detail }
@@ -247,20 +256,21 @@ export function createAgentRetargeter({
}
}
if (!grid) {
- const cleared = await tmuxBackend.clearEnv(pane, gridEnvVarNames(session.engine), current)
- if (!current()) return changed()
+ const cleared = await tmuxBackend.clearEnv(pane, gridEnvVarNames(session.engine), dispatchCurrent)
+ if (!dispatchCurrent()) return preparationChanged()
if (cleared.state !== 'succeeded') {
return failed('GRID_CLEAR_FAILED', 'reason' in cleared ? cleared.reason : 'tmux would not clear the pane environment')
}
}
const bypassPermission = await bypassPermissionFor(session, () => liveBypassPermission(session))
if (!current()) return changed()
- const retargetPermission = await downgradedPermission(session, bypassPermission, 'retarget')
+ const retargetPermission = await downgradedPermission(session, bypassPermission, 'retarget', native)
+ if (retargetPermission.nativeHold || native?.current() === false) return failed('NATIVE_LAUNCH_HELD', retargetPermission.nativeHold ?? 'Waiting for fresh executable and hook evidence.')
if (!current()) return changed()
const outcome = await restartAgent(
{ engine: session.engine, sessionId: session.sessionId, ...(session.resumeOnly ? { resumeOnly: true as const } : {}) },
retargetPermission.bypassPermission === true,
- { ...paneSwapDeps(session, pane, built.overrides, retargetPermission.permissionMode ?? null, current), isCurrent: current },
+ { ...paneSwapDeps(session, pane, built.overrides, retargetPermission.permissionMode ?? null, dispatchCurrent), isCurrent: dispatchCurrent },
)
replacementStarted = outcome.ok
if (!current()) return changed()
diff --git a/cli/src/core/agents/swap.spec.ts b/cli/src/core/agents/swap.spec.ts
index fe3d36258..118dc7e48 100644
--- a/cli/src/core/agents/swap.spec.ts
+++ b/cli/src/core/agents/swap.spec.ts
@@ -7,6 +7,7 @@ import { processRows } from '../../lib/terminalAgentDiscovery.js'
import { bypassPermissionActive, resolvePaneEngineProcess } from '../../lib/tmux.js'
import { AgentRestartCoordinator } from '../../lib/restartAgent.js'
import { createPaneSwap, SWAP_SETTLE_MS, type PaneSwapDeps } from './swap.js'
+import type { NativeLaunch } from '../../engines/nativeLaunch.js'
vi.mock('../../lib/deleteAgentFallback.js', async (real) => ({ ...await real<object>(), terminateDeletedAgent: vi.fn(async () => ({ ok: true })) }))
vi.mock('../../lib/engineLaunch.js', async (real) => ({ ...await real<object>(), buildEngineLaunchArgv: vi.fn(() => ['zsh', '-lc', 'claude']) }))
@@ -37,6 +38,12 @@ function setup(row: RegisteredSession | null = session()) {
}
describe('the pane-process swap', () => {
+ it('passes the prepared native snapshot into the final argv builder', () => {
+ const native = { token: 'prepared-native' } as NativeLaunch
+ const prepared = setup().swap.paneSwapDeps(session(), runtime, { native })
+ prepared.buildArgv({ resumeSessionId: 's1', bypassPermission: false })
+ expect(buildEngineLaunchArgv).toHaveBeenCalledWith('claude', expect.objectContaining({ native, resumeSessionId: 's1' }))
+ })
beforeEach(() => {
vi.mocked(terminateDeletedAgent).mockClear()
vi.mocked(resolvePaneEngineProcess).mockReset().mockResolvedValue(null)
diff --git a/cli/src/core/agents/swap.ts b/cli/src/core/agents/swap.ts
index fff191ddf..165c16175 100644
--- a/cli/src/core/agents/swap.ts
+++ b/cli/src/core/agents/swap.ts
@@ -48,7 +48,7 @@ export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume, kee
const paneSwapDeps = (
session: RegisteredSession,
runtime: TmuxRuntimeRef,
- launch: { env?: Record<string, string>; extraArgs?: readonly string[]; clearEnv?: readonly string[] } = {},
+ launch: { native?: import('../../engines/nativeLaunch.js').NativeLaunch; env?: Record<string, string>; extraArgs?: readonly string[]; clearEnv?: readonly string[] } = {},
/** The mode this swap may actually ask for — the row's own, unless the engine on disk has since
* stopped taking its flag and the caller dropped it (`dropPermissionFlagIfUnsupported`). */
permissionMode: string | null = session.permissionMode ?? null,
@@ -108,6 +108,7 @@ export function createPaneSwap({ byAgent, tmuxBackend, prepareSessionResume, kee
},
buildArgv: (opts) => buildEngineLaunchArgv(session.engine, {
...opts,
+ ...(launch.native ? { native: launch.native } : {}),
// The mode picked at create outranks what the live argv said: `bypassPermission` is a yes/no, and
// Plan or Accept edits would come back as Ask without it.
...(permissionMode ? { permissionMode } : {}),
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index b6b1bc371..78b61df3d 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -7,6 +7,11 @@ import { createScreens } from './engines/screens.js'
import { createScreenTransport } from './engines/screenTransport.js'
import { inProcessScreen, preloadEngine } from '../engines/inProcess.js'
import { opencodeMajorVersion } from '../engines/launchControl.js'
+import { inspectNativeLaunch, type NativeLaunch } from '../engines/nativeLaunch.js'
+import { nativeHookLocations } from '../engines/kit/nativeLocations.js'
+import { createNativeLaunchPreparer } from '../engines/prepareNativeLaunch.js'
+import { createNativeInstallations } from '../engines/kit/nativeInstall.js'
+import { publishGridConfigDir } from '../lib/publishedGridConfig.js'
import { masterRunsEngineScreen } from '../harnessd/services.js'
import { createSubmissions } from './engines/submissions.js'
import { createNativeControls } from './engines/nativeControls.js'
@@ -84,7 +89,8 @@ import { ApiConnectionMetadata } from '../lib/apiConnectionMetadata.js'
import { prepareApiInstructions } from '../lib/apiInstructions.js'
import type { AgentDshContext } from '../lib/agentFrame.js'
import type { AgentGridTarget, GridAnnotation } from '../lib/gridAnnotation.js'
-import { sessionCodexHome } from '../lib/engineHomes.js'
+import { confirmHomes, sessionCodexHome } from '../lib/engineHomes.js'
+import { sessionStoreContracts } from '../engines/sessionStoreContracts.js'
import { argvTokens, clearPaneRemainOnExit, lookupPaneEngineProcess, processRows, resolvePaneEngineProcess, tmuxPaneInfo, tmuxPaneState } from '../lib/tmux.js'
import { ALL_TERMINAL_BACKENDS } from '../config/terminalConfig.js'
import { TerminalBackendCoordinator } from '../lib/terminalBackendCoordinator.js'
@@ -428,10 +434,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
let searchGeneration = 0
let restoreCancelled = (_agentId: string): boolean => false
let launchCancelled = (_agentId: string): boolean => false
- let restoreOnly: ((only: ReadonlySet<string>) => Promise<RestoreSummary>) | null = null
+ let restoreOnly: ((only: ReadonlySet<string>, current: () => boolean) => Promise<RestoreSummary>) | null = null
const heldLaunches = createHeldLaunches({
registry,
- restore: (only) => restoreOnly?.(only) ?? Promise.resolve({ restored: [], skipped: [], failed: [], held: [], unsurveyed: [] }),
+ restore: (only, current) => restoreOnly?.(only, current) ?? Promise.resolve({ restored: [], skipped: [], failed: [], held: [], unsurveyed: [] }),
log: (line) => console.log(line),
})
wakeGateway({ outOfProcess: servicesTheMasterRuns(process.env, KNOWN_SERVICES), signedIn: !!session, dataDir: env.ADAPTER_DATA_DIR, want: (service) => coreLink.want(service) })
@@ -1966,9 +1972,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
* OpenCode launch alone, by OpenCode's own code: every launch of OpenCode loads it before asking, and is refused
* without it (core/agents/create.ts, lib/launchOverrides.ts).
*/
- const gridLaunchMachine = async (engine: AgentEngine): Promise<GridLaunchMachine> => ({
+ const gridLaunchMachine = async (engine: AgentEngine, native?: NativeLaunch): Promise<GridLaunchMachine> => ({
hermesSystemManaged: existsSync(HERMES_SYSTEM_MANAGED_DIR),
- opencodeMajor: engine === 'opencode' ? await opencodeMajorVersion() : null,
+ opencodeMajor: native ? native.opencodeMajor : engine === 'opencode' ? await opencodeMajorVersion() : null,
+ ...(native?.environment.HOME ? {
+ grokHome: nativeHookLocations(native.environment).GROK_HOME,
+ piSkillsDir: join(nativeHookLocations(native.environment).PI_AGENT_DIR, 'skills'),
+ } : {}),
})
/**
@@ -1982,8 +1992,17 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const gridLaunch = gridLaunchThrough(() => ports.models ?? MODELS_OFF)
const dshLaunch = dshThrough({ store: () => ports.store ?? STORE_OFF,
nameOf: id => installedDsh(id)?.manifest.name, account: () => ({ privateGrid: backend.gridName() }) })
+ const prepareNativeLaunch = createNativeLaunchPreparer({
+ installations: createNativeInstallations({ directory: join(env.ADAPTER_DATA_DIR, 'native-installations') }),
+ inspect: (engine, source) => inspectNativeLaunch(engine, source, {
+ confirmHome: (engine, home) => { confirmHomes({ [sessionStoreContracts[engine].sessions.moved.variable]: home }) },
+ }),
+ })
const launchOverridesDeps: LaunchOverridesDeps = {
+ publishConfig: publishGridConfigDir,
machine: gridLaunchMachine,
+ native: prepareNativeLaunch,
+ prepareNative: (native, current, environment, clear) => native.prepareHooks(env.DISABLE_HOOK_INSTALL ? 0 : hookPort, current, environment, clear),
gridLaunch,
writeGridConfigDir,
tmuxSupportsSessionEnv,
@@ -1992,8 +2011,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
// What a relaunch needs to bring a pane back (core/agents/launch.ts). Declared before the restore
// pass below, which calls these for every pane it rebuilds.
+ const launchAuthority = createLaunchAuthority({ byAgent: id => registry.byAgent(id), revision: restoreRevision, cancelled: id => launchCancelled(id) })
const launchHelpers = createLaunchHelpers({
- authority: createLaunchAuthority({ byAgent: id => registry.byAgent(id), revision: restoreRevision, cancelled: id => launchCancelled(id) }),
+ authority: launchAuthority,
prepareApiTools,
launchOverridesDeps,
setGridLaunch: (agentId, launch) => registry.setGridLaunch(agentId, launch),
@@ -2035,7 +2055,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (saved && !isTerminalEngine(saved.engine)) retainExitedSession(entry, true)
}
// Later passes over held agents (core/agents/heldLaunches.ts) wait for this one.
- await heldLaunches.boot(async () => {
+ await heldLaunches.boot(async (current) => {
if (tmuxBackend) {
// Best effort, like the cwd repair above it: panes that cannot be rebuilt cost this boot its
// tiles, not the daemon. `restoreDegraded` then stops discovery retiring the rows whose panes
@@ -2043,7 +2063,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
try {
const backend = tmuxBackend
const restoreDeps: RestoreAgentsDeps = {
- cancelled: (agentId) => restoreCancelled(agentId),
+ cancelled: (agentId) => !current() || restoreCancelled(agentId),
revision: (agentId) => restoreRevision(agentId),
paneOperation: restorePanes.run,
paneAllocations: restorePanes.runMany,
@@ -2061,11 +2081,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
liveProcess: (entry, runtime) => tmuxSurvey(() => listTmuxPanes(), lookupPaneEngineProcess).liveProcess(entry, runtime),
buildLaunch: createRestoreLaunch({
workspaceMissing, relaunchOverrides, prepareSessionResume, refreshGridWebSearch,
- downgradedPermission: (entry) => downgradedPermission(entry, entry.bypassPermission === true, 'restore'),
+ downgradedPermission: (entry, native) => downgradedPermission(entry, entry.bypassPermission === true, 'restore', native),
launch: (entry, opts, overrides, permission) => {
const { env: launchEnv, extraArgs, clearEnv } = overrides
const argv = buildEngineLaunchArgv(entry.engine, {
...opts,
+ ...(overrides.native ? { native: overrides.native } : {}),
...(entry.externalResume?.continue && entry.externalResume.signal === 'sent' && !entry.externalResume.dispatched && supportsFirstPrompt(entry.engine) ? { firstPrompt: 'continue' } : {}),
bypassPermission: permission.bypassPermission === true,
...(permission.permissionMode ? { permissionMode: permission.permissionMode } : {}),
@@ -2075,7 +2096,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
...(clearEnv.length ? { clearEnv } : {}),
...(launchEnv.HARNESS_DSH ? { harnessNode: true } : {}),
})
- return { argv, ...(Object.keys(launchEnv).length ? { env: launchEnv } : {}) }
+ return { argv, ...(overrides.native ? { nativeToken: overrides.native.token, current: overrides.native.current } : {}), ...(Object.keys(launchEnv).length ? { env: launchEnv } : {}) }
},
}),
createPane: async (entry, launch, control) => {
@@ -2107,12 +2128,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
triggerHint: async (runtime, engine) => { await agentReconciler.triggerHint(runtime, engine) },
log: (message) => console.log(message),
// A grid's or a saved API's launch asks models: not before the core is ready (core/agents/heldLaunches.ts).
- needs: (entry) => [...(externalResumePending(entry.externalResume) ? ['search'] : []), ...(entry.gridLaunch ? ['models'] : []), ...(entry.dsh ? ['store'] : [])],
- waitingLaunch: (entry, held) => ({ argv: heldPaneArgv(held.detail, entry.externalResume?.token) }),
+ needs: (entry) => [...(externalResumePending(entry.externalResume) ? ['search'] : []), ...(entry.gridLaunch ? ['models'] : []), ...(entry.dsh ? ['store'] : []), ...(!isTerminalEngine(entry.engine) ? ['native'] : [])],
+ waitingLaunch: (entry, held) => ({ argv: heldPaneArgv(held.detail, entry.externalResume?.token ?? held.nativeToken) }),
killPane: async (runtime) => { await backend.kill(runtime) },
}
// Later passes launch the held agents, into the panes they wait in, outside this pass's transaction.
- restoreOnly = (only) => restoreAgents({ ...restoreDeps, only })
+ restoreOnly = (only, current) => restoreAgents({ ...restoreDeps, only, cancelled: id => !current() || restoreCancelled(id) })
const summary = await restoreAgents({ ...restoreDeps, defer: true })
// A row restore could not look at keeps its pane for discovery to judge, but not to retire this boot.
for (const agentId of summary.unsurveyed) restoreUnsurveyed.add(agentId)
@@ -2254,6 +2275,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Watching a pane create or fork just opened until its engine is up, or why not (core/agents/newPane.ts).
const watchNewPane = createPaneWatcher({
+ waitingPane: (runtime, token) => tmuxBackend?.isHeld(runtime, token) ?? Promise.resolve('unknown'),
registry,
announceSession,
triggerHint: async (runtime, engine) => { await agentReconciler.triggerHint(runtime, engine) },
@@ -2268,13 +2290,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {
waiting: row => tmuxBackend?.isHeld({ backend: 'tmux', paneId: row.tmuxPane }, row.externalResume!.token).then(value => value === true) ?? Promise.resolve(false),
inspect: request => ports.search?.inspect(request) ?? Promise.resolve(externalUnavailable()),
preflight: createExternalPreflight({ blocksFolder: cwd => backend.purgeAgentService?.blocksFolder(cwd),
- hookPort, hooksDisabled: env.DISABLE_HOOK_INSTALL, installOpencodePlugin: installOpencodePluginBeforeSpawn }),
+ native: prepareNativeLaunch, hookPort, hooksDisabled: env.DISABLE_HOOK_INSTALL, installOpencodePlugin: installOpencodePluginBeforeSpawn }),
announce: announceSession, launch: () => { void heldLaunches.restoreHeld('search') },
forget: id => forgetSession(id, { force: true }),
})
// Creating an agent (core/agents/create.ts).
- backend.onCreateAgent = createAgentCreator({
+ const creator = createAgentCreator({
+ publishConfig: publishGridConfigDir,
+ native: prepareNativeLaunch,
dshLaunch,
tmuxBackend,
registry,
@@ -2297,9 +2321,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The backend's word, else what the models service works out (services/models.ts).
privateGridName: async () => backend.gridName() ?? await (ports.models ?? MODELS_OFF).privateGridName(),
})
+ backend.onCreateAgent = creator
// Forking an agent (core/agents/fork.ts).
backend.onForkAgent = createAgentForker({
+ native: prepareNativeLaunch,
+ prepareNative: launchOverridesDeps.prepareNative,
+ authority: launchAuthority,
dshLaunch,
tmuxBackend,
registry,
@@ -2406,6 +2434,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Restarting an agent in its own pane (core/agents/restart.ts).
const restartAgent = createAgentRestarter({
+ native: prepareNativeLaunch,
restartJobs,
registry,
purgeBusy: (agentId) => restorePanes.busy(agentId) || backend.purgeAgentService?.busy(agentId),
@@ -2429,6 +2458,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,
resumeAgent: () => lifecycle.resumeAgent, restartAgent: () => restartAgent,
byAgent: (id) => registry.byAgent(id), toProject: (s) => backend.toProject(s),
modelTarget: (selection) => (ports.models ?? MODELS_OFF).launchTarget(selection),
@@ -2469,7 +2499,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// stops being `bootHandoff` HERE, and not a line earlier: everything the teardown releases exists by now.
// A straight-line assignment, never a wait: if the body never reaches this line the handler stays
// `bootHandoff`, and the fix still lands.
- const updateTeardown = (): TeardownStep[] => { installedHooks?.close(); externalResumes?.stop(); launches.stop(); return [
+ const updateTeardown = (): TeardownStep[] => { heldLaunches.close(); installedHooks?.close(); externalResumes?.stop(); launches.stop(); return [
['the registry', () => registry.flush({ exiting: true })], ['the updater', () => daemonBoot.updaterBeside?.()],
['the reconciler', () => agentReconciler.stop()],
['the timers', () => { clearInterval(logTrimTimer); clearInterval(runtimeReconcileTimer); clearInterval(paneTitleSyncTimer) }],
@@ -2506,6 +2536,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
* which restarts any other exit (harnessd/protocol.ts). */
const forGood = (reason: string): boolean => reason === 'revoked' || reason === 'busy'
const shutdown = async (signal: string): Promise<void> => {
+ heldLaunches.close()
installedHooks?.close()
externalResumes?.stop()
launches.stop()
diff --git a/cli/src/engines/__fixtures__/native-launch-compatibility.golden.json b/cli/src/engines/__fixtures__/native-launch-compatibility.golden.json
new file mode 100644
index 000000000..b38c56c1f
--- /dev/null
+++ b/cli/src/engines/__fixtures__/native-launch-compatibility.golden.json
@@ -0,0 +1,336 @@
+{
+ "claude fresh": [
+ "claude"
+ ],
+ "claude resume": [
+ "claude",
+ "--resume",
+ "fixture-conversation"
+ ],
+ "claude fork": [
+ "claude",
+ "--resume",
+ "fixture-parent",
+ "--fork-session"
+ ],
+ "claude permission": [
+ "claude",
+ "--permission-mode",
+ "auto",
+ "--model",
+ "fixture/model"
+ ],
+ "claude first": [
+ "claude",
+ "literal ; $(first message)"
+ ],
+ "codex fresh": [
+ "codex"
+ ],
+ "codex resume": [
+ "codex",
+ "resume",
+ "fixture-conversation"
+ ],
+ "codex fork": [
+ "codex",
+ "fork",
+ "fixture-parent"
+ ],
+ "codex permission": [
+ "codex",
+ "--approve-for-me",
+ "--model",
+ "fixture/model"
+ ],
+ "codex first": [
+ "codex",
+ "literal ; $(first message)"
+ ],
+ "cursor fresh": [
+ "cursor-agent"
+ ],
+ "cursor resume": [
+ "cursor-agent",
+ "--resume",
+ "fixture-conversation"
+ ],
+ "cursor fork": [
+ "cursor-agent"
+ ],
+ "cursor permission": [
+ "cursor-agent",
+ "--force",
+ "--model",
+ "fixture/model"
+ ],
+ "cursor first": {
+ "refused": "FirstPromptUnsupportedError",
+ "detail": "cursor has no documented way to start with a first prompt, so the agent was not created."
+ },
+ "opencode fresh": [
+ "opencode"
+ ],
+ "opencode resume": [
+ "opencode",
+ "--session",
+ "fixture-conversation"
+ ],
+ "opencode fork": [
+ "opencode"
+ ],
+ "opencode permission": [
+ "opencode",
+ "--auto",
+ "--model",
+ "fixture/model"
+ ],
+ "opencode first": [
+ "opencode",
+ "--prompt",
+ "literal ; $(first message)"
+ ],
+ "pi fresh": [
+ "pi"
+ ],
+ "pi resume": [
+ "pi",
+ "--session",
+ "fixture-conversation"
+ ],
+ "pi fork": [
+ "pi"
+ ],
+ "pi permission": [
+ "pi",
+ "--model",
+ "fixture/model"
+ ],
+ "pi first": {
+ "refused": "FirstPromptUnsupportedError",
+ "detail": "pi has no documented way to start with a first prompt, so the agent was not created."
+ },
+ "hermes fresh": [
+ "hermes"
+ ],
+ "hermes resume": [
+ "hermes",
+ "--resume",
+ "fixture-conversation"
+ ],
+ "hermes fork": [
+ "hermes"
+ ],
+ "hermes permission": [
+ "hermes",
+ "--model",
+ "fixture/model"
+ ],
+ "hermes first": [
+ "hermes",
+ "chat",
+ "-q",
+ "literal ; $(first message)"
+ ],
+ "commandcode fresh": [
+ "cmd"
+ ],
+ "commandcode resume": [
+ "cmd",
+ "--resume",
+ "fixture-conversation"
+ ],
+ "commandcode fork": [
+ "cmd"
+ ],
+ "commandcode permission": [
+ "cmd",
+ "--model",
+ "fixture/model"
+ ],
+ "commandcode first": {
+ "refused": "FirstPromptUnsupportedError",
+ "detail": "commandcode has no documented way to start with a first prompt, so the agent was not created."
+ },
+ "devin fresh": [
+ "devin"
+ ],
+ "devin resume": [
+ "devin",
+ "--resume",
+ "fixture-conversation"
+ ],
+ "devin fork": [
+ "devin"
+ ],
+ "devin permission": [
+ "devin",
+ "--model",
+ "fixture/model"
+ ],
+ "devin first": {
+ "refused": "FirstPromptUnsupportedError",
+ "detail": "devin has no documented way to start with a first prompt, so the agent was not created."
+ },
+ "muse fresh": [
+ "muse"
+ ],
+ "muse resume": [
+ "muse",
+ "resume",
+ "fixture-conversation"
+ ],
+ "muse fork": [
+ "muse"
+ ],
+ "muse permission": [
+ "muse",
+ "--model",
+ "fixture/model"
+ ],
+ "muse first": {
+ "refused": "FirstPromptUnsupportedError",
+ "detail": "muse has no documented way to start with a first prompt, so the agent was not created."
+ },
+ "amp fresh": [
+ "amp"
+ ],
+ "amp resume": [
+ "amp",
+ "threads",
+ "continue",
+ "fixture-conversation"
+ ],
+ "amp fork": [
+ "amp"
+ ],
+ "amp permission": [
+ "amp",
+ "--model",
+ "fixture/model"
+ ],
+ "amp first": {
+ "refused": "FirstPromptUnsupportedError",
+ "detail": "amp has no documented way to start with a first prompt, so the agent was not created."
+ },
+ "kilo fresh": [
+ "kilo"
+ ],
+ "kilo resume": [
+ "kilo",
+ "--session",
+ "fixture-conversation"
+ ],
+ "kilo fork": [
+ "kilo"
+ ],
+ "kilo permission": [
+ "kilo",
+ "--model",
+ "fixture/model"
+ ],
+ "kilo first": {
+ "refused": "FirstPromptUnsupportedError",
+ "detail": "kilo has no documented way to start with a first prompt, so the agent was not created."
+ },
+ "grok fresh": [
+ "grok"
+ ],
+ "grok resume": [
+ "grok",
+ "--resume",
+ "fixture-conversation"
+ ],
+ "grok fork": [
+ "grok"
+ ],
+ "grok permission": [
+ "grok",
+ "--model",
+ "fixture/model"
+ ],
+ "grok first": {
+ "refused": "FirstPromptUnsupportedError",
+ "detail": "grok has no documented way to start with a first prompt, so the agent was not created."
+ },
+ "agy fresh": [
+ "agy"
+ ],
+ "agy resume": [
+ "agy",
+ "--conversation",
+ "fixture-conversation"
+ ],
+ "agy fork": [
+ "agy"
+ ],
+ "agy permission": [
+ "agy",
+ "--model",
+ "fixture/model"
+ ],
+ "agy first": {
+ "refused": "FirstPromptUnsupportedError",
+ "detail": "agy has no documented way to start with a first prompt, so the agent was not created."
+ },
+ "copilot fresh": [
+ "copilot"
+ ],
+ "copilot resume": [
+ "copilot",
+ "--resume",
+ "fixture-conversation"
+ ],
+ "copilot fork": [
+ "copilot"
+ ],
+ "copilot permission": [
+ "copilot",
+ "--model",
+ "fixture/model"
+ ],
+ "copilot first": {
+ "refused": "FirstPromptUnsupportedError",
+ "detail": "copilot has no documented way to start with a first prompt, so the agent was not created."
+ },
+ "installation installed": {
+ "code": 0,
+ "trace": [
+ "engine",
+ "--prompt",
+ "literal ; $(first message)"
+ ],
+ "executable": true
+ },
+ "installation vendor": {
+ "code": 0,
+ "trace": [
+ "install:vendor",
+ "engine",
+ "--prompt",
+ "literal ; $(first message)"
+ ],
+ "executable": true
+ },
+ "installation fallback": {
+ "code": 0,
+ "trace": [
+ "primary",
+ "install:vendor",
+ "engine",
+ "--prompt",
+ "literal ; $(first message)"
+ ],
+ "executable": true
+ },
+ "installation npm": {
+ "code": 0,
+ "trace": [
+ "install:<root>/home/.local",
+ "engine",
+ "--prompt",
+ "literal ; $(first message)"
+ ],
+ "executable": true
+ }
+}
diff --git a/cli/src/engines/facets/hooks.ts b/cli/src/engines/facets/hooks.ts
index 39d625343..570da0cd1 100644
--- a/cli/src/engines/facets/hooks.ts
+++ b/cli/src/engines/facets/hooks.ts
@@ -1,4 +1,4 @@
-import type { HookPreparationOptions } from '../kit/nativeHookFiles.js'
+import type { NativeHookOptions } from '../kit/nativeLocations.js'
import type { Env } from '../../config/env.js'
import type { LiveEvent } from '../kit/events.js'
import type { LiveTurn } from './live.js'
@@ -125,8 +125,8 @@ export interface HookContract {
/** What core calls, composed from an engine's contract and the kit's mechanics (engines/hooks.ts). */
export interface EngineHooks {
- install(port: number, options?: HookPreparationOptions): Promise<boolean>
- installIn(port: number, home: string, options?: HookPreparationOptions): Promise<boolean>
+ install(port: number, options?: NativeHookOptions): Promise<boolean>
+ installIn(port: number, home: string, options?: NativeHookOptions): Promise<boolean>
transcriptFor?(body: HookSession, agent: HookSession | undefined): string | undefined
admit?(body: HookSession): HookAdmission
onStop?(context: HookTurnContext, body: HookStop): void | Promise<void>
diff --git a/cli/src/engines/kit/hookReview.ts b/cli/src/engines/kit/hookReview.ts
index 45fe49c18..cfd1fc116 100644
--- a/cli/src/engines/kit/hookReview.ts
+++ b/cli/src/engines/kit/hookReview.ts
@@ -50,15 +50,17 @@ export function reviewRecords(record: HookReviewRecord, settingsFile: string, se
for (const [event, label] of Object.entries(record.events)) {
const blocks = settings.hooks?.[event]
if (!Array.isArray(blocks)) continue
- const blockIndex = blocks.findIndex(harnessOwn)
- if (blockIndex < 0) continue
- const block = blocks[blockIndex]
- const hookIndex = block.hooks.findIndex((hook) => harnessOwn({ hooks: [hook] }))
- const hook = block.hooks[hookIndex]
- if (hook.type !== 'command' || typeof hook.command !== 'string') continue
- // A hook edited into a shape Harness does not write is one the engine reads its own way: it asks.
- if ((hook.timeout !== undefined && typeof hook.timeout !== 'number') || (block.matcher !== undefined && typeof block.matcher !== 'string')) continue
- records.set(`${settingsFile}:${label}:${blockIndex}:${hookIndex}`, reviewHash(record, event, block.matcher, hook))
+ // An optional Messages block can precede a required notify block. Approving
+ // only the first would report a prepared launch with SessionStart disabled.
+ for (const [blockIndex, block] of blocks.entries()) {
+ if (!harnessOwn(block)) continue
+ for (const [hookIndex, hook] of block.hooks.entries()) {
+ if (!harnessOwn({ hooks: [hook] }) || hook.type !== 'command' || typeof hook.command !== 'string') continue
+ // A hook edited into a shape Harness does not write is one the engine reads its own way: it asks.
+ if ((hook.timeout !== undefined && typeof hook.timeout !== 'number') || (block.matcher !== undefined && typeof block.matcher !== 'string')) continue
+ records.set(`${settingsFile}:${label}:${blockIndex}:${hookIndex}`, reviewHash(record, event, block.matcher, hook))
+ }
+ }
}
return records
}
diff --git a/cli/src/engines/kit/hookSettings.spec.ts b/cli/src/engines/kit/hookSettings.spec.ts
index 8872e742e..0bd2a2fb6 100644
--- a/cli/src/engines/kit/hookSettings.spec.ts
+++ b/cli/src/engines/kit/hookSettings.spec.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { homedir, tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
@@ -7,6 +7,10 @@ import { hooks as claude } from '../claude/hookContract.js'
import { hooks as codex } from '../codex/hookContract.js'
import { defaultHookHome, installHookSettings } from './hookSettings.js'
import { HOOK_SCRIPT } from './notifyHooks.js'
+import type { HookPreparationProof } from './nativeHookFiles.js'
+import { messagesCommand } from './messagesHook.js'
+import * as preparations from './nativeHookFiles.js'
+import { reviewHash, reviewRecords } from './hookReview.js'
// What every case writes and logs is engines/hookInstallers.golden.spec.ts; these are the kit's own edges.
let root = ''
@@ -21,6 +25,110 @@ it('finds an engine\'s home in the person\'s home or in a daemon setting', () =>
expect(defaultHookHome(codex.settings)).toBe(env.CODEX_HOME)
})
+it.each(['claude', 'codex'] as const)('publishes one current %s proof after both native and Agent Messages blocks', async engine => {
+ const settings = engine === 'claude' ? claude.settings : codex.settings
+ const home = join(root, engine), proofs: HookPreparationProof[] = []
+ expect(await installHookSettings(engine, settings, 19473, home, { confirmed: proof => { proofs.push(proof) } })).toBe(true)
+ expect(proofs).toHaveLength(1)
+ expect(proofs[0]!.current()).toBe(true)
+ const content = JSON.parse(readFileSync(join(home, settings.file), 'utf8'))
+ expect(content.hooks[settings.inbox!.event]?.some((block: { hooks: { command: string }[] }) => block.hooks.some(hook => hook.command === messagesCommand(env.HARNESS_AGENT_MESSAGES_DIR)))).toBe(true)
+})
+
+it.each(['both current', 'follower revoked', 'owner revoked'] as const)('joins the complete Messages stage with caller authority: %s', async state => {
+ const home = join(root, 'claude'), file = join(home, claude.settings.file)
+ const inspect = preparations.inspectHookFile
+ let enter!: () => void, release!: () => void
+ const entered = new Promise<void>(done => { enter = done })
+ const gate = new Promise<void>(done => { release = done })
+ let paused = false
+ vi.spyOn(preparations, 'inspectHookFile').mockImplementation((path, mode) => {
+ const observed = inspect(path, mode)
+ return { ...observed, replace: async (next, attempt, exclusive) => {
+ if (!paused && path === file && next.includes('harness-agent-messages')) {
+ paused = true; enter(); await gate
+ }
+ return observed.replace(next, attempt, exclusive)
+ } }
+ })
+ const proofs: HookPreparationProof[] = []
+ const options = { confirmed: (proof: HookPreparationProof) => { proofs.push(proof) } }
+ let owner = true, follower = true
+ const startup = installHookSettings('claude', claude.settings, 19473, home, { ...options, current: () => owner })
+ await entered
+ const launch = installHookSettings('claude', claude.settings, 19473, home, { ...options, current: () => follower })
+ if (state === 'follower revoked') follower = false
+ if (state === 'owner revoked') owner = false
+ release()
+ expect(await Promise.all([startup, launch])).toEqual(state === 'owner revoked' ? [false, false] : [true, follower])
+ expect(proofs).toHaveLength(state === 'owner revoked' ? 0 : follower ? 2 : 1)
+ expect(proofs.every(proof => proof.current())).toBe(true)
+ expect(readFileSync(file, 'utf8').includes('harness-agent-messages')).toBe(owner)
+})
+
+it.each(['peer edit', 'another port'] as const)('holds when %s changes required hook authority during publication', async change => {
+ const home = join(root, 'claude'), file = join(home, claude.settings.file)
+ const run = preparations.runHookPreparation
+ let intercepted = false, peerBytes = ''
+ vi.spyOn(preparations, 'runHookPreparation').mockImplementation((files, work, options) => run(files, attempt => work({
+ ...attempt, async flush(fd) {
+ await attempt.flush(fd)
+ if (!intercepted && existsSync(file)) {
+ intercepted = true
+ if (change === 'another port') expect(await installHookSettings('claude', claude.settings, 19474, home)).toBe(false)
+ else {
+ const settings = JSON.parse(readFileSync(file, 'utf8')); delete settings.hooks.SessionStart
+ writeFileSync(file, JSON.stringify(settings))
+ }
+ peerBytes = readFileSync(file, 'utf8')
+ }
+ },
+ }), options))
+ const confirmed = vi.fn()
+ expect(await installHookSettings('claude', claude.settings, 19473, home, { confirmed })).toBe(false)
+ expect(intercepted).toBe(true)
+ expect(confirmed).not.toHaveBeenCalled()
+ expect(readFileSync(file, 'utf8')).toBe(peerBytes)
+ if (change === 'another port') expect(await installHookSettings('claude', claude.settings, 19474, home)).toBe(true)
+})
+
+it('preserves marker-only commands and foreign siblings of the exact Messages hook without approving them', async () => {
+ const home = join(root, 'codex'); mkdirSync(home)
+ const foreign = { type: 'command', command: 'echo harness-agent-messages' }
+ const sibling = { type: 'command', command: 'echo my own hook' }
+ const owned = { type: 'command', command: messagesCommand('/fixture/old') }
+ const blocks = [{ hooks: [foreign] }, { matcher: 'custom', annotation: 'retain this', hooks: [owned, sibling] },
+ { hooks: [{ ...owned, command: owned.command + '; echo foreign' }] }]
+ const file = join(home, codex.settings.file), event = codex.settings.inbox!.event
+ writeFileSync(file, JSON.stringify({ hooks: { [event]: blocks } }))
+ expect(await installHookSettings('codex', codex.settings, 19473, home)).toBe(true)
+ const settings = JSON.parse(readFileSync(file, 'utf8'))
+ expect(settings.hooks[event].slice(0, 3)).toEqual([blocks[0], { ...blocks[1], hooks: [sibling] }, blocks[2]])
+ expect(settings.hooks[event][3].hooks[0].command).toBe(messagesCommand(env.HARNESS_AGENT_MESSAGES_DIR))
+ const records = [...reviewRecords(codex.settings.reviewed!, file, settings).keys()]
+ const label = codex.settings.reviewed!.events[event]
+ expect(records.filter(key => key.includes(`:${label}:`))).toEqual([`${file}:${label}:3:0`])
+})
+
+it('approves the required Codex hook when an earlier optional hook uses the same event', async () => {
+ const home = join(root, 'codex'); mkdirSync(home)
+ const previous = { hooks: [{ type: 'command', command: messagesCommand('/fixture/previous') }] }
+ const file = join(home, codex.settings.file)
+ writeFileSync(file, JSON.stringify({ hooks: { SessionStart: [previous] } }))
+ const confirmed = vi.fn()
+ expect(await installHookSettings('codex', codex.settings, 19473, home, { confirmed })).toBe(true)
+ const settings = JSON.parse(readFileSync(file, 'utf8'))
+ expect(settings.hooks.SessionStart[0]).toEqual(previous)
+ const required = settings.hooks.SessionStart[1]
+ expect(required.hooks[0].command).toContain('notify.mjs')
+ const config = readFileSync(join(home, codex.settings.reviewed!.file), 'utf8')
+ const key = `${realpathSync(file)}:session_start:1:0`
+ const hash = reviewHash(codex.settings.reviewed!, 'SessionStart', required.matcher, required.hooks[0])
+ expect(config).toContain(`[hooks.state.${JSON.stringify(key)}]\ntrusted_hash = ${JSON.stringify(hash)}`)
+ expect(confirmed).toHaveBeenCalledOnce()
+ expect(confirmed.mock.calls[0]![0].current()).toBe(true)
+})
+
it('names a home literally in its log lines, whatever characters the path holds', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
// `$&` and `$1` mean something to String.replace with a string replacement, and {port} to the templates.
diff --git a/cli/src/engines/kit/hookSettings.ts b/cli/src/engines/kit/hookSettings.ts
index f03bb5c3a..37cc4f977 100644
--- a/cli/src/engines/kit/hookSettings.ts
+++ b/cli/src/engines/kit/hookSettings.ts
@@ -12,7 +12,8 @@ import type { HookSettings } from '../facets/hooks.js'
import { prepareReviewed } from './hookReview.js'
import { isMessagesBlock, messagesCommand, writeMessagesHook } from './messagesHook.js'
import { command, HOOK_SCRIPT, isOurs, foreignHookBlocks, type Settings } from './notifyHooks.js'
-import { HookPreparationHeld, inspectHookFile, runHookPreparation, type HookPreparationOptions } from './nativeHookFiles.js'
+import { HookPreparationHeld, inspectHookFile, runHookPreparation, type HookPreparationAttempt } from './nativeHookFiles.js'
+import type { NativeHookOptions } from './nativeLocations.js'
/** The engines whose hooks run the notify.mjs command. */
export type HookEngine = Parameters<typeof command>[1]
@@ -22,111 +23,118 @@ export function defaultHookHome(settings: HookSettings): string {
return 'setting' in settings.home ? env[settings.home.setting] : join(homedir(), settings.home.inHome)
}
-export async function installHookSettings(engine: HookEngine, settings: HookSettings, port: number, home: string = defaultHookHome(settings), options: HookPreparationOptions = {}): Promise<boolean> {
- const ready = await installNotifyHooks(engine, settings, port, home, options)
- // Agent Messages' block after Harness's own, and never in its way: whatever becomes of it, the answer is the
- // notify hooks' (a Codex agent's create waits on it, core/agents/create.ts).
- if (ready && settings.inbox) await installMessagesBlock(settings, home, options)
- return ready
+export async function installHookSettings(engine: HookEngine, settings: HookSettings, port: number, home: string = defaultHookHome(settings), options: NativeHookOptions = {}): Promise<boolean> {
+ const files = [join(home, settings.file), ...(settings.reviewed ? [join(home, settings.reviewed.file)] : [])]
+ const cmd = command(port, engine, settings.commandNamesHome ? home : undefined, undefined, options.environment)
+ // A startup refresh and a launch share the entire installation. Releasing the
+ // reservation between notify and Messages let each revoke the other's second
+ // stage, so a healthy launch could be held by the daemon's own refresh.
+ try {
+ return await runHookPreparation(files, async attempt => {
+ await installNotifyHooks(engine, settings, port, home, options, attempt)
+ const required = files.map(file => inspectHookFile(file))
+ const verifyRequired = () => { attempt.verify(); for (const file of required) file.verify() }
+ if (settings.inbox) await installMessagesBlock(settings, home, attempt, verifyRequired)
+ return true
+ }, { ...options, identity: JSON.stringify([engine, settings, port, home, cmd, env.HARNESS_AGENT_MESSAGES_DIR]) })
+ } catch (err) {
+ console.error(settings.messages.failed.replace(/\{(file|script|port)\}/g, (_, name: string) =>
+ name === 'file' ? files[0] : name === 'script' ? HOOK_SCRIPT : String(port)), err)
+ return false
+ }
}
/**
* Agent Messages' block (kit/messagesHook.ts) in the engine's settings: exactly one, in its event, running the
* current command, every other block as it was; its script beside the inboxes; and for Codex, the block
- * recorded as reviewed like Harness's others. Its own preparation, after the notify hooks', so a file it
- * cannot write (read-only, held) costs only Agent Messages' delivery at a tool call: a message still reaches
- * an idle agent, typed. Says nothing unless it fails.
+ * recorded as reviewed like Harness's others. It shares their reservation and deadline. An optional
+ * failure is harmless only while the required hooks remain exactly as confirmed; an uncertain partial
+ * write holds launch. A message can still reach an idle agent, typed.
*/
-async function installMessagesBlock(settings: HookSettings, home: string, options: HookPreparationOptions): Promise<void> {
+async function installMessagesBlock(settings: HookSettings, home: string, attempt: HookPreparationAttempt, verifyRequired: () => void): Promise<void> {
const file = join(home, settings.file)
const root = env.HARNESS_AGENT_MESSAGES_DIR
const inboxCommand = messagesCommand(root)
const event = settings.inbox!.event
try {
- await runHookPreparation([file, ...(settings.reviewed ? [join(home, settings.reviewed.file)] : [])], async attempt => {
- const observed = inspectHookFile(file)
- const current = (observed.content === null ? {} : JSON.parse(observed.content)) as Settings
- if (!current || typeof current !== 'object' || Array.isArray(current) || !current.hooks || typeof current.hooks !== 'object'
- || Array.isArray(current.hooks) || (current.hooks[event] !== undefined && !Array.isArray(current.hooks[event]))) {
- throw new HookPreparationHeld('the hook settings do not have the declared object shape')
- }
- const blocks = current.hooks[event] ?? []
- const ours = blocks.filter(isMessagesBlock)
- const changed = ours.length !== 1 || ours[0].matcher !== undefined || ours[0].hooks?.length !== 1
- || ours[0].hooks[0]?.command !== inboxCommand || ours[0].hooks[0]?.timeout !== settings.timeout
- current.hooks[event] = [...blocks.filter((b) => !isMessagesBlock(b)), { hooks: [{ type: 'command', command: inboxCommand, timeout: settings.timeout }] }]
- const next = changed ? JSON.stringify(current, null, 2) + '\n' : observed.content!
- const reviewed = settings.reviewed ? prepareReviewed(settings.reviewed, home, file, JSON.parse(next) as Settings) : null
- reviewed?.verify()
- const published = await observed.replace(next, attempt)
- const approval = await reviewed?.commit(attempt)
- published.verify(); approval?.verify()
- writeMessagesHook(root)
- return true
- }, { ...options, identity: JSON.stringify(['agent-messages', settings, home, inboxCommand]) })
+ verifyRequired()
+ const observed = inspectHookFile(file)
+ const current = (observed.content === null ? {} : JSON.parse(observed.content)) as Settings
+ if (!current || typeof current !== 'object' || Array.isArray(current) || !current.hooks || typeof current.hooks !== 'object'
+ || Array.isArray(current.hooks) || (current.hooks[event] !== undefined && !Array.isArray(current.hooks[event]))) {
+ throw new HookPreparationHeld('the hook settings do not have the declared object shape')
+ }
+ const blocks = current.hooks[event] ?? []
+ const ours = blocks.filter(isMessagesBlock)
+ const changed = ours.length !== 1 || ours[0].matcher !== undefined || ours[0].hooks?.length !== 1
+ || ours[0].hooks[0]?.command !== inboxCommand || ours[0].hooks[0]?.timeout !== settings.timeout
+ current.hooks[event] = [...foreignHookBlocks(blocks, isMessagesBlock), { hooks: [{ type: 'command', command: inboxCommand, timeout: settings.timeout }] }]
+ const next = changed ? JSON.stringify(current, null, 2) + '\n' : observed.content!
+ const reviewed = settings.reviewed ? prepareReviewed(settings.reviewed, home, file, JSON.parse(next) as Settings) : null
+ reviewed?.verify()
+ const published = await observed.replace(next, attempt)
+ const approval = await reviewed?.commit(attempt)
+ published.verify(); approval?.verify()
+ writeMessagesHook(root)
} catch (err) {
console.warn(`[hooks] Agent Messages' hook not installed in ${file} (messages reach its agents once they are idle):`, err instanceof Error ? err.message : err)
+ verifyRequired()
}
}
-async function installNotifyHooks(engine: HookEngine, settings: HookSettings, port: number, home: string, options: HookPreparationOptions): Promise<boolean> {
+async function installNotifyHooks(engine: HookEngine, settings: HookSettings, port: number, home: string, options: NativeHookOptions, attempt: HookPreparationAttempt): Promise<boolean> {
const file = join(home, settings.file)
- const cmd = command(port, engine, settings.commandNamesHome ? home : undefined)
+ const cmd = command(port, engine, settings.commandNamesHome ? home : undefined, undefined, options.environment)
const say = (line: string): string => line.replace(/\{(file|script|port)\}/g, (_, name: string) =>
name === 'file' ? file : name === 'script' ? HOOK_SCRIPT : String(port))
const { messages } = settings
- try { return await runHookPreparation([file, ...(settings.reviewed ? [join(home, settings.reviewed.file)] : [])], async attempt => {
- const observed = inspectHookFile(file)
- const current = (observed.content === null ? {} : JSON.parse(observed.content)) as Settings
- if (!current || typeof current !== 'object' || Array.isArray(current)
- || (current.hooks !== undefined && (!current.hooks || typeof current.hooks !== 'object' || Array.isArray(current.hooks)))) {
- throw new HookPreparationHeld('the hook settings do not have the declared object shape')
- }
- current.hooks ??= {}
- let changed = false
- let updated = false // true when an EXISTING block's command changed (path/port drift)
+ const observed = inspectHookFile(file)
+ const current = (observed.content === null ? {} : JSON.parse(observed.content)) as Settings
+ if (!current || typeof current !== 'object' || Array.isArray(current)
+ || (current.hooks !== undefined && (!current.hooks || typeof current.hooks !== 'object' || Array.isArray(current.hooks)))) {
+ throw new HookPreparationHeld('the hook settings do not have the declared object shape')
+ }
+ current.hooks ??= {}
+ let changed = false
+ let updated = false // true when an EXISTING block's command changed (path/port drift)
- for (const { event, matcher } of settings.events) {
- if (current.hooks[event] !== undefined && !Array.isArray(current.hooks[event])) throw new HookPreparationHeld('a hook event is not a list')
- const blocks = current.hooks[event] ?? []
- // Collapse any duplicate "ours" blocks (e.g. from an earlier path) down to a single one, and keep every
- // non-ours block untouched.
- const foreign = foreignHookBlocks(blocks)
- const ours = blocks.filter(isOurs)
- if (ours.length !== 1) changed = true // none yet, or duplicates to drop
- const existing = ours[0]
- if (existing) {
- // A prior block with a different command (moved checkout / dev↔dist / changed port / interpreter) is
- // overwritten in place by the canonical one below.
- const existingCmd = settings.upToDate.command === 'first-ours'
- ? existing.hooks?.find((h) => isOurs({ hooks: [h] }))?.command
- : existing.hooks?.[0]?.command
- if (existingCmd !== cmd) { changed = true; updated = true }
- if (settings.upToDate.matcher && existing.matcher !== matcher) changed = true
- }
- current.hooks[event] = [...foreign, { ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command: cmd, timeout: settings.timeout }] }]
- }
-
- const next = changed ? JSON.stringify(current, null, 2) + '\n' : observed.content!
- const reviewed = settings.reviewed ? prepareReviewed(settings.reviewed, home, file, JSON.parse(next) as Settings) : null
- reviewed?.verify()
- if (!changed) {
- const published = await observed.replace(next, attempt)
- console.log(say(messages.current))
- // Installed by an earlier start, or by a release before the engine asked: recorded now, as the file has it.
- const approval = await reviewed?.commit(attempt)
- published.verify(); approval?.verify()
- return true
+ for (const { event, matcher } of settings.events) {
+ if (current.hooks[event] !== undefined && !Array.isArray(current.hooks[event])) throw new HookPreparationHeld('a hook event is not a list')
+ const blocks = current.hooks[event] ?? []
+ // Collapse any duplicate "ours" blocks (e.g. from an earlier path) down to a single one, and keep every
+ // non-ours block untouched.
+ const foreign = foreignHookBlocks(blocks)
+ const ours = blocks.filter(isOurs)
+ if (ours.length !== 1) changed = true // none yet, or duplicates to drop
+ const existing = ours[0]
+ if (existing) {
+ // A prior block with a different command (moved checkout / dev↔dist / changed port / interpreter) is
+ // overwritten in place by the canonical one below.
+ const existingCmd = settings.upToDate.command === 'first-ours'
+ ? existing.hooks?.find((h) => isOurs({ hooks: [h] }))?.command
+ : existing.hooks?.[0]?.command
+ if (existingCmd !== cmd) { changed = true; updated = true }
+ if (settings.upToDate.matcher && existing.matcher !== matcher) changed = true
}
+ current.hooks[event] = [...foreign, { ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command: cmd, timeout: settings.timeout }] }]
+ }
+ const next = changed ? JSON.stringify(current, null, 2) + '\n' : observed.content!
+ const reviewed = settings.reviewed ? prepareReviewed(settings.reviewed, home, file, JSON.parse(next) as Settings) : null
+ reviewed?.verify()
+ if (!changed) {
const published = await observed.replace(next, attempt)
- console.log(say(updated && messages.updated ? messages.updated : messages.installed))
- console.log(say(messages.after))
+ console.log(say(messages.current))
+ // Installed by an earlier start, or by a release before the engine asked: recorded now, as the file has it.
const approval = await reviewed?.commit(attempt)
published.verify(); approval?.verify()
return true
- }, { ...options, identity: JSON.stringify([engine, settings, port, home, cmd]) }) } catch (err) {
- console.error(say(messages.failed), err)
- return false
}
+
+ const published = await observed.replace(next, attempt)
+ console.log(say(updated && messages.updated ? messages.updated : messages.installed))
+ console.log(say(messages.after))
+ const approval = await reviewed?.commit(attempt)
+ published.verify(); approval?.verify()
+ return true
}
diff --git a/cli/src/engines/kit/launchEnvironment.spec.ts b/cli/src/engines/kit/launchEnvironment.spec.ts
new file mode 100644
index 000000000..804bcce12
--- /dev/null
+++ b/cli/src/engines/kit/launchEnvironment.spec.ts
@@ -0,0 +1,24 @@
+import { afterEach, expect, it, vi } from 'vitest'
+import { execFile } from 'node:child_process'
+import { launchEnvironment } from './launchExecutable.js'
+
+vi.mock('../../lib/engineLaunch.js', () => ({
+ interactiveEngineShell: () => ({ path: '/fixture/login-shell', args: ['-ic'], label: 'fixture shell' }),
+ engineShellArgv: (shell: { path: string; args: string[] }, args: string[]) => [shell.path, ...shell.args, ...args],
+}))
+vi.mock('../../lib/nodeRuntime.js', () => ({ managedNodePath: () => '/fixture/node' }))
+vi.mock('node:child_process', () => ({ execFile: vi.fn((_file, _args, _options, done) => {
+ queueMicrotask(() => done(null, '__HARNESS_LAUNCH_ENV__' + JSON.stringify({
+ HOME: '/fixture/home', PATH: '/fixture/bin', CODEX_HOME: '/fixture/moved-codex',
+ })))
+ return { stdin: { end: vi.fn() } }
+}) }))
+afterEach(() => { vi.unstubAllEnvs(); vi.clearAllMocks() })
+
+it('captures the actual launch shell for an isolated daemon running with NODE_ENV=test', async () => {
+ vi.stubEnv('NODE_ENV', 'test')
+ vi.stubEnv('CODEX_HOME', '/fixture/daemon-codex')
+ expect(await launchEnvironment()).toEqual({ HOME: '/fixture/home', PATH: '/fixture/bin', CODEX_HOME: '/fixture/moved-codex' })
+ expect(execFile).toHaveBeenCalledWith('/fixture/login-shell', expect.any(Array),
+ expect.objectContaining({ timeout: 5_000, maxBuffer: 64 * 1024 }), expect.any(Function))
+})
diff --git a/cli/src/engines/kit/launchExecutable.spec.ts b/cli/src/engines/kit/launchExecutable.spec.ts
new file mode 100644
index 000000000..05fc2bf6f
--- /dev/null
+++ b/cli/src/engines/kit/launchExecutable.spec.ts
@@ -0,0 +1,52 @@
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync, symlinkSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { 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 = '' })
+async function fixture() {
+ root = mkdtempSync(join(tmpdir(), 'launch-executable-'))
+ const bin = join(root, 'bin'); mkdirSync(bin)
+ vi.stubEnv('HOME', root); vi.stubEnv('PATH', bin); vi.stubEnv('OPENCODE_PATH', '')
+ vi.resetModules()
+ return { bin, ...await import('./launchExecutable.js') }
+}
+it('captures an absolute executable once and detects its replacement', async () => {
+ const { bin, captureLaunchExecutable } = await fixture()
+ const file = join(bin, 'opencode'); writeFileSync(file, 'fixture', { mode: 0o700 })
+ const result = await captureLaunchExecutable('opencode', '')
+ expect(result.state).toBe('ready')
+ if (result.state !== 'ready') throw new Error('fixture was held')
+ expect(result.executable.command).toBe(file)
+ expect(result.executable.current()).toBe(true)
+ writeFileSync(file, 'upgraded fixture')
+ expect(result.executable.current()).toBe(false)
+})
+it('distinguishes complete absence from inaccessible or ambiguous candidates', async () => {
+ const { bin, captureLaunchExecutable } = await fixture()
+ expect(await captureLaunchExecutable('opencode', '')).toMatchObject({ state: 'install' })
+ const file = join(bin, 'opencode'); writeFileSync(file, 'fixture'); chmodSync(file, 0o600)
+ expect(await captureLaunchExecutable('opencode', '')).toMatchObject({ state: 'held' })
+ rmSync(file); mkdirSync(file)
+ expect(await captureLaunchExecutable('opencode', '')).toMatchObject({ state: 'held' })
+ vi.stubEnv('PATH', 'relative')
+ expect(await captureLaunchExecutable('opencode', '')).toMatchObject({ state: 'held' })
+})
+it('never installs over an explicitly configured missing executable', async () => {
+ await fixture()
+ vi.stubEnv('OPENCODE_PATH', join(root, 'absent'))
+ vi.resetModules()
+ const { captureLaunchExecutable } = await import('./launchExecutable.js')
+ expect(await captureLaunchExecutable('opencode', '')).toMatchObject({ state: 'held' })
+})
+
+it('holds dangling command aliases instead of authorizing an installation over them', async () => {
+ const { bin, captureLaunchExecutable } = await fixture()
+ symlinkSync(join(root, 'unavailable-engine'), join(bin, 'opencode'))
+ expect(await captureLaunchExecutable('opencode', '')).toMatchObject({ state: 'held' })
+})
+it('permits complete absence through a valid search-directory alias', async () => {
+ const { bin, captureLaunchExecutable } = await fixture()
+ const alias = join(root, 'path-alias'); symlinkSync(bin, alias); vi.stubEnv('PATH', alias)
+ expect(await captureLaunchExecutable('opencode', '')).toMatchObject({ state: 'install' })
+})
diff --git a/cli/src/engines/kit/launchExecutable.ts b/cli/src/engines/kit/launchExecutable.ts
new file mode 100644
index 000000000..14e3bbe38
--- /dev/null
+++ b/cli/src/engines/kit/launchExecutable.ts
@@ -0,0 +1,96 @@
+/** 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 { engineBin, enginePathOverride } from '../../lib/engineBin.js'
+import { engineInstallPaths, engineInstallRecipe, type EngineInstallRecipe } from '../../lib/engineInstall.js'
+import { engineShellArgv, interactiveEngineShell } from '../../lib/engineLaunch.js'
+import { managedNodePath } from '../../lib/nodeRuntime.js'
+import { shellSingleQuote } from '../../lib/shellQuote.js'
+import { LAUNCH_LOCATION_VARIABLES } from './nativeLocations.js'
+import type { AgentEngine } from '../types.js'
+import { NativeEvidenceBudget } from './nativeEvidence.js'
+import { NativePaths } from './nativePaths.js'
+import { executableSnapshot, nativeVersionProbe, type NativeExecutableSnapshot } from './nativeVersion.js'
+
+export type LaunchExecutableResult =
+ | { state: 'ready'; executable: NativeExecutableSnapshot; environment: NodeJS.ProcessEnv }
+ | { state: 'install'; recipe: EngineInstallRecipe; environment: Record<string, string> }
+ | { state: 'held'; detail: string }
+const held = (detail: string): LaunchExecutableResult => ({ state: 'held', detail })
+const ENV_MARKER = '__HARNESS_LAUNCH_ENV__'
+export { LAUNCH_LOCATION_VARIABLES } from './nativeLocations.js'
+const pickLocations = (environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv => Object.fromEntries(
+ LAUNCH_LOCATION_VARIABLES.filter(key => environment[key] !== undefined).map(key => [key, environment[key]]),
+)
+let probing = 0
+const MAX_PROBES = 8
+
+/** No unavailable or negative shell answer is cached. A slot belongs to the
+ * actual child until its callback, including timeout/oversized-output kills. */
+export async function launchEnvironment(shell?: string): Promise<NodeJS.ProcessEnv | null> {
+ const interactive = interactiveEngineShell(shell)
+ if (!interactive) return pickLocations(process.env)
+ if (probing >= MAX_PROBES) return null
+ const code = `process.stdout.write(${JSON.stringify(ENV_MARKER)}+JSON.stringify(Object.fromEntries(${JSON.stringify(LAUNCH_LOCATION_VARIABLES)}.filter(k=>process.env[k]!==undefined).map(k=>[k,process.env[k]]))))`
+ const argv = engineShellArgv(interactive, [`exec ${shellSingleQuote(managedNodePath())} -e ${shellSingleQuote(code)}`, 'harness-launch-environment'])
+ probing++
+ return new Promise(done => {
+ try {
+ const child = execFile(argv[0], argv.slice(1), { encoding: 'utf8', timeout: 5_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 }, (error, output) => {
+ probing--
+ if (error) { done(null); return }
+ try {
+ const marker = output.lastIndexOf(ENV_MARKER)
+ if (marker < 0) { done(null); return }
+ const value: unknown = JSON.parse(output.slice(marker + ENV_MARKER.length))
+ if (!value || typeof value !== 'object' || Array.isArray(value)
+ || Object.values(value).some(item => typeof item !== 'string' || item.includes('\0'))) { done(null); return }
+ done(pickLocations(value as NodeJS.ProcessEnv))
+ } catch { done(null) }
+ })
+ child.stdin?.end()
+ } catch { probing--; done(null) }
+ })
+}
+
+/** A complete absence can authorize installation. Unreadable routes and failed
+ * shell capture cannot: installing then would risk replacing a working engine. */
+export async function captureLaunchExecutable(engine: AgentEngine, shell?: string): Promise<LaunchExecutableResult> {
+ const environment = await launchEnvironment(shell)
+ if (!environment || !environment.HOME || !isAbsolute(environment.HOME)) return held('Waiting to read the engine’s launch environment.')
+ const command = engineBin(engine), override = enginePathOverride(engine)
+ const entries = environment.PATH?.split(delimiter) ?? []
+ if (entries.length === 0 || entries.length > 256 || entries.some(path => !isAbsolute(path) || path.length > 4096)) {
+ return held('Waiting for a bounded, absolute engine search path.')
+ }
+ const recipe = override ? undefined : engineInstallRecipe(engine)
+ const names = [...new Set([command, ...(recipe?.executable.names ?? [])])]
+ const candidates = command.includes('/') ? [resolve(command)] : names.flatMap(name => entries.map(path => join(path, name)))
+ if (recipe) candidates.push(...engineInstallPaths(recipe, environment.HOME))
+ for (const path of [...new Set(candidates)]) {
+ try {
+ const info = statSync(path)
+ if (!info.isFile()) return held('Waiting for the selected engine path to name an executable file.')
+ accessSync(path, constants.X_OK)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ try {
+ const paths = new NativePaths(new NativeEvidenceBudget(250))
+ if (paths.resolveSync(path, true)) return held('Waiting for the engine search path to stop changing.')
+ // A dangling executable/ancestor alias is an existing user choice,
+ // not evidence that installation is safe. Ordinary missing folders
+ // and missing descendants of valid aliases still prove absence.
+ for (const fact of paths.snapshot()) if (fact.alias) statSync(fact.path)
+ paths.verify()
+ } catch { return held('Waiting to confirm the engine search path and its aliases.') }
+ continue
+ }
+ return held('Waiting to confirm access to the selected engine executable.')
+ }
+ 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 recipe ? { state: 'install', recipe, environment: environment as Record<string, string> } : held('Waiting for the configured engine executable to become available.')
+}
diff --git a/cli/src/engines/kit/messagesHook.spec.ts b/cli/src/engines/kit/messagesHook.spec.ts
new file mode 100644
index 000000000..2f04fdd80
--- /dev/null
+++ b/cli/src/engines/kit/messagesHook.spec.ts
@@ -0,0 +1,20 @@
+import { expect, it } from 'vitest'
+import { isMessagesBlock, isMessagesCommand, messagesCommand } from './messagesHook.js'
+
+it.each(['/fixture/messages', "/fixture/space and ' quote"])('recognizes the complete literal Messages protocol at %s', root => {
+ const command = messagesCommand(root, '/fixture/runtime/node')
+ expect(isMessagesCommand(command)).toBe(true)
+ expect(isMessagesBlock({ hooks: [{ type: 'command', command }] })).toBe(true)
+ expect(isMessagesBlock({ hooks: [{ type: 'prompt', command }] })).toBe(false)
+ expect(isMessagesCommand(command + '; echo foreign')).toBe(false)
+ expect(isMessagesCommand(command.replace('--root', '--unrelated'))).toBe(false)
+})
+
+it('never infers ownership from a marker, basename, unrelated script or shell expansion', () => {
+ const command = messagesCommand('/fixture/messages', '/fixture/runtime/node')
+ for (const value of [null, '', 'echo harness-agent-messages', command.replace('/hook.mjs', '/foreign.mjs'),
+ command.replace('/fixture/runtime/node', '/fixture/runtime/foreign'), command.replace("'/fixture/runtime/node'", '$(find-node)'),
+ messagesCommand('relative', '/fixture/runtime/node'), command + '\0', 'x'.repeat(65537)]) {
+ expect(isMessagesCommand(value), String(value).slice(0, 120)).toBe(false)
+ }
+})
diff --git a/cli/src/engines/kit/messagesHook.ts b/cli/src/engines/kit/messagesHook.ts
index a7ecf8a37..1c53f3568 100644
--- a/cli/src/engines/kit/messagesHook.ts
+++ b/cli/src/engines/kit/messagesHook.ts
@@ -18,7 +18,7 @@
* agent's messages.
*/
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
-import { join } from 'node:path'
+import { basename, isAbsolute, join } from 'node:path'
import { managedNodePath } from '../../lib/nodeRuntime.js'
import type { HookBlock } from './notifyHooks.js'
@@ -95,15 +95,27 @@ function shellQuote(value: string): string {
}
/** The command an engine runs at each tool call: a shell test first, Node only when something waits. */
-export function messagesCommand(root: string): string {
+export function messagesCommand(root: string, node: string = managedNodePath()): string {
const script = join(root, 'hook.mjs')
return `p=${shellQuote(join(root, 'inbox'))}/"\${TMUX_PANE#%}"; [ -n "\${TMUX_PANE:-}" ] && [ -d "$p" ] || exit 0; `
- + `${shellQuote(managedNodePath())} ${shellQuote(script)} --root ${shellQuote(root)}; exit 0 # ${MESSAGES_HOOK_MARK}`
+ + `${shellQuote(node)} ${shellQuote(script)} --root ${shellQuote(root)}; exit 0 # ${MESSAGES_HOOK_MARK}`
+}
+
+/** Only the complete literal command we publish is ours to replace or approve.
+ * A marker in somebody else's script, or a shell suffix, grants no ownership. */
+export function isMessagesCommand(value: unknown): boolean {
+ if (typeof value !== 'string' || value.length > 64 * 1024 || value.includes('\0')) return false
+ const words = value.match(/'(?:[^']|'\\'')*'/g)
+ if (words?.length !== 4) return false
+ const [inbox, node, script, root] = words.map(word => word.slice(1, -1).replace(/'\\''/g, "'"))
+ if (![inbox, node, script, root].every(isAbsolute) || !/^(?:node|nodejs)(?:\.exe)?$/.test(basename(node))
+ || inbox !== join(root, 'inbox') || script !== join(root, 'hook.mjs')) return false
+ return value === messagesCommand(root, node)
}
/** Whether a block is Agent Messages' own. */
export function isMessagesBlock(block: HookBlock): boolean {
- return Array.isArray(block?.hooks) && block.hooks.some((h) => typeof h?.command === 'string' && h.command.includes(MESSAGES_HOOK_MARK))
+ return Array.isArray(block?.hooks) && block.hooks.some(hook => hook?.type === 'command' && isMessagesCommand(hook.command))
}
/** Write the script where the command runs it, when it is not already there as it should be. */
diff --git a/cli/src/engines/kit/nativeHookFiles.ts b/cli/src/engines/kit/nativeHookFiles.ts
index ec183c8a9..8aa33fec3 100644
--- a/cli/src/engines/kit/nativeHookFiles.ts
+++ b/cli/src/engines/kit/nativeHookFiles.ts
@@ -1,7 +1,7 @@
/** Hook preparation owns only a verified file version. Unknown contents are
* never an empty configuration, and a completed write includes its directory. */
import { randomUUID } from 'node:crypto'
-import { accessSync, closeSync, constants, fchmodSync, fstatSync, fsync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync, type BigIntStats } from 'node:fs'
+import { accessSync, closeSync, constants, fchmodSync, fstatSync, fsync, linkSync, lstatSync, mkdirSync, openSync, readSync, renameSync, unlinkSync, writeFileSync, type BigIntStats } from 'node:fs'
import { basename, dirname, join } from 'node:path'
import { NativeEvidenceBudget } from './nativeEvidence.js'
import { NativePaths, verifyNativePathFacts } from './nativePaths.js'
@@ -132,8 +132,9 @@ export function inspectHookFile(file: string, defaultMode = 0o666) {
return {
content, directory, stamp: before,
verify, prepare,
- async replace(next: string, attempt: HookPreparationAttempt): Promise<HookFilePublication> {
+ async replace(next: string, attempt: HookPreparationAttempt, exclusive = false): Promise<HookFilePublication> {
attempt.verify(); prepare(next)
+ if (exclusive && content !== null) throw new HookPreparationHeld('another owner already published this claim')
if (content === next) {
// A previous rename may have succeeded before directory sync failed.
// Equality alone cannot turn that uncertainty into a durable success.
@@ -174,7 +175,8 @@ export function inspectHookFile(file: string, defaultMode = 0o666) {
// route; only directories created above can replace an absent fact.
verifyNativePathFacts(facts.filter(fact => fact.identity !== null))
attempt.verify()
- renameSync(temporary, actual)
+ if (exclusive) { linkSync(temporary, actual); unlinkSync(temporary) }
+ else renameSync(temporary, actual)
const committed = inspectHookFile(file)
if (committed.content !== next || committed.stamp !== version(fstatSync(fd, { bigint: true }))) {
throw new HookPreparationHeld('the published settings changed before sync')
@@ -234,6 +236,8 @@ export interface HookPreparationOptions {
identity?: string
current?(): boolean
timeoutMs?: number
+ /** Immutable effect claims must let a competing publisher finish. */
+ retainConflicts?: boolean
/** Evidence retained by this launch; never a global success cache. */
confirmed?(proof: HookPreparationProof): void
}
@@ -292,9 +296,8 @@ function dispatchFlushes(): void {
}
}
-/** Disk waits remain in eager core code. Reservations survive a timeout until
- * actual I/O settles: a late fsync must never use a closed, recycled descriptor. */
-export async function runHookPreparation<T>(files: readonly string[], work: (attempt: HookPreparationAttempt) => Promise<T>, options: HookPreparationOptions = {}): Promise<T> {
+/** A caller keeps its own aliases even when it later follows a newer publisher. */
+export function hookPreparationRoutes(files: readonly string[]): { verify(): void; keys: string[]; facts: ReturnType<NativePaths['snapshot']> } {
if (!files.length || files.length > 32) throw new HookPreparationHeld('the destination set exceeds its limit')
const reservations = files.map(file => {
const paths = new NativePaths(new NativeEvidenceBudget(250))
@@ -314,12 +317,19 @@ export async function runHookPreparation<T>(files: readonly string[], work: (att
}
}
const keys = [...new Set(reservations.map(reservation => reservation.key))].sort()
+ return { verify: verifyRoutes, keys, facts: [...new Map(reservations.flatMap(item => item.facts).map(fact => [fact.path, fact])).values()] }
+}
+
+/** Disk waits remain in eager core code. Reservations survive a timeout until
+ * actual I/O settles: a late fsync must never use a closed, recycled descriptor. */
+export async function runHookPreparation<T>(files: readonly string[], work: (attempt: HookPreparationAttempt) => Promise<T>, options: HookPreparationOptions = {}): Promise<T> {
+ const { verify: verifyRoutes, keys } = hookPreparationRoutes(files)
const conflicts = [...pendingPreparations].filter(pending => pending.keys.some(key => keys.includes(key)))
if (conflicts.length) {
const same = conflicts.length === 1 && options.identity !== undefined && conflicts[0].identity === options.identity
&& JSON.stringify(conflicts[0].keys) === JSON.stringify(keys)
if (same) return await joinPreparation<T>(conflicts[0], options, verifyRoutes, files)
- for (const pending of conflicts) pending.revoke()
+ if (!options.retainConflicts) for (const pending of conflicts) pending.revoke()
throw new HookPreparationHeld('another preparation still owns these destinations')
}
if (pendingPreparations.size >= MAX_PREPARATIONS) throw new HookPreparationHeld('the disk preparation slots are occupied')
diff --git a/cli/src/engines/kit/nativeHookSettings.ts b/cli/src/engines/kit/nativeHookSettings.ts
index 5895dfdc8..6b80d5c4e 100644
--- a/cli/src/engines/kit/nativeHookSettings.ts
+++ b/cli/src/engines/kit/nativeHookSettings.ts
@@ -1,6 +1,7 @@
/** Eager mechanics for native JSON hook schemas; unreadable settings are never empty settings. */
import { command, isOurs, isManagedHookCommand, foreignHookBlocks, type Settings, type HookBlock } from './notifyHooks.js'
-import { HookPreparationHeld, inspectHookFile, runHookPreparation, type HookPreparationOptions } from './nativeHookFiles.js'
+import { HookPreparationHeld, inspectHookFile, runHookPreparation } from './nativeHookFiles.js'
+import type { NativeHookOptions } from './nativeLocations.js'
export interface NativeHookSettings {
file: string
@@ -28,8 +29,8 @@ function entries(value: unknown): Entry[] {
return value
}
-export async function installNativeHookSettings(rule: NativeHookSettings, port: number, options: HookPreparationOptions = {}): Promise<boolean> {
- const cmd = command(port, rule.engine)
+export async function installNativeHookSettings(rule: NativeHookSettings, port: number, options: NativeHookOptions = {}): Promise<boolean> {
+ const cmd = command(port, rule.engine, undefined, undefined, options.environment)
try { return await runHookPreparation([rule.file], async attempt => {
const observed = inspectHookFile(rule.file)
const parsed: unknown = observed.content === null ? {} : JSON.parse(observed.content)
diff --git a/cli/src/engines/kit/nativeHookYaml.ts b/cli/src/engines/kit/nativeHookYaml.ts
index 137449904..6e718ec9f 100644
--- a/cli/src/engines/kit/nativeHookYaml.ts
+++ b/cli/src/engines/kit/nativeHookYaml.ts
@@ -112,7 +112,7 @@ function stripOwnedBlocks(rule: NativeYamlHooks, config: string, hookLines: Read
}
/** Installs only homes with a config, each with its own command and allowlist. */
-export async function installNativeYamlHooks(rule: NativeYamlHooks, commandForHome: (home: string) => string, selectedHome?: string, options: HookPreparationOptions = {}): Promise<boolean> {
+export async function installNativeYamlHooks(rule: NativeYamlHooks, commandForHome: (home: string) => string, selectedHome?: string, options: HookPreparationOptions & { createMissing?: boolean } = {}): Promise<boolean> {
const homes = selectedHome ? [selectedHome] : nativeHookHomes(rule.homes, rule.home)
let next = 0, installed = true
const worker = async () => {
@@ -127,14 +127,17 @@ export async function installNativeYamlHooks(rule: NativeYamlHooks, commandForHo
return installed
}
-async function installIn(rule: NativeYamlHooks, cmd: string, home: string, options: HookPreparationOptions): Promise<boolean> {
+async function installIn(rule: NativeYamlHooks, cmd: string, home: string, options: HookPreparationOptions & { createMissing?: boolean }): Promise<boolean> {
const configPath = join(home, rule.homes.file)
try { return await runHookPreparation([configPath, join(home, rule.allowlist)], async attempt => {
- const observed = inspectHookFile(configPath), config = observed.content
- if (config === null) {
+ const observed = inspectHookFile(configPath)
+ if (observed.content === null && !options.createMissing) {
if (home === rule.home) console.log(message(rule.messages.missing, { file: configPath }))
return false
}
+ // A captured launch owns preparation of its selected home, including its
+ // first settings file. A background catalog scan never creates a profile.
+ const config = observed.content ?? ''
const budget = new NativeEvidenceBudget(250)
let tokens = 0
diff --git a/cli/src/engines/kit/nativeInstall.spec.ts b/cli/src/engines/kit/nativeInstall.spec.ts
new file mode 100644
index 000000000..a318a56a9
--- /dev/null
+++ b/cli/src/engines/kit/nativeInstall.spec.ts
@@ -0,0 +1,347 @@
+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 { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { EngineInstallRecipe } from '../../lib/engineInstall.js'
+import { createNativeInstallations, NATIVE_INSTALL_WORKER } from './nativeInstall.js'
+
+const fixture = vi.hoisted(() => ({ failSync: false, argv: [] as string[], onSync: undefined as undefined | (() => number | void) }))
+vi.mock('../../lib/engineLaunch.js', () => ({ buildEngineInstallationArgv: () => fixture.argv }))
+vi.mock('node:fs', async original => ({ ...await original<typeof import('node:fs')>(),
+ fsync: (_fd: number, done: (error: Error | null) => void) => {
+ const delay = fixture.onSync?.()
+ const finish = () => done(fixture.failSync ? Error('fixture unavailable disk') : null)
+ if (delay) setTimeout(finish, delay); else queueMicrotask(finish)
+ },
+}))
+const hash = (text: string) => createHash('sha256').update(text).digest('hex')
+const recipe: EngineInstallRecipe = { command: 'fixture-only', source: 'fixture', executable: { names: ['fixture'] } }
+let root: string, directory: string, environment: Record<string, string>
+beforeEach(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'native-install-')))
+ directory = join(root, 'claims')
+ const home = join(root, 'home'); mkdirSync(home, { mode: 0o700 })
+ environment = { HOME: home, PATH: '/usr/bin:/bin' }
+ fixture.failSync = false; fixture.onSync = undefined
+ fixture.argv = [process.execPath, '-e', `require('node:fs').appendFileSync(${JSON.stringify(join(root, 'installed'))}, 'one\\n')`]
+})
+afterEach(() => { rmSync(root, { recursive: true, force: true }); vi.restoreAllMocks() })
+const controller = (dispatch = vi.fn()) => ({ dispatch, ...createNativeInstallations({ directory, node: () => process.execPath, dispatch }) })
+function complete(file = join(directory, '00000000.json'), code = 0): void {
+ const text = readFileSync(file, 'utf8'), claim = JSON.parse(text)
+ writeFileSync(`${file}.result`, JSON.stringify({ token: claim.token, claim: hash(text), code, signal: null }), { mode: 0o600 })
+}
+
+it('does not reserve or dispatch after cancellation', async () => {
+ const install = controller()
+ expect(await install.ensure('opencode', recipe, environment, 'request', () => false)).toMatchObject({ complete: false })
+ expect(existsSync(directory)).toBe(false)
+ expect(install.dispatch).not.toHaveBeenCalled()
+})
+
+it('reads installation obligations after reconstruction without creating a missing history', async () => {
+ const install = controller()
+ expect(await install.status('opencode', 'request', () => true)).toBeNull()
+ expect(existsSync(directory)).toBe(false)
+ expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(await controller().status('opencode', 'request', () => true)).toMatchObject({ complete: false })
+ expect(await controller().status('codex', 'unrelated', () => true)).toBeNull()
+ complete()
+ expect(await controller().status('opencode', 'request', () => true)).toEqual({ complete: true })
+ expect(await controller().status('opencode', 'new-request', () => true)).toBeNull()
+ expect(install.dispatch).toHaveBeenCalledOnce()
+})
+
+it('confirms missing installation history through a stable parent alias and recovers its later result', async () => {
+ const physical = join(root, 'physical'), alias = join(root, 'alias')
+ mkdirSync(physical, { mode: 0o700 }); symlinkSync(physical, alias)
+ directory = join(alias, 'claims')
+ const install = controller()
+ expect(await install.status('opencode', 'request', () => true)).toBeNull()
+ expect(existsSync(directory)).toBe(false)
+ await install.ensure('opencode', recipe, environment, 'request', () => true)
+ expect(install.dispatch).toHaveBeenCalledOnce()
+ complete()
+ expect(await controller().status('opencode', 'request', () => true)).toEqual({ complete: true })
+})
+
+it('does not treat a dangling authority leaf as missing through a parent alias', async () => {
+ const physical = join(root, 'physical'), alias = join(root, 'alias')
+ mkdirSync(physical, { mode: 0o700 }); symlinkSync(physical, alias)
+ directory = join(alias, 'claims')
+ symlinkSync(join(physical, 'missing-authority'), `${directory}.authority`)
+ const install = controller()
+ expect(await install.status('opencode', 'request', () => true)).toMatchObject({ complete: false })
+ expect(existsSync(directory)).toBe(false)
+ expect(install.dispatch).not.toHaveBeenCalled()
+})
+
+it('holds a failed installation across different request IDs and a reconstructed core', 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 })
+ expect(await controller().status('codex', 'unrelated-request', () => true)).toBeNull()
+ expect(install.dispatch).toHaveBeenCalledOnce()
+})
+
+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 })
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+ expect(readdirSync(directory).sort()).toEqual(['00000000.json', '00000000.json.dispatch'])
+ expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ const restarted = controller()
+ expect(await restarted.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(restarted.dispatch).not.toHaveBeenCalled()
+ complete()
+ expect(await restarted.ensure('opencode', recipe, environment, 'request', () => true)).toEqual({ complete: true })
+ expect(restarted.dispatch).not.toHaveBeenCalled()
+})
+
+it('serializes different requests and engines while an installer owns a shared prefix', async () => {
+ const first = controller(), other = controller()
+ const result = await Promise.all([
+ first.ensure('opencode', recipe, environment, 'one', () => true),
+ other.ensure('codex', recipe, environment, 'two', () => true),
+ ])
+ expect(result.every(value => !value.complete)).toBe(true)
+ expect(first.dispatch.mock.calls.length + other.dispatch.mock.calls.length).toBe(1)
+ const claim = JSON.parse(readFileSync(join(directory, '00000000.json'), 'utf8'))
+ complete()
+ const engine = claim.engine === 'opencode' ? 'codex' : 'opencode'
+ const request = claim.request === 'one' ? 'two' : 'one'
+ expect(await other.ensure(engine, recipe, environment, request, () => true)).toMatchObject({ complete: false })
+ expect(readdirSync(directory).sort()).toEqual(['00000000.json', '00000000.json.dispatch', '00000000.json.result', '00000001.json', '00000001.json.dispatch'])
+})
+
+it('never dispatches an unconfirmed claim and can recover before any publication', async () => {
+ const install = controller()
+ fixture.failSync = true
+ expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(install.dispatch).not.toHaveBeenCalled()
+ fixture.failSync = false
+ expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+})
+
+it('settles a durable non-dispatch cancellation through the ready-executable status path', async () => {
+ const file = join(directory, '00000000.json')
+ fixture.onSync = () => { if (existsSync(file)) fixture.failSync = true }
+ const original = controller()
+ await original.ensure('opencode', recipe, environment, 'original', () => true)
+ expect(original.dispatch).not.toHaveBeenCalled()
+ fixture.failSync = false
+ const witness = `${directory}.00000000.dispatch`
+ fixture.onSync = () => { if (existsSync(witness)) fixture.failSync = true }
+ const other = controller()
+ await other.ensure('codex', recipe, environment, 'other', () => true)
+ expect(other.dispatch).not.toHaveBeenCalled()
+ expect(JSON.parse(readFileSync(witness, 'utf8')).kind).toBe('cancelled')
+ expect(existsSync(`${file}.result`)).toBe(false)
+ fixture.onSync = undefined; fixture.failSync = false
+ const recovered = controller()
+ expect(await recovered.status('opencode', 'original', () => true)).toMatchObject({ complete: false })
+ expect(JSON.parse(readFileSync(`${file}.result`, 'utf8')).notDispatched).toBe(true)
+ expect(await recovered.status('opencode', 'original', () => true)).toBeNull()
+ expect(recovered.dispatch).not.toHaveBeenCalled()
+})
+
+it('does not replay a dispatch whose reply was lost', async () => {
+ const install = controller(vi.fn(() => { throw Error('lost dispatch acknowledgement') }))
+ expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ const restarted = controller()
+ expect(await restarted.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+ expect(restarted.dispatch).not.toHaveBeenCalled()
+})
+
+it.each(['changed owner', 'foreign result', 'failed installer', 'unsafe result', 'orphan result', 'malformed result', 'contradictory result'])('holds %s without dispatch or a false completion', async kind => {
+ const install = controller()
+ await install.ensure('opencode', recipe, environment, 'request', () => true)
+ const file = join(directory, '00000000.json')
+ if (kind === 'changed owner') writeFileSync(file, readFileSync(file, 'utf8') + ' ')
+ else if (kind === 'orphan result') writeFileSync(join(directory, '00000001.json.result'), '{}', { mode: 0o600 })
+ else {
+ complete(file, kind === 'failed installer' ? 1 : 0)
+ if (kind === 'foreign result') writeFileSync(`${file}.result`, JSON.stringify({ token: 'different', claim: 'different', code: 0, signal: null }))
+ if (kind === 'unsafe result') chmodSync(`${file}.result`, 0o666)
+ if (kind === 'malformed result' || kind === 'contradictory result') {
+ const value = JSON.parse(readFileSync(`${file}.result`, 'utf8'))
+ value.notDispatched = kind === 'malformed result' ? 'yes' : true
+ writeFileSync(`${file}.result`, JSON.stringify(value))
+ }
+ }
+ expect(await install.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+})
+
+it('runs only the claimed fixture installer and records completion after the core object is gone', async () => {
+ const install = controller()
+ await install.ensure('opencode', recipe, environment, 'request', () => true)
+ const [node, file, digest] = install.dispatch.mock.calls[0] as unknown as [string, string, string]
+ const code = await new Promise<number | null>((done, failed) => {
+ const child = spawn(node, ['-e', NATIVE_INSTALL_WORKER, file, digest], { env: { ...process.env, ...environment }, stdio: 'pipe' })
+ let error = ''; child.stderr.on('data', data => { error += data })
+ child.on('error', failed)
+ child.on('close', code => code === 0 ? done(code) : failed(Error(error)))
+ })
+ expect(code).toBe(0)
+ expect(readFileSync(join(root, 'installed'), 'utf8')).toBe('one\n')
+ expect(await controller().ensure('opencode', recipe, environment, 'request', () => true)).toEqual({ complete: true })
+})
+
+
+it('settles a known pre-dispatch cancellation so another engine can install', async () => {
+ const install = controller()
+ let current = true
+ fixture.onSync = () => { if (existsSync(join(directory, '00000000.json'))) current = false }
+ expect(await install.ensure('opencode', recipe, environment, 'cancelled', () => current)).toMatchObject({ complete: false })
+ expect(install.dispatch).not.toHaveBeenCalled()
+ expect(JSON.parse(readFileSync(join(directory, '00000000.json.result'), 'utf8'))).toMatchObject({ notDispatched: true })
+ fixture.onSync = undefined
+ const later = controller()
+ await later.ensure('codex', recipe, environment, 'later', () => true)
+ expect(later.dispatch).toHaveBeenCalledTimes(1)
+})
+
+it.each(['missing', 'replaced', 'emptied', 'dispatch removed', 'witness removed'])('holds %s history after core reconstruction', async kind => {
+ await controller().ensure('opencode', recipe, environment, 'request', () => true)
+ if (kind === 'dispatch removed') unlinkSync(join(directory, '00000000.json.dispatch'))
+ else if (kind === 'witness removed') unlinkSync(`${directory}.00000000.dispatch`)
+ else if (kind === 'emptied') {
+ for (const name of readdirSync(directory)) unlinkSync(join(directory, name))
+ } else {
+ renameSync(directory, `${directory}-former`)
+ if (kind === 'replaced') mkdirSync(directory, { mode: 0o700 })
+ }
+ const restarted = controller()
+ expect(await restarted.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(restarted.dispatch).not.toHaveBeenCalled()
+})
+
+it('confirms a readable result durably before crediting it or dispatching its successor', async () => {
+ await controller().ensure('opencode', recipe, environment, 'request', () => true)
+ complete()
+ fixture.failSync = true
+ const restarted = controller()
+ expect(await restarted.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(await restarted.ensure('codex', recipe, environment, 'other', () => true)).toMatchObject({ complete: false })
+ expect(restarted.dispatch).not.toHaveBeenCalled()
+ fixture.failSync = false
+ expect(await restarted.ensure('opencode', recipe, environment, 'request', () => true)).toEqual({ complete: true })
+})
+
+it('does not credit completion after the owner changes during result confirmation', async () => {
+ await controller().ensure('opencode', recipe, environment, 'request', () => true)
+ complete()
+ let current = true
+ fixture.onSync = () => { current = false }
+ expect(await controller().ensure('opencode', recipe, environment, 'request', () => current)).toMatchObject({ complete: false })
+})
+
+it('keeps recipe and HOME snapshots across disk waits, and gives HOME a fresh evidence budget', async () => {
+ const mutableRecipe = { ...structuredClone(recipe) }, mutableEnvironment = { ...environment }
+ const expected = hash(JSON.stringify({ recipe: mutableRecipe, environment: mutableEnvironment }))
+ let once = false
+ fixture.onSync = () => {
+ if (once) return
+ once = true; mutableRecipe.command = 'changed'; mutableEnvironment.HOME = '/fixture/not-authorized'
+ return 300
+ }
+ const install = controller()
+ await install.ensure('opencode', mutableRecipe, mutableEnvironment, 'request', () => true)
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+ expect(JSON.parse(readFileSync(join(directory, '00000000.json'), 'utf8'))).toMatchObject({ recipe: expected, environment })
+})
+
+it.each(['invalid name', 'oversized', 'relative home'])('refuses %s inputs before reserving an installation', async kind => {
+ const install = controller()
+ const invalid = kind === 'invalid name' ? { ...environment, 'A;false': 'x' }
+ : kind === 'oversized' ? { ...environment, LARGE: 'x'.repeat(262144) } : { ...environment, HOME: 'relative' }
+ expect(await install.ensure('opencode', recipe, invalid, 'request', () => true)).toMatchObject({ complete: false })
+ expect(existsSync(directory)).toBe(false)
+ expect(install.dispatch).not.toHaveBeenCalled()
+})
+
+
+it('does not rewrite an in-place result change during confirmation', async () => {
+ await controller().ensure('opencode', recipe, environment, 'request', () => true)
+ complete()
+ const file = join(directory, '00000000.json.result')
+ let changed = false
+ fixture.onSync = () => {
+ if (changed) return
+ changed = true
+ const value = JSON.parse(readFileSync(file, 'utf8')); value.code = 1
+ writeFileSync(file, JSON.stringify(value))
+ }
+ const restarted = controller()
+ expect(await restarted.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(JSON.parse(readFileSync(file, 'utf8')).code).toBe(1)
+ fixture.onSync = undefined
+ expect(await restarted.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(restarted.dispatch).not.toHaveBeenCalled()
+})
+
+
+it('lets one of two independent recovering cores own an immutable outside dispatch slot', async () => {
+ const first = controller()
+ let delayed = false
+ fixture.onSync = () => {
+ if (delayed || !existsSync(join(directory, '00000000.json'))) return
+ delayed = true
+ return 1000
+ }
+ const initial = first.ensure('opencode', recipe, environment, 'request', () => true)
+ for (let n = 0; n < 200 && !delayed; n++) await new Promise(done => setTimeout(done, 5))
+ expect(delayed).toBe(true)
+ // Separate module state models another core's independent disk reservations.
+ vi.resetModules()
+ const { createNativeInstallations: recoveredController } = await import('./nativeInstall.js')
+ const dispatch = vi.fn()
+ const recovered = recoveredController({ directory, node: () => process.execPath, dispatch })
+ await recovered.ensure('opencode', recipe, environment, 'request', () => true)
+ expect(dispatch).toHaveBeenCalledTimes(1)
+ const saved = readFileSync(`${directory}.00000000.dispatch`, 'utf8')
+ await initial
+ expect(first.dispatch).not.toHaveBeenCalled()
+ expect(readFileSync(`${directory}.00000000.dispatch`, 'utf8')).toBe(saved)
+})
+
+it('preserves a changed pending claim instead of confirming stale bytes', async () => {
+ const file = join(directory, '00000000.json')
+ fixture.onSync = () => { if (existsSync(file)) fixture.failSync = true }
+ const original = controller()
+ await original.ensure('opencode', recipe, environment, 'request', () => true)
+ expect(existsSync(file)).toBe(true)
+ expect(original.dispatch).not.toHaveBeenCalled()
+ fixture.failSync = false
+ let changed = false, expected = ''
+ fixture.onSync = () => {
+ if (changed) return
+ changed = true; expected = readFileSync(file, 'utf8') + ' '
+ writeFileSync(file, expected)
+ }
+ const restarted = controller()
+ expect(await restarted.ensure('opencode', recipe, environment, 'request', () => true)).toMatchObject({ complete: false })
+ expect(changed).toBe(true)
+ expect(readFileSync(file, 'utf8')).toBe(expected)
+ expect(restarted.dispatch).not.toHaveBeenCalled()
+ expect(existsSync(`${directory}.00000000.dispatch`)).toBe(false)
+})
+
+it('holds oversized installation history without replaying or changing saved records', async () => {
+ const install = controller()
+ await install.ensure('opencode', recipe, environment, 'request', () => true)
+ const original = readFileSync(join(directory, '00000000.json'), 'utf8')
+ for (let index = 1; index <= 128; index++) writeFileSync(join(directory, `${String(index).padStart(8, '0')}.json`), original, { mode: 0o600 })
+ install.dispatch.mockClear()
+ const result = await install.ensure('opencode', recipe, environment, 'request', () => true)
+ expect(result).toMatchObject({ complete: false, detail: expect.stringContaining('automatic recovery limit') })
+ expect(install.dispatch).not.toHaveBeenCalled()
+ expect(readFileSync(join(directory, '00000000.json'), 'utf8')).toBe(original)
+})
diff --git a/cli/src/engines/kit/nativeInstall.ts b/cli/src/engines/kit/nativeInstall.ts
new file mode 100644
index 000000000..6633d675a
--- /dev/null
+++ b/cli/src/engines/kit/nativeInstall.ts
@@ -0,0 +1,337 @@
+/** Installer-only dependencies survive core restart; engine dispatch returns to core. */
+import { spawn } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from 'node:fs'
+import { basename, dirname, isAbsolute, join } from 'node:path'
+import { buildEngineInstallationArgv } from '../../lib/engineLaunch.js'
+import type { EngineInstallRecipe } from '../../lib/engineInstall.js'
+import { managedNodePath } from '../../lib/nodeRuntime.js'
+import { secureStateDirectory } from '../../lib/secureState.js'
+import type { AgentEngine } from '../types.js'
+import { LAUNCH_LOCATION_VARIABLES } from './nativeLocations.js'
+import { NativeEvidenceBudget } from './nativeEvidence.js'
+import { NativeFiles } from './nativeFiles.js'
+import { inspectHookFile, runHookPreparation } from './nativeHookFiles.js'
+import { NativePaths, verifyNativePathFacts, type NativePathFact } from './nativePaths.js'
+
+const LIMIT = 262_144
+// This is installation history, not launch history: ordinary launches never add
+// an entry. Bound exceptional recovery instead of making Stop wait on an ever
+// larger synchronous ownership fence. Full records stay on disk for review.
+const MAX_INSTALLATIONS = 128
+const digest = (text: string): string => createHash('sha256').update(text).digest('hex')
+const identity = (s: BigIntStats): string => `${s.dev}:${s.ino}:${s.mode}:${s.uid}`
+const version = (s: BigIntStats): string => `${identity(s)}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`
+const directoryStamp = (directory: string): string => version(lstatSync(directory, { bigint: true }))
+const missing = (error: unknown): boolean => (error as NodeJS.ErrnoException).code === 'ENOENT'
+interface Link { file: string; digest: string }
+interface Authority { version: 1; directory: string }
+interface Claim {
+ version: 1; token: string; request: string; engine: AgentEngine; recipe: string
+ argv: string[]; environment: Record<string, string>
+ routes: ReturnType<NativePaths['snapshot']>; previous: Link[]; authority: string; witness: string
+}
+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 }
+const hold = (detail: string): NativeInstallation => ({ complete: false, 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 } {
+ const paths = new NativePaths(new NativeEvidenceBudget(250))
+ const location = paths.resolveSync(file, true), facts = paths.snapshot()
+ if (!location) {
+ // An ancestor may be an ordinary alias, such as macOS /var. Absence
+ // belongs to the observed physical parent, never a dangling leaf alias.
+ const parent = paths.resolveSync(dirname(file), true)
+ if (!parent?.info.isDirectory() || !paths.absentLeaf(join(parent.path, basename(file)))) throw Error('Unconfirmed missing installation route')
+ paths.verify()
+ throw Object.assign(Error('Missing installation record'), { code: 'ENOENT' })
+ }
+ if (lstatSync(file).isSymbolicLink()) throw Error('Aliased installation record')
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ let stamp: string, text: string
+ try {
+ const before = fstatSync(fd, { bigint: true })
+ if (!before.isFile() || before.size > LIMIT || before.ino !== location.info.ino || before.dev !== location.info.dev
+ || (before.mode & 0o022n) !== 0n || before.uid !== BigInt(process.getuid!())) throw Error('Unsafe installation record')
+ stamp = version(before)
+ const bytes = Buffer.alloc(Number(before.size))
+ let offset = 0
+ for (let calls = 0; offset < bytes.length; calls++) {
+ if (calls >= 64) throw Error('Installation record read limit')
+ const count = readSync(fd, bytes, offset, bytes.length - offset, offset)
+ if (!count) throw Error('Truncated installation record')
+ offset += count
+ }
+ if (version(fstatSync(fd, { bigint: true })) !== stamp) throw Error('Changed installation record')
+ text = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
+ } finally { closeSync(fd) }
+ const verify = () => { verifyNativePathFacts(facts); if (version(lstatSync(file, { bigint: true })) !== stamp) throw Error('Changed installation record') }
+ verify()
+ return { text, file, stamp, facts, verify }
+}
+
+/** The helper records this one installation after core dies. Its shell has job control off,
+ * so the deadline kills the installer group, including stopped children. It never runs an engine. */
+export const NATIVE_INSTALL_WORKER = String.raw`
+const fs=require('node:fs'),cp=require('node:child_process'),path=require('node:path'),crypto=require('node:crypto');
+const [file,expected,testDeadline]=process.argv.slice(1),directory=path.dirname(file),C=fs.constants;
+const hash=s=>crypto.createHash('sha256').update(s).digest('hex');
+const id=s=>String(s.dev)+':'+String(s.ino)+':'+String(s.mode)+':'+String(s.uid);
+const ver=s=>id(s)+':'+String(s.size)+':'+String(s.mtimeNs)+':'+String(s.ctimeNs);
+function read(file){const fd=fs.openSync(file,C.O_RDONLY|C.O_NOFOLLOW|C.O_NONBLOCK);try{
+ const s=fs.fstatSync(fd,{bigint:true});if(!s.isFile()||s.size>262144n||s.uid!==BigInt(process.getuid())||(s.mode&0o022n))throw Error('Unsafe installation record');
+ const bytes=Buffer.alloc(Number(s.size));let offset=0;for(let calls=0;offset<bytes.length;calls++){
+ if(calls>=64)throw Error('Installation record read limit');const n=fs.readSync(fd,bytes,offset,bytes.length-offset,offset);if(!n)throw Error('Truncated record');offset+=n}
+ if(ver(fs.fstatSync(fd,{bigint:true}))!==ver(s)||ver(fs.lstatSync(file,{bigint:true}))!==ver(s))throw Error('Changed installation record');
+ return new TextDecoder('utf-8',{fatal:true}).decode(bytes)
+ }finally{fs.closeSync(fd)}}
+const directoryFd=fs.openSync(directory,C.O_RDONLY|C.O_DIRECTORY|C.O_NOFOLLOW),directoryId=id(fs.fstatSync(directoryFd,{bigint:true}));
+const text=read(file);if(hash(text)!==expected)throw Error('Changed installation claim');
+const claim=JSON.parse(text),authorityText=read(claim.authority),authority=JSON.parse(authorityText),dispatchText=read(claim.witness),dispatch=JSON.parse(dispatchText);
+if(authority.directory!==directoryId||read(file+'.dispatch')!==dispatchText||dispatch.kind!=='run'||dispatch.token!==claim.token||dispatch.claim!==expected)throw Error('Unconfirmed installer dispatch');
+try{fs.lstatSync(file+'.result');throw Error('Installer already settled')}catch(e){if(e.code!=='ENOENT')throw e}
+function current(){
+ if(id(fs.lstatSync(directory,{bigint:true}))!==directoryId||read(file)!==text||read(claim.authority)!==authorityText||read(claim.witness)!==dispatchText||read(file+'.dispatch')!==dispatchText)throw Error('Changed installation authority');
+ for(const p of claim.previous)if(hash(read(p.file))!==p.digest)throw Error('Changed installation predecessor');
+ for(const r of claim.routes){let s;try{s=fs.lstatSync(r.path,{bigint:true})}catch(e){if(e.code!=='ENOENT')throw e;s=null}
+ if((s?id(s):null)!==r.identity)throw Error('Changed installation target');
+ if(r.alias&&(!s||ver(s)!==r.alias.version||fs.readlinkSync(r.path)!==r.alias.target))throw Error('Changed installation alias');}
+}
+function publish(value){
+ current();const temporary=file+'.'+claim.token+'.result-tmp',result=file+'.result';
+ const bytes=JSON.stringify(value);if(Buffer.byteLength(bytes)>262144)throw Error('Oversized installation result');
+ const fd=fs.openSync(temporary,C.O_WRONLY|C.O_CREAT|C.O_EXCL|C.O_NOFOLLOW,0o600);
+ try{
+ fs.writeFileSync(fd,bytes);const staged=ver(fs.fstatSync(fd,{bigint:true}));fs.fsyncSync(fd);
+ if(ver(fs.fstatSync(fd,{bigint:true}))!==staged||ver(fs.lstatSync(temporary,{bigint:true}))!==staged)throw Error('Changed result staging file');
+ current();fs.linkSync(temporary,result);
+ if(id(fs.lstatSync(result,{bigint:true}))!==id(fs.fstatSync(fd,{bigint:true}))||read(result)!==bytes)throw Error('Changed published result');
+ if(id(fs.lstatSync(temporary,{bigint:true}))!==id(fs.fstatSync(fd,{bigint:true})))throw Error('Changed result staging file');
+ fs.unlinkSync(temporary);fs.fsyncSync(directoryFd);
+ if(id(fs.lstatSync(result,{bigint:true}))!==id(fs.fstatSync(fd,{bigint:true}))||read(result)!==bytes)throw Error('Changed confirmed result');
+ }finally{fs.closeSync(fd)}
+}
+current();
+let output='',finished=false,leaderGone=false,uncertain=false,deadline,drain;
+const environment={...process.env};for(const key of ${JSON.stringify(LAUNCH_LOCATION_VARIABLES)})delete environment[key];Object.assign(environment,claim.environment);
+const child=cp.spawn(claim.argv[0],claim.argv.slice(1),{env:environment,cwd:claim.environment.HOME,detached:true,stdio:['ignore','pipe','pipe']});
+const collect=chunk=>{output=(output+chunk.toString()).slice(-32768)};
+child.stdout.on('data',collect);child.stderr.on('data',collect);
+child.on('error',error=>{output=String(error).slice(0,2000)});
+child.on('exit',()=>{
+ leaderGone=true;clearTimeout(deadline);
+ drain=setTimeout(()=>{if(finished)return;uncertain=true;child.stdout.destroy();child.stderr.destroy()},250);
+});
+child.on('close',(code,signal)=>{if(finished)return;finished=true;clearTimeout(deadline);clearTimeout(drain);try{if(!uncertain)publish({token:claim.token,claim:expected,code,signal,detail:output})}finally{fs.closeSync(directoryFd)}});
+deadline=setTimeout(()=>{if(leaderGone||child.exitCode!==null||child.signalCode!==null)return;try{process.kill(-child.pid,'SIGKILL')}catch{}},Math.max(20,Math.min(1200000,Number(testDeadline)||1200000)));
+`
+
+export function createNativeInstallations({ directory, node = managedNodePath, dispatch = defaultDispatch }: {
+ directory: string; node?: () => string; dispatch?: (node: string, file: string, digest: string) => void
+}) {
+ // Outside the claim directory: recreating or emptying that directory cannot erase its active owner.
+ const authorityFile = `${directory}.authority`
+ const examine = async (engine: AgentEngine, inputRecipe: EngineInstallRecipe, inputEnvironment: Record<string, string>, request: string,
+ current: () => boolean, query = false): Promise<NativeInstallation | null> => {
+ try {
+ if (!current()) return hold('The saved launch request changed before installation.')
+ // Snapshot caller-owned objects before any yield. The fingerprint and executed bytes agree.
+ const recipe = structuredClone(inputRecipe), environment = { ...inputEnvironment }, runtime = query ? '' : node()
+ if (!isAbsolute(directory) || typeof request !== 'string' || !request || request.length > 4096
+ || (!query && (!isAbsolute(environment.HOME ?? '') || !isAbsolute(runtime)
+ || Object.entries(environment).some(([key, value]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== 'string' || value.includes('\0'))
+ || typeof recipe.command !== 'string' || recipe.command.includes('\0')))) throw Error('Invalid installation input')
+ const wantedRecipe = digest(JSON.stringify({ recipe, environment }))
+ const argv = query ? [] : buildEngineInstallationArgv(engine, recipe, environment, runtime)
+ // Enforce the helper's read limit before publishing any irreversible claim.
+ if (Buffer.byteLength(JSON.stringify({ recipe, environment, argv })) > LIMIT - 32768) throw Error('Oversized installation input')
+ const maybe = (file: string) => {
+ try { return readRecord(file) } catch (error) { if (!missing(error)) throw error; return undefined }
+ }
+ const witness = (index: number) => `${directory}.${String(index).padStart(8, '0')}.dispatch`
+ let authority = maybe(authorityFile)
+ if (!authority && maybe(witness(0))) return hold('The engine installation authority is missing; previous work cannot be replayed.')
+ if (query && !authority) {
+ const absent = new NativeFiles()
+ if (absent.entries(directory, true).length) return hold('The engine installation authority is missing; existing work cannot be replayed.')
+ absent.verify()
+ if (!current() || maybe(authorityFile) || maybe(witness(0))) return hold('Waiting to confirm current installation ownership.')
+ return null
+ }
+ secureStateDirectory(directory, !authority)
+ const paths = new NativePaths(new NativeEvidenceBudget(250))
+ paths.resolveSync(directory)
+ const directoryFacts = paths.snapshot(), directoryId = identity(lstatSync(directory, { bigint: true }))
+ const physical = () => { try { verifyNativePathFacts(directoryFacts); return true } catch { return false } }
+ const publish = async (file: string, bytes: string, owner = physical) => {
+ if (Buffer.byteLength(bytes) > LIMIT) throw Error('Oversized installation record')
+ return runHookPreparation([file], attempt => inspectHookFile(file, 0o600).replace(bytes, attempt, true), { current: owner, retainConflicts: true })
+ }
+ const confirm = async (file: string, record: ReturnType<typeof readRecord>, owner = physical) => {
+ await runHookPreparation([file], attempt => {
+ record.verify()
+ const observed = inspectHookFile(file, 0o600)
+ if (observed.content !== record.text) throw Error('Changed installation confirmation')
+ record.verify()
+ // Equal bytes take only the fsync path; confirmation can never overwrite newer evidence.
+ return observed.replace(record.text, attempt)
+ }, { current: owner, retainConflicts: true })
+ record.verify()
+ }
+ if (!authority) {
+ if (new NativeFiles().entries(directory).length) return hold('The engine installation authority is missing; existing work cannot be replayed.')
+ await publish(authorityFile, JSON.stringify({ version: 1, directory: directoryId } satisfies Authority))
+ authority = readRecord(authorityFile)
+ }
+ const genesis = JSON.parse(authority.text) as Authority
+ if (genesis.version !== 1 || genesis.directory !== directoryId) return hold('The engine installation history was replaced; its previous owner is still unconfirmed.')
+ const stamp = directoryStamp(directory)
+ // NativeFiles retains iterator acquisition and ancestor evidence, including ABA route swaps.
+ const entries = new NativeFiles().entries(directory), names = entries.filter(name => /^\d{8}\.json$/.test(name)).sort()
+ if (names.length > MAX_INSTALLATIONS) return hold('The engine installation history exceeds the automatic recovery limit. Its saved records need review before another installation.')
+ if (maybe(witness(names.length)) || entries.some(name => /^\d{8}\.json\.(result|dispatch)$/.test(name) && !names.includes(name.replace(/\.(result|dispatch)$/, '')))) {
+ return hold('The engine installation history is incomplete; a previous installation may still own its target.')
+ }
+ const previous: Link[] = []
+ const routesByPath = new Map<string, NativePathFact>(), leaves = new Map<string, string>()
+ const retain = (record: ReturnType<typeof readRecord>) => {
+ for (const fact of record.facts) {
+ if (fact.path === record.file) continue // The leaf's complete version is checked below.
+ const prior = routesByPath.get(fact.path)
+ if (prior && JSON.stringify(prior) !== JSON.stringify(fact)) throw Error('Changed installation ancestry')
+ routesByPath.set(fact.path, fact)
+ }
+ const prior = leaves.get(record.file)
+ if (prior && prior !== record.stamp) throw Error('Changed installation record')
+ leaves.set(record.file, record.stamp)
+ }
+ retain(authority)
+ let complete = false, began = performance.now()
+ let pending: { file: string; record: ReturnType<typeof readRecord>; claim: Claim; slot?: ReturnType<typeof readRecord> } | undefined
+ let lastResult: { file: string; record: ReturnType<typeof readRecord> } | undefined
+ for (const [index, name] of names.entries()) {
+ if (name !== `${String(index).padStart(8, '0')}.json`) return hold('The engine installation history has an unconfirmed gap.')
+ const file = join(directory, name), record = readRecord(file), hash = digest(record.text), claim = JSON.parse(record.text) as Claim
+ retain(record)
+ if (claim.version !== 1 || typeof claim.token !== 'string' || !claim.token || typeof claim.request !== 'string'
+ || claim.authority !== authorityFile || claim.witness !== witness(index) || JSON.stringify(claim.previous) !== JSON.stringify(previous)) throw Error('Invalid installation claim')
+ if (claim.request === request && (claim.engine !== engine || (!query && claim.recipe !== wantedRecipe))) return hold('The saved request’s installation choices changed.')
+ const resultRecord = maybe(`${file}.result`), slot = maybe(claim.witness)
+ if (slot) retain(slot)
+ if (!resultRecord) {
+ if (index !== names.length - 1) throw Error('Unfinished installation predecessor')
+ pending = { file, record, claim, slot }; break
+ }
+ if (!slot) throw Error('Missing installation dispatch witness')
+ const markerRecord = readRecord(`${file}.dispatch`)
+ retain(markerRecord); retain(resultRecord)
+ const result = JSON.parse(resultRecord.text) as Result, marker = JSON.parse(slot.text) as Dispatch
+ if (markerRecord.text !== slot.text || marker.token !== claim.token || marker.claim !== hash || !['run', 'cancelled'].includes(marker.kind)
+ || result.token !== claim.token || result.claim !== hash || (result.code !== null && !Number.isInteger(result.code))
+ || (result.signal !== null && (typeof result.signal !== 'string' || !/^SIG[A-Z0-9]+$/.test(result.signal)))
+ || (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.')
+ }
+ 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.')
+ complete = true
+ }
+ lastResult = { file: `${file}.result`, record: resultRecord }
+ previous.splice(0, previous.length, { file, digest: hash }, { file: `${file}.result`, digest: digest(resultRecord.text) })
+ if (performance.now() - began > 20) { await new Promise<void>(done => setImmediate(done)); began = performance.now() }
+ }
+ const historyOwner = () => {
+ try {
+ const began = performance.now()
+ verifyNativePathFacts([...routesByPath.values()])
+ for (const [file, stamp] of leaves) {
+ if (performance.now() - began > 20 || version(lstatSync(file, { bigint: true })) !== stamp) return false
+ }
+ return physical()
+ } catch { return false }
+ }
+ const historyCurrent = () => historyOwner() && directoryStamp(directory) === stamp
+ if (!current() || !historyCurrent()) return hold('Waiting to confirm current installation ownership.')
+ // A helper may have linked its result just before its final directory sync failed.
+ if (lastResult) await confirm(lastResult.file, lastResult.record, historyCurrent)
+ if (!current() || !historyCurrent()) return hold('Waiting to confirm current installation ownership.')
+ if (pending?.slot) {
+ const { file, record, claim, slot } = pending
+ const marker = JSON.parse(slot.text) as Dispatch, hash = digest(record.text)
+ if (marker.token !== claim.token || marker.claim !== hash || !['run', 'cancelled'].includes(marker.kind)) throw Error('Invalid pending installer dispatch')
+ if (marker.kind === 'cancelled') {
+ // A durable cancellation proves the helper never ran. Complete only
+ // that result, including when a ready executable takes the status path.
+ const retained = () => {
+ try { record.verify(); slot.verify(); verifyNativePathFacts(claim.routes); return historyOwner() }
+ catch { return false }
+ }
+ const inside = maybe(`${file}.dispatch`)
+ if (inside) {
+ if (inside.text !== slot.text) throw Error('Changed cancellation marker')
+ await confirm(`${file}.dispatch`, inside, retained)
+ } else await publish(`${file}.dispatch`, slot.text, retained)
+ await confirm(claim.witness, slot, retained)
+ await publish(`${file}.result`, JSON.stringify({ token: claim.token, claim: hash, code: null, signal: null, notDispatched: true } satisfies Result), retained)
+ return hold('The cancelled installer is settled; the saved launch can retry.')
+ }
+ }
+ 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.')
+ : complete ? { complete: true } : null
+ if (!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.
+ const homes = new NativePaths(new NativeEvidenceBudget(250)), home = homes.resolveSync(environment.HOME)
+ if (!home?.info.isDirectory()) return hold('Waiting to confirm the native installation home.')
+ const routes = [...directoryFacts, ...homes.snapshot()]
+ const file = pending?.file ?? join(directory, `${String(names.length).padStart(8, '0')}.json`)
+ const claim: Claim = pending?.claim ?? { version: 1, token: randomUUID(), request, engine, recipe: wantedRecipe,
+ argv, environment, routes, previous, authority: authorityFile, witness: witness(names.length) }
+ const bytes = pending?.record.text ?? JSON.stringify(claim), hash = digest(bytes)
+ verifyNativePathFacts(claim.routes)
+ if (!current() || !historyCurrent()) return hold('Waiting to confirm current installation ownership.')
+ if (pending) await confirm(file, pending.record, historyCurrent)
+ else await publish(file, bytes, historyOwner)
+ const claimed = readRecord(file)
+ const 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.')
+ }
+ // 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.')
+ if (!claimCurrent()) return hold('Waiting to confirm the installer claim.')
+ // Another request may settle an inert reservation, but cannot replay or cancel an actual installer.
+ const kind = current() && claim.request === request ? 'run' : 'cancelled'
+ const markerBytes = JSON.stringify({ token: claim.token, claim: hash, kind } satisfies Dispatch)
+ await publish(claim.witness, markerBytes, claimCurrent)
+ const slot = readRecord(claim.witness)
+ const dispatchCurrent = () => { try { slot.verify(); return claimCurrent() } catch { return false } }
+ await publish(`${file}.dispatch`, markerBytes, dispatchCurrent)
+ if (kind === 'cancelled' || !current()) {
+ await publish(`${file}.result`, result, dispatchCurrent)
+ return hold('The launch changed before installation. No installer was dispatched.')
+ }
+ 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.')
+ } 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> =>
+ (await examine(engine, recipe, environment, request, current))!
+ const status = (engine: AgentEngine, request: string, current: () => boolean) => examine(engine,
+ { command: '', source: '', executable: { names: [] } }, {}, request, current, true)
+ return { ensure, status }
+}
+
+function defaultDispatch(node: string, file: string, hash: string): void {
+ const child = spawn(node, ['-e', NATIVE_INSTALL_WORKER, file, hash], { detached: true, stdio: 'ignore' })
+ child.on('error', () => { /* The durable dispatch stays uncertain; it never authorizes a replay. */ })
+ child.unref()
+}
diff --git a/cli/src/engines/kit/nativeInstallProcess.spec.ts b/cli/src/engines/kit/nativeInstallProcess.spec.ts
new file mode 100644
index 000000000..57a79ef21
--- /dev/null
+++ b/cli/src/engines/kit/nativeInstallProcess.spec.ts
@@ -0,0 +1,132 @@
+/** Real generated installer shell and detached recorder, with only private fixture commands. */
+import { spawn, type ChildProcess } from 'node:child_process'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { EngineInstallRecipe } from '../../lib/engineInstall.js'
+import { shellSingleQuote } from '../../lib/shellQuote.js'
+
+let root: string, home: string, binary: string, directory: string, environment: Record<string, string>
+let module: typeof import('./nativeInstall.js')
+const children = new Set<ChildProcess>()
+beforeEach(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'native-install-process-')))
+ home = join(root, 'home'); mkdirSync(home, { mode: 0o700 })
+ binary = join(root, 'fixture-engine'); directory = join(root, 'claims')
+ for (const key of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'ZDOTDIR']) {
+ const value = key === 'HOME' ? home : join(root, key)
+ mkdirSync(value, { recursive: true, mode: 0o700 }); vi.stubEnv(key, value)
+ }
+ vi.stubEnv('OPENCODE_PATH', join(root, 'absent-default'))
+ vi.stubEnv('SHELL', '/bin/sh'); vi.stubEnv('PATH', '/usr/bin:/bin')
+ environment = { HOME: home, PATH: '/usr/bin:/bin', SHELL: '/bin/sh' }
+ vi.resetModules(); module = await import('./nativeInstall.js')
+})
+afterEach(() => {
+ for (const child of children) child.kill('SIGKILL')
+ children.clear()
+ // The recorder reaps its stopped group; the escaped fixture exits after five
+ // seconds. Their recorded PIDs are observations, never cleanup authority.
+ vi.unstubAllEnvs(); rmSync(root, { recursive: true, force: true })
+})
+
+const nodeCommand = (code: string) => `${shellSingleQuote(process.execPath)} -e ${shellSingleQuote(code)}`
+const installCode = () => `require('node:fs').writeFileSync(${JSON.stringify(binary)},${JSON.stringify('#!/bin/sh\nprintf ran >' + shellSingleQuote(join(root, 'engine-ran')) + '\nexit 0\n')},{mode:0o700})`
+const recipe = (code: string): EngineInstallRecipe => ({ command: nodeCommand(code), source: 'private fixture', executable: { names: [binary] } })
+const controller = () => {
+ const dispatch = vi.fn()
+ return { dispatch, ...module.createNativeInstallations({ directory, node: () => process.execPath, dispatch }) }
+}
+function run(file: string, hash: string, deadline = 2000, prefix = ''): Promise<{ code: number | null; stderr: string }> {
+ return new Promise((done, failed) => {
+ const child = spawn(process.execPath, ['-e', prefix + module.NATIVE_INSTALL_WORKER, file, hash, String(deadline)], {
+ env: { ...process.env, ...environment }, stdio: ['ignore', 'pipe', 'pipe'],
+ })
+ children.add(child)
+ let stderr = ''; child.stderr.on('data', data => { stderr += data })
+ const timer = setTimeout(() => { child.kill('SIGKILL'); failed(Error('Private installer recorder exceeded its test limit')) }, 8000)
+ child.on('error', failed)
+ child.on('close', code => { clearTimeout(timer); children.delete(child); done({ code, stderr }) })
+ })
+}
+const settled = async (test: () => boolean) => {
+ for (let n = 0; n < 200; n++) { if (test()) return; await new Promise(done => setTimeout(done, 10)) }
+ throw Error('Private fixture did not reach its checkpoint')
+}
+
+it('executes the real installation wrapper once without starting the engine or dropping shell support', async () => {
+ const install = controller(), chosen = recipe(installCode())
+ await install.ensure('opencode', chosen, environment, 'request', () => true)
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+ const [, file, hash] = install.dispatch.mock.calls[0]
+ const result = await run(file, hash)
+ expect(result.code).toBe(0)
+ expect(result.stderr).not.toMatch(/harness_resume.*not found/)
+ const recorded = JSON.parse(readFileSync(`${file}.result`, 'utf8'))
+ expect(recorded, recorded.detail).toMatchObject({ code: 0, signal: null })
+ expect(recorded.detail).not.toMatch(/harness_resume.*not found/)
+ expect(existsSync(join(root, 'engine-ran'))).toBe(false)
+ expect(existsSync(binary)).toBe(true)
+ expect(await controller().ensure('opencode', chosen, environment, 'request', () => true)).toEqual({ complete: true })
+}, 15_000)
+
+it('waits for a private live Desktop download marker before using its installation', async () => {
+ mkdirSync(join(home, '.harness', 'run'), { recursive: true })
+ const downloader = spawn(process.execPath, ['-e', 'setInterval(()=>{},1000)', 'harness-download-private-fixture'], { stdio: 'ignore' })
+ children.add(downloader)
+ writeFileSync(join(home, '.harness', 'run', 'downloading-opencode'), String(downloader.pid))
+ const install = controller(), wrong = join(root, 'competing-install')
+ await install.ensure('opencode', recipe(`require('node:fs').writeFileSync(${JSON.stringify(wrong)},'wrong');${installCode()}`), environment, 'request', () => true)
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+ const [, file, hash] = install.dispatch.mock.calls[0]
+ const running = run(file, hash)
+ await new Promise(done => setTimeout(done, 150))
+ expect(existsSync(wrong)).toBe(false)
+ writeFileSync(binary, '#!/bin/sh\nexit 0\n', { mode: 0o700 })
+ downloader.kill('SIGTERM')
+ expect((await running).code).toBe(0)
+ expect(existsSync(wrong)).toBe(false)
+ expect(JSON.parse(readFileSync(`${file}.result`, 'utf8')).code).toBe(0)
+}, 15_000)
+
+it('ends a stopped installer child at the group deadline', async () => {
+ const pidFile = join(root, 'stopped.pid')
+ const install = controller()
+ await install.ensure('opencode', recipe(`require('node:fs').writeFileSync(${JSON.stringify(pidFile)},String(process.pid));process.kill(process.pid,'SIGSTOP');${installCode()}`), environment, 'request', () => true)
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+ const [, file, hash] = install.dispatch.mock.calls[0]
+ const result = await run(file, hash, 500)
+ expect(result.code).toBe(0)
+ expect(existsSync(pidFile)).toBe(true)
+ expect(JSON.parse(readFileSync(`${file}.result`, 'utf8'))).toMatchObject({ code: null, signal: 'SIGKILL' })
+ expect(existsSync(binary)).toBe(false)
+}, 15_000)
+
+it('holds an escaped pipe owner after leader exit and closes the recorder without late group signalling', async () => {
+ const pidFile = join(root, 'escaped.pid')
+ const install = controller()
+ const code = `${installCode()};const child=require('node:child_process').spawn(process.execPath,['-e','setTimeout(()=>{},5000)'],{detached:true,stdio:['ignore',1,2]});require('node:fs').writeFileSync(${JSON.stringify(pidFile)},String(child.pid));child.unref()`
+ const chosen = recipe(code)
+ await install.ensure('opencode', chosen, environment, 'request', () => true)
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+ const [, file, hash] = install.dispatch.mock.calls[0]
+ const result = await run(file, hash, 1000)
+ expect(result.code).toBe(0)
+ await settled(() => existsSync(pidFile))
+ expect(existsSync(`${file}.result`)).toBe(false)
+ expect(await controller().ensure('opencode', chosen, environment, 'request', () => true)).toMatchObject({ complete: false })
+}, 15_000)
+
+it('cannot publish a substituted success record from a replaced helper staging file', async () => {
+ const install = controller(), chosen = recipe('process.exit(7)')
+ await install.ensure('opencode', chosen, environment, 'request', () => true)
+ expect(install.dispatch).toHaveBeenCalledTimes(1)
+ const [, file, hash] = install.dispatch.mock.calls[0]
+ const prefix = `const injected=require('node:fs'), originalSync=injected.fsyncSync;let changed=false;injected.fsyncSync=function(fd){if(!changed&&injected.fstatSync(fd).isFile()){changed=true;const temporary=injected.readdirSync(${JSON.stringify(directory)}).find(name=>name.endsWith('.result-tmp'));const path=${JSON.stringify(directory)}+'/'+temporary;const value=JSON.parse(injected.readFileSync(path,'utf8'));value.code=0;value.signal=null;injected.unlinkSync(path);injected.writeFileSync(path,JSON.stringify(value),{mode:0o600});}return originalSync(fd)};\n`
+ const result = await run(file, hash, 2000, prefix)
+ expect(result.code).not.toBe(0)
+ expect(result.stderr).toContain('Changed result staging file')
+ expect(existsSync(`${file}.result`)).toBe(false)
+ expect(await controller().ensure('opencode', chosen, environment, 'request', () => true)).toMatchObject({ complete: false })
+}, 15_000)
diff --git a/cli/src/engines/kit/nativeLaunchGuard.spec.ts b/cli/src/engines/kit/nativeLaunchGuard.spec.ts
new file mode 100644
index 000000000..a5bb47c5f
--- /dev/null
+++ b/cli/src/engines/kit/nativeLaunchGuard.spec.ts
@@ -0,0 +1,60 @@
+import { execFileSync } from 'node:child_process'
+import { chmodSync, mkdtempSync, realpathSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it } from 'vitest'
+import type { NativeLaunch } from '../nativeLaunch.js'
+import { nativeLaunchGuard } from './nativeLaunchGuard.js'
+import { inspectHookFile, runHookPreparation, type HookPreparationProof } from './nativeHookFiles.js'
+import { executableSnapshot, nativeVersionProbe } from './nativeVersion.js'
+
+let root: string
+beforeEach(() => { root = realpathSync(mkdtempSync(join(tmpdir(), 'launch-guard-'))) })
+afterEach(() => rmSync(root, { recursive: true, force: true }))
+
+async function prepared(file = join(root, "settings with ' quotes")) {
+ const command = join(root, 'engine')
+ writeFileSync(command, '#!/bin/sh\nprintf engine\n'); chmodSync(command, 0o700)
+ const executable = executableSnapshot(nativeVersionProbe({ args: [], output: /^$/, timeoutMs: 100 }, () => command))!
+ const proofs: HookPreparationProof[] = []
+ await runHookPreparation([file], attempt => inspectHookFile(file).replace('hooks', attempt), { confirmed: proof => proofs.push(proof) })
+ const launch: NativeLaunch = { executable, proofs, opencodeMajor: null, environment: {},
+ current: () => executable.current() && proofs.every(proof => proof.current()), ready: () => true,
+ prepareHooks: async () => true, permission: async () => 'supported' }
+ const run = () => execFileSync('/bin/sh', ['-c', nativeLaunchGuard(launch, process.execPath, 'printf held; exit 0') + 'printf ready'], { encoding: 'utf8', timeout: 5_000 })
+ return { command, file, run }
+}
+
+it('checks the prepared executable and durable hook files after shell startup', async () => {
+ const p = await prepared()
+ expect(p.run()).toBe('ready')
+ writeFileSync(p.command, '#!/bin/sh\nprintf replacement\n')
+ expect(p.run()).toBe('held')
+})
+
+it('holds changed hook contents without executing an engine', async () => {
+ const p = await prepared()
+ writeFileSync(p.file, 'foreign hooks')
+ expect(p.run()).toBe('held')
+})
+
+it('holds a redirected settings alias even when both files have matching contents', async () => {
+ const first = join(root, 'first'), second = join(root, 'second'), alias = join(root, 'alias')
+ writeFileSync(first, 'hooks'); writeFileSync(second, 'hooks'); symlinkSync(first, alias)
+ const p = await prepared(alias)
+ expect(p.run()).toBe('ready')
+ unlinkSync(alias); symlinkSync(second, alias)
+ expect(p.run()).toBe('held')
+})
+
+it('adds no guard for a terminal without a native executable', () => {
+ expect(nativeLaunchGuard({} as NativeLaunch, process.execPath, 'exit 1')).toBe('')
+})
+
+it('holds an inspected executable that never completed native preparation', async () => {
+ const p = await prepared()
+ const executable = executableSnapshot(nativeVersionProbe({ args: [], output: /^$/, timeoutMs: 100 }, () => p.command))!
+ const unprepared = { executable, proofs: [], ready: () => false } as unknown as NativeLaunch
+ const output = execFileSync('/bin/sh', ['-c', nativeLaunchGuard(unprepared, process.execPath, 'printf held; exit 0') + 'printf ready'], { encoding: 'utf8', timeout: 5_000 })
+ expect(output).toBe('held')
+})
diff --git a/cli/src/engines/kit/nativeLaunchGuard.ts b/cli/src/engines/kit/nativeLaunchGuard.ts
new file mode 100644
index 000000000..3b0879179
--- /dev/null
+++ b/cli/src/engines/kit/nativeLaunchGuard.ts
@@ -0,0 +1,25 @@
+/** A final check after login rc files, immediately before the prepared command. */
+import type { NativeLaunch } from '../nativeLaunch.js'
+import { shellSingleQuote } from '../../lib/shellQuote.js'
+
+/** JSON is passed as one literal argv. Nothing from a path is parsed as code. */
+export function nativeLaunchGuard(launch: NativeLaunch, node: string, held: string): string {
+ if (!launch.executable) return ''
+ const proof = { ready: launch.ready?.() !== false, command: launch.executable.command, identity: launch.executable.identity,
+ files: launch.proofs.flatMap(item => item.files) }
+ const verify = [
+ 'const fs=require("node:fs"),p=JSON.parse(process.argv[1]);',
+ 'const id=s=>`${s.dev}:${s.ino}:${s.mode}:${s.uid}`;',
+ 'const ver=s=>`${id(s)}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;',
+ 'const stamp=s=>`${s.dev}:${s.ino}:${s.uid}:${s.mode}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;',
+ 'const stat=p=>{try{return fs.lstatSync(p,{bigint:true})}catch(e){if(e.code==="ENOENT")return null;throw e}};',
+ 'try{if(!p.ready)throw 0;const s=fs.statSync(p.command,{bigint:true});',
+ 'if(`${p.command}:${fs.realpathSync(p.command)}:${s.dev}:${s.ino}:${s.mode}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`!==p.identity)throw 0;',
+ 'for(const f of p.files){for(const r of f.facts){const s=stat(r.path);',
+ 'if((s?id(s):null)!==r.identity)throw 0;',
+ 'if(r.alias&&(!s||ver(s)!==r.alias.version||fs.readlinkSync(r.path)!==r.alias.target))throw 0;}',
+ 'const s=stat(f.target);if((s?stamp(s):null)!==f.stamp)throw 0;}',
+ '}catch{process.exitCode=75}',
+ ].join('')
+ return `if ! ${shellSingleQuote(node)} -e ${shellSingleQuote(verify)} ${shellSingleQuote(JSON.stringify(proof))}; then\n${held}\nfi\n`
+}
diff --git a/cli/src/engines/kit/nativeLocations.ts b/cli/src/engines/kit/nativeLocations.ts
new file mode 100644
index 000000000..f1e874cd1
--- /dev/null
+++ b/cli/src/engines/kit/nativeLocations.ts
@@ -0,0 +1,62 @@
+/** Paths observed in the launch shell, used without changing daemon globals. */
+import { isAbsolute, join } from 'node:path'
+import type { HookPreparationOptions } from './nativeHookFiles.js'
+
+// Capture only launch locations, never vendor credentials. Pin these locations
+// again after rc files run in the pane, so preparation and execution agree.
+export const LAUNCH_LOCATION_VARIABLES = [
+ 'HOME', 'PATH', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME',
+ 'OPENCODE_CONFIG', 'OPENCODE_CONFIG_DIR', 'OPENCODE_DATA_DIR', 'OPENCODE_DB', 'PI_CODING_AGENT_DIR',
+ 'HERMES_HOME', 'CURSOR_CONFIG_DIR', 'CURSOR_DATA_DIR', 'GROK_HOME', 'AGY_HOME', 'COPILOT_HOME',
+ 'SHELL', 'ZDOTDIR', 'CLAUDE_PROJECTS_DIR', 'CURSOR_HOME', 'AGY_CONFIG_DIR', 'COMMANDCODE_HOME',
+ 'DEVIN_HOME', 'DEVIN_CONFIG_PATH', 'OPENCODE_PLUGIN_DIR', 'KILO_PLUGIN_DIR', 'PI_HOME',
+ 'PI_CODING_AGENT_SESSION_DIR', 'AMP_PLUGIN_DIR',
+] as const
+
+/** The shell can unset an inherited location. Absence is part of its snapshot. */
+export function nativeProcessEnvironment(locations: Readonly<NodeJS.ProcessEnv>, ambient: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
+ const result = { ...ambient }
+ for (const key of LAUNCH_LOCATION_VARIABLES) delete result[key]
+ return { ...result, ...locations }
+}
+
+/** OpenCode uses OPENCODE_DB, otherwise its XDG data root; OPENCODE_DATA_DIR is ignored. */
+export function nativeOpencodeStore(vars: Readonly<Record<string, string>>): string {
+ const store = vars.OPENCODE_DB || join(vars.XDG_DATA_HOME || join(vars.HOME, '.local', 'share'), 'opencode', 'opencode.db')
+ if (!isAbsolute(store) || store.includes('\0') || store.length > 4096) throw Error('Unconfirmed OpenCode store')
+ return store
+}
+
+export interface NativeHookOptions extends HookPreparationOptions {
+ environment?: Readonly<Record<string, string>>
+}
+
+export function nativeHookLocations(vars: Readonly<Record<string, string>>) {
+ const home = vars.HOME
+ if (!home || !isAbsolute(home)) throw Error('Unconfirmed native home')
+ const config = vars.XDG_CONFIG_HOME || join(home, '.config')
+ const data = vars.XDG_DATA_HOME || join(home, '.local', 'share')
+ const locations = {
+ CLAUDE_HOME: vars.CLAUDE_CONFIG_DIR || join(home, '.claude'),
+ CLAUDE_PROJECTS_DIR: vars.CLAUDE_CONFIG_DIR ? join(vars.CLAUDE_CONFIG_DIR, 'projects') : vars.CLAUDE_PROJECTS_DIR || join(home, '.claude', 'projects'),
+ CODEX_HOME: vars.CODEX_HOME || join(home, '.codex'),
+ GROK_HOME: vars.GROK_HOME || join(home, '.grok'),
+ AGY_HOME: vars.AGY_HOME || join(home, '.gemini', 'antigravity-cli'),
+ AGY_CONFIG_DIR: vars.AGY_CONFIG_DIR || join(home, '.gemini', 'config'),
+ COPILOT_HOME: vars.COPILOT_HOME || join(home, '.copilot'),
+ CURSOR_HOME: vars.CURSOR_DATA_DIR || vars.CURSOR_HOME || join(home, '.cursor'),
+ CURSOR_CONFIG_DIR: vars.CURSOR_CONFIG_DIR || (vars.XDG_CONFIG_HOME ? join(config, 'cursor') : vars.CURSOR_HOME || join(home, '.cursor')),
+ OPENCODE_PLUGIN_DIR: vars.OPENCODE_PLUGIN_DIR || join(vars.OPENCODE_CONFIG_DIR || join(config, 'opencode'), 'plugin'),
+ KILO_PLUGIN_DIR: vars.KILO_PLUGIN_DIR || join(config, 'kilo', 'plugin'),
+ PI_AGENT_DIR: vars.PI_CODING_AGENT_DIR || join(vars.PI_HOME || join(home, '.pi'), 'agent'),
+ HERMES_HOME: vars.HERMES_HOME || join(home, '.hermes'),
+ COMMANDCODE_HOME: vars.COMMANDCODE_HOME || join(home, '.commandcode'),
+ DEVIN_HOME: vars.DEVIN_HOME || join(data, 'devin', 'cli'),
+ DEVIN_CONFIG_PATH: vars.DEVIN_CONFIG_PATH || join(config, 'devin', 'config.json'),
+ AMP_PLUGIN_DIR: vars.AMP_PLUGIN_DIR || join(config, 'amp', 'plugins'),
+ }
+ if (Object.values(locations).some(path => !isAbsolute(path) || path.includes('\0') || path.length > 4096)) {
+ throw Error('Unconfirmed native location')
+ }
+ return locations
+}
diff --git a/cli/src/engines/kit/nativeMutationDispatch.spec.ts b/cli/src/engines/kit/nativeMutationDispatch.spec.ts
index 0afc58332..28c1947e6 100644
--- a/cli/src/engines/kit/nativeMutationDispatch.spec.ts
+++ b/cli/src/engines/kit/nativeMutationDispatch.spec.ts
@@ -1,13 +1,56 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createSessionModelControl } from './nativeSessionModel.js'
import { OPENCODE_SESSION_MODEL } from '../opencode/contract.js'
+import { applyOpencodeSessionModel } from '../launchControl.js'
+import { LAUNCH_LOCATION_VARIABLES, nativeOpencodeStore } from './nativeLocations.js'
const exec = vi.hoisted(() => vi.fn())
vi.mock('node:child_process', () => ({ execFile: exec }))
-afterEach(() => vi.clearAllMocks())
+afterEach(() => { vi.clearAllMocks(); vi.unstubAllEnvs() })
const model = { providerID: 'fixture', modelID: 'model' }
describe('native mutation process dispatch', () => {
+ it('carries the public apply API executable and absent native locations through the actual child options', async () => {
+ vi.stubEnv('XDG_DATA_HOME', '/fixture/ambient-data')
+ vi.stubEnv('OPENCODE_DB', '/fixture/ambient.db')
+ vi.stubEnv('OPENCODE_CONFIG', '/fixture/ambient-config.json')
+ const environment = { HOME: '/fixture/captured-home', PATH: '/fixture/bin' }
+ const executable = { command: '/fixture/captured/opencode', identity: 'captured', current: () => true }
+ exec.mockImplementation((_file, args: string[], _options, done) => {
+ const result = args[1] === 'model.list' ? [{ providerID: 'fixture', id: 'model' }]
+ : { data: { id: 'ses_captured', model: { providerID: 'fixture', id: 'model' } } }
+ queueMicrotask(() => done(null, JSON.stringify(result), ''))
+ return { stdin: { end: vi.fn() } }
+ })
+ expect(await applyOpencodeSessionModel({ opencodeMajor: 2, dbPath: nativeOpencodeStore(environment), sessionId: 'ses_captured', model, checkCatalog: true },
+ { executable, environment, retryDelayMs: 0 })).toEqual({ ok: true })
+ expect(exec.mock.calls.map(call => call[1][1])).toEqual(['model.list', 'session.switchModel', 'session.get'])
+ for (const [command, , options] of exec.mock.calls) {
+ expect(command).toBe(executable.command)
+ expect(options.env).toMatchObject(environment)
+ for (const key of ['XDG_DATA_HOME', 'OPENCODE_DB', 'OPENCODE_CONFIG']) expect(options.env).not.toHaveProperty(key)
+ }
+ expect(LAUNCH_LOCATION_VARIABLES).toContain('OPENCODE_DB')
+ expect(nativeOpencodeStore(environment)).toBe('/fixture/captured-home/.local/share/opencode/opencode.db')
+ expect(nativeOpencodeStore({ ...environment, XDG_DATA_HOME: '/fixture/data', OPENCODE_DATA_DIR: '/fixture/ignored' })).toBe('/fixture/data/opencode/opencode.db')
+ expect(nativeOpencodeStore({ ...environment, OPENCODE_DB: '/fixture/selected.db' })).toBe('/fixture/selected.db')
+ expect(() => nativeOpencodeStore({ ...environment, OPENCODE_DB: 'relative.db' })).toThrow('Unconfirmed')
+ })
+
+ it('does not reconcile an uncertain native write through a newly captured store environment', async () => {
+ const control = createSessionModelControl(OPENCODE_SESSION_MODEL, () => '/fixture/bin/opencode')
+ const run = vi.fn(async () => { throw Error('unavailable after dispatch') })
+ const input = { major: 2, dbPath: '/fixture/label.db', sessionId: 'ses_fixture', model }
+ const environment = { HOME: '/fixture/home', XDG_DATA_HOME: '/fixture/original' }
+ expect(await control.applySessionModel(input, { run, environment, retryDelayMs: 0 })).toMatchObject({ effect: 'uncertain' })
+ run.mockClear()
+ for (const env of [{ ...environment, XDG_DATA_HOME: '/fixture/replacement' }, { ...environment, OPENCODE_DB: '/fixture/other.db' }]) {
+ expect(await control.applySessionModel(input, { run, environment: env, retryDelayMs: 0 }))
+ .toMatchObject({ effect: 'uncertain', detail: expect.stringContaining('original store and folder') })
+ }
+ expect(run).not.toHaveBeenCalled()
+ })
+
it.each([null, 1])('does not bypass an unresolved API write when a later version probe says %s', async major => {
const control = createSessionModelControl(OPENCODE_SESSION_MODEL, () => '/fixture/bin/opencode')
const run = vi.fn(async () => { throw Error('native service unavailable after write') })
diff --git a/cli/src/engines/kit/nativeSessionModel.ts b/cli/src/engines/kit/nativeSessionModel.ts
index d045834c6..4513c00e4 100644
--- a/cli/src/engines/kit/nativeSessionModel.ts
+++ b/cli/src/engines/kit/nativeSessionModel.ts
@@ -1,13 +1,15 @@
+import type { NativeExecutableSnapshot } from './nativeVersion.js'
/** Native launch writes from an engine's declared SQLite transaction or CLI API protocol.
* Optional history readers never own these operations. Compatibility extraction first;
* cancellation and uncertain-write corrections are tracked in the OpenCode control research note. */
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
+import { LAUNCH_LOCATION_VARIABLES, nativeProcessEnvironment } from './nativeLocations.js'
export interface NativeSessionModel { providerID: string; modelID: string }
export type NativeModelResult = { ok: true } | { ok: false; code: string; detail: string; effect?: 'uncertain' }
export type NativeApiRun = (args: string[], options: { cwd?: string }) => Promise<{ stdout: string }>
-export interface NativeModelAuthority { current?: () => boolean }
+export interface NativeModelAuthority { current?: () => boolean; executable?: NativeExecutableSnapshot; environment?: NodeJS.ProcessEnv }
export interface NativeModelRule {
label: string; serviceMajor: number; id: RegExp; modelFlags: readonly string[]; modelEquals: string; variantSeparator: string
errors: { sqliteMissing: string; sessionMissing: string; writeFailed: string; binaryMissing: string; switchFailed: string; unknownModel: string }
@@ -27,7 +29,7 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
// An uncertain write cannot be forgotten just because its request returned. Keep
// one receipt per conversation until a later read confirms it. At capacity, hold
// new work instead of evicting a receipt and making a blind retry possible.
- type Pending = { model: NativeSessionModel; cwd?: string; store?: string; busy: boolean; dispatched: boolean; executable?: Promise<string> }
+ type Pending = { model: NativeSessionModel; cwd?: string; store?: string; environment?: string; busy: boolean; dispatched: boolean; executable?: Promise<string> }
const pending = new Map<string, Pending>()
const capacity = 256
/** A SQL string literal — the only way a value reaches the statement. */
@@ -118,15 +120,16 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
return { ok: true }
}
- const nativeRun = (authority: NativeModelAuthority, selection: { executable?: Promise<string> }): NativeApiRun => {
+ const nativeRun = (authority: NativeModelAuthority, selection: { executable?: Promise<string>; snapshot?: NativeExecutableSnapshot }): NativeApiRun => {
// Resolve once for this operation, before its first native command. Resolving
// through a login shell can yield; cancellation must be checked afterwards.
return async (args, options) => {
- selection.executable ??= Promise.resolve().then(binary)
+ selection.snapshot ??= authority.executable
+ selection.executable ??= authority.executable ? Promise.resolve(authority.executable.command) : Promise.resolve().then(binary)
const executable = await selection.executable
- if (authority.current?.() === false) throw new NativeDispatchCancelled('Native model operation was cancelled before dispatch')
+ if (authority.current?.() === false || selection.snapshot?.current() === false || authority.executable?.current() === false) throw new NativeDispatchCancelled('Native model operation was cancelled before dispatch')
return new Promise((done, failed) => {
- const child = execFile(executable, args, { ...(options.cwd ? { cwd: options.cwd } : {}),
+ const child = execFile(executable, args, { ...(authority.environment ? { env: nativeProcessEnvironment(authority.environment) } : {}), ...(options.cwd ? { cwd: options.cwd } : {}),
timeout: rule.api.timeoutMs, killSignal: 'SIGKILL', maxBuffer: 1024 * 1024, encoding: 'utf8',
}, (error, stdout, stderr) => { if (error) failed(Object.assign(error, { stdout, stderr })); else done({ stdout }) })
child.stdin?.end()
@@ -160,7 +163,7 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
model: NativeSessionModel,
options: { cwd?: string; store?: string; run?: NativeApiRun; checkCatalog?: boolean; retryDelayMs?: number } & NativeModelAuthority = {},
): Promise<NativeModelResult> {
- options = { ...options }
+ options = { ...options, ...(options.environment ? { environment: { ...options.environment } } : {}) }
const current = () => options.current?.() !== false
if (!current()) return changed()
if (!ID_RE.test(sessionId)) {
@@ -168,14 +171,17 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
}
const requested = { ...model }
const previous = pending.get(sessionId)
+ // A receipt is evidence about one captured native store, not permission for
+ // a later shell/profile to reinterpret an uncertain write at the same id.
+ const environment = options.environment && JSON.stringify(LAUNCH_LOCATION_VARIABLES.map(key => options.environment![key] ?? null))
const held = (detail: string): NativeModelResult => ({ ok: false, code: rule.errors.switchFailed, detail,
...(previous?.dispatched ? { effect: 'uncertain' as const } : {}) })
if (previous?.busy) return held('Waiting for the native model operation already running for this conversation. No additional change was sent.')
- if (previous && (previous.cwd !== options.cwd || previous.store !== options.store)) {
+ if (previous && (previous.cwd !== options.cwd || previous.store !== options.store || previous.environment !== environment)) {
return held('Waiting to confirm the earlier native model change in its original store and folder. No additional change was sent.')
}
if (!previous && pending.size >= capacity) return held('Waiting for outstanding native model changes to be confirmed. No model change was sent.')
- const receipt: Pending = previous ?? { model: requested, cwd: options.cwd, store: options.store, busy: false, dispatched: false }
+ const receipt: Pending = previous ?? { model: requested, cwd: options.cwd, store: options.store, environment, busy: false, dispatched: false }
receipt.busy = true
pending.set(sessionId, receipt)
const run = options.run ?? nativeRun(options, receipt)
@@ -300,7 +306,7 @@ export function createSessionModelControl(rule: NativeModelRule, binary: () => s
): Promise<NativeModelResult> {
if (deps.current?.() === false) return changed()
if ((input.major ?? 0) >= rule.serviceMajor) {
- return switchSessionModel(input.sessionId, input.model, { cwd: input.cwd, store: input.dbPath, run: deps.run, checkCatalog: input.checkCatalog, retryDelayMs: deps.retryDelayMs, current: deps.current })
+ return switchSessionModel(input.sessionId, input.model, { ...deps, cwd: input.cwd, store: input.dbPath, checkCatalog: input.checkCatalog })
}
const written = await setSessionModel(input.dbPath, input.sessionId, input.model, deps)
return !written.ok && written.code === rule.errors.sessionMissing ? { ok: true } : written
diff --git a/cli/src/engines/kit/nativeVersion.ts b/cli/src/engines/kit/nativeVersion.ts
index 33c0d3f19..dc7eb6091 100644
--- a/cli/src/engines/kit/nativeVersion.ts
+++ b/cli/src/engines/kit/nativeVersion.ts
@@ -24,7 +24,7 @@ export function parseMajor(rule: VersionRule, output: string): number | null {
return match ? Number(match[1]) : null
}
-export function nativeVersionProbe(rule: VersionRule, binary: () => string): NativeVersionProbe {
+export function nativeVersionProbe(rule: VersionRule, binary: () => string, environment?: NodeJS.ProcessEnv): NativeVersionProbe {
// One attempt resolves one command. Previously identity() and read() resolved
// independently, so a PATH/config change could cache B's answer under A's key.
let selected: string | null | undefined
@@ -50,7 +50,7 @@ export function nativeVersionProbe(rule: VersionRule, binary: () => string): Nat
const file = path()
if (!file) { failed(new Error('Native executable is unavailable')); return }
const child = execFile(file, [...rule.args], {
- encoding: 'utf8', timeout: rule.timeoutMs, killSignal: 'SIGKILL', maxBuffer: 64 * 1024,
+ env: environment, encoding: 'utf8', timeout: rule.timeoutMs, killSignal: 'SIGKILL', maxBuffer: 64 * 1024,
}, (error, stdout) => { if (error) failed(error); else done(stdout) })
child.stdin?.end()
}),
diff --git a/cli/src/engines/kit/notifyHooks.ts b/cli/src/engines/kit/notifyHooks.ts
index 1ffdf25e1..c81885afa 100644
--- a/cli/src/engines/kit/notifyHooks.ts
+++ b/cli/src/engines/kit/notifyHooks.ts
@@ -6,6 +6,7 @@ import { env } from '../../config/env.js'
import { managedNodePath } from '../../lib/nodeRuntime.js'
import { HookPreparationHeld } from './nativeHookFiles.js'
import { cursorDataDir } from '../cursor/contract.js'
+import { nativeHookLocations } from './nativeLocations.js'
// notify.mjs location depends on the layout (import.meta.url is the REAL executing file at runtime):
// - packaged/bundled: cli.js at ~/.harness/cli/cli.js → notify.mjs is a SIBLING (dist/ bundle too).
@@ -43,7 +44,9 @@ export function command(
// config.yaml, and the block in it carried the DEFAULT home — so the hook looked the session up in
// a store it was not in (openharness#191). See installHermesHooks.
hermesHome: string = env.HERMES_HOME,
+ environment?: Readonly<Record<string, string>>,
): string {
+ const homes = environment ? nativeHookLocations(environment) : { ...env, CURSOR_HOME: cursorDataDir() }
return [
// Absolute, never the bare word `node`. This string is executed later by the ENGINE, in a shell
// whose PATH is none of our business — and since the product ships its own Node, a computer with
@@ -53,15 +56,15 @@ export function command(
shellQuote(HOOK_SCRIPT),
'--port', String(port),
'--data-dir', shellQuote(env.ADAPTER_DATA_DIR),
- '--claude-projects-dir', shellQuote(env.CLAUDE_PROJECTS_DIR),
- '--codex-home', shellQuote(codexHome),
- '--grok-home', shellQuote(env.GROK_HOME),
- '--cursor-home', shellQuote(cursorDataDir()),
- '--hermes-home', shellQuote(hermesHome),
- '--commandcode-home', shellQuote(env.COMMANDCODE_HOME),
- '--devin-home', shellQuote(env.DEVIN_HOME),
- '--agy-home', shellQuote(env.AGY_HOME),
- '--copilot-home', shellQuote(env.COPILOT_HOME),
+ '--claude-projects-dir', shellQuote(homes.CLAUDE_PROJECTS_DIR),
+ '--codex-home', shellQuote(environment ? homes.CODEX_HOME : codexHome),
+ '--grok-home', shellQuote(homes.GROK_HOME),
+ '--cursor-home', shellQuote(homes.CURSOR_HOME),
+ '--hermes-home', shellQuote(environment ? homes.HERMES_HOME : hermesHome),
+ '--commandcode-home', shellQuote(homes.COMMANDCODE_HOME),
+ '--devin-home', shellQuote(homes.DEVIN_HOME),
+ '--agy-home', shellQuote(homes.AGY_HOME),
+ '--copilot-home', shellQuote(homes.COPILOT_HOME),
...(engine !== 'claude' ? ['--engine', engine] : []),
].join(' ')
}
@@ -112,7 +115,7 @@ export function isOurs(block: HookBlock): boolean {
/** A managed command can share a block with somebody else's command. Updating
* ours must keep those siblings and the block's matcher and other fields. */
-export function foreignHookBlocks(blocks: HookBlock[]): HookBlock[] {
+export function foreignHookBlocks(blocks: HookBlock[], owns: (block: HookBlock) => boolean = isOurs): HookBlock[] {
for (const block of blocks) {
if (!block || typeof block !== 'object' || !Array.isArray(block.hooks) || block.hooks.some(hook =>
!hook || typeof hook !== 'object' || (hook.command !== undefined && typeof hook.command !== 'string'))) {
@@ -120,8 +123,8 @@ export function foreignHookBlocks(blocks: HookBlock[]): HookBlock[] {
}
}
return blocks.flatMap(block => {
- if (!isOurs(block)) return [block]
- const hooks = block.hooks.filter(hook => !isOurs({ hooks: [hook] }))
+ if (!owns(block)) return [block]
+ const hooks = block.hooks.filter(hook => !owns({ hooks: [hook] }))
return hooks.length ? [{ ...block, hooks }] : []
})
}
diff --git a/cli/src/engines/launchPrep.ts b/cli/src/engines/launchPrep.ts
index afced0349..2c5903482 100644
--- a/cli/src/engines/launchPrep.ts
+++ b/cli/src/engines/launchPrep.ts
@@ -25,10 +25,10 @@ export interface FolderTrust {
* one; null for an engine that asks no such question. The home is found at each call, as the person's shell
* may have moved it since.
*/
-export function folderTrust(engine: AgentEngine, profile?: string | null): FolderTrust | null {
+export function folderTrust(engine: AgentEngine, profile?: string | null, environment?: NodeJS.ProcessEnv): FolderTrust | null {
const trust = launchContract(engine)?.trust
if (!trust) return null
- const file = (): string => join(launchHomeOf(trust.home, profile), trust.file)
+ const file = (): string => join(launchHomeOf(trust.home, profile, environment), trust.file)
return { trusts: (path) => trustsIn(trust, file(), path), record: (path) => recordTrustIn(trust, file(), path) }
}
diff --git a/cli/src/engines/nativeHookPreparation.spec.ts b/cli/src/engines/nativeHookPreparation.spec.ts
index 4d2535f1c..b4e3c2e8b 100644
--- a/cli/src/engines/nativeHookPreparation.spec.ts
+++ b/cli/src/engines/nativeHookPreparation.spec.ts
@@ -1,10 +1,10 @@
-import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync, chmodSync, symlinkSync, renameSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync, chmodSync, symlinkSync, renameSync, unlinkSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
-const probe = vi.hoisted(() => ({ major: 1 as number | null, failSync: false, failRemove: false, beforeSync: undefined as (() => Promise<void>) | undefined, onStat: undefined as ((path: unknown) => void) | undefined }))
-vi.mock('./launchControl.js', () => ({ opencodeMajorVersion: async () => probe.major }))
+const probe = vi.hoisted(() => ({ major: 1 as number | null, beforeProbe: undefined as (() => Promise<void>) | undefined, failSync: false, failRemove: false, beforeSync: undefined as (() => Promise<void>) | undefined, onStat: undefined as ((path: unknown) => void) | undefined }))
+vi.mock('./launchControl.js', () => ({ opencodeMajorVersion: async () => { await probe.beforeProbe?.(); return probe.major } }))
vi.mock('node:fs', async original => {
const fs = await original<typeof import('node:fs')>()
return { ...fs,
@@ -18,7 +18,7 @@ vi.mock('node:fs', async original => {
})
const roots: string[] = []
afterEach(() => {
- probe.major = 1; probe.failSync = false; probe.failRemove = false; probe.beforeSync = undefined; probe.onStat = undefined
+ probe.major = 1; probe.beforeProbe = undefined; probe.failSync = false; probe.failRemove = false; probe.beforeSync = undefined; probe.onStat = undefined
vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.resetModules()
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
@@ -342,3 +342,63 @@ it('rechecks the OpenCode deadline after final proof reads', async () => {
})
expect(await install(4242, undefined, { timeoutMs: 10 })).toBe(false)
})
+
+it('keeps the original route when following a newer OpenCode publisher', async () => {
+ const { root, install } = await fixture()
+ const a = join(root, 'route-a'), b = join(root, 'route-b'), alias = join(root, 'selected-config')
+ mkdirSync(a); mkdirSync(b); symlinkSync(a, alias)
+ const environment = { HOME: join(root, 'HOME'), OPENCODE_PLUGIN_DIR: join(alias, 'plugin') }
+ const snapshot = { command: '/fixture/opencode', identity: 'same-executable', major: 2, current: () => true }
+ let release!: () => void, began!: () => void
+ const paused = new Promise<void>(done => { release = done }), started = new Promise<void>(done => { began = done })
+ probe.beforeSync = async () => { probe.beforeSync = undefined; began(); await paused }
+ const confirmed = vi.fn()
+ const first = install(4242, snapshot, { environment, confirmed })
+ try {
+ await started
+ unlinkSync(alias); symlinkSync(b, alias)
+ expect(await install(4242, snapshot, { environment })).toBe(true)
+ } finally { release() }
+ expect(await first).toBe(false)
+ expect(confirmed).not.toHaveBeenCalled()
+})
+
+it('cannot write through a route that changed during the version probe', async () => {
+ const { root, install } = await fixture()
+ const a = join(root, 'probe-a'), b = join(root, 'probe-b'), alias = join(root, 'probe-selected')
+ mkdirSync(a); mkdirSync(b); symlinkSync(a, alias)
+ const environment = { HOME: join(root, 'HOME'), OPENCODE_PLUGIN_DIR: join(alias, 'plugin') }
+ let release!: () => void
+ probe.beforeProbe = () => new Promise<void>(done => { release = done })
+ const preparing = install(4242, undefined, { environment })
+ unlinkSync(alias); symlinkSync(b, alias)
+ release()
+ expect(await preparing).toBe(false)
+ expect(() => readFileSync(join(b, 'plugin/launcher-register.js'))).toThrow()
+ expect(() => readFileSync(join(b, 'plugins/launcher-register/tui.js'))).toThrow()
+})
+
+it.each(['deadline', 'owner', 'executable'] as const)('checks %s after the last original-route verification', async reason => {
+ const { install } = await fixture()
+ let time = 0, owner = true, executable = true, verifications = 0
+ vi.spyOn(performance, 'now').mockImplementation(() => time)
+ const files = await import('./kit/nativeHookFiles.js'), capture = files.hookPreparationRoutes
+ vi.spyOn(files, 'hookPreparationRoutes').mockImplementation(paths => {
+ const original = capture(paths)
+ return { ...original, verify: () => {
+ original.verify()
+ if (++verifications === 2) {
+ if (reason === 'deadline') time = 20
+ else if (reason === 'owner') owner = false
+ else executable = false
+ }
+ } }
+ })
+ vi.spyOn(files, 'runHookPreparation').mockImplementationOnce(async (_files, _work, options) => {
+ options?.confirmed?.({ files: [], current: () => true }); return true as never
+ })
+ const confirmed = vi.fn()
+ expect(await install(4242, { command: '/fixture/opencode', identity: 'fixture', major: 2, current: () => executable },
+ { timeoutMs: 10, current: () => owner, confirmed })).toBe(false)
+ expect(confirmed).not.toHaveBeenCalled()
+})
diff --git a/cli/src/engines/nativeHooks.ts b/cli/src/engines/nativeHooks.ts
index 0cf2d4fa1..7fdcca7ad 100644
--- a/cli/src/engines/nativeHooks.ts
+++ b/cli/src/engines/nativeHooks.ts
@@ -1,6 +1,7 @@
/** Native hook installation is eager. Optional transcript and screen readers own no hook files. */
-import { join } from 'node:path'
-import { runHookPreparation, type HookPreparationOptions, type HookPreparationProof } from './kit/nativeHookFiles.js'
+import { dirname, join } from 'node:path'
+import { hookPreparationRoutes, runHookPreparation, type HookPreparationProof } from './kit/nativeHookFiles.js'
+import { nativeHookLocations, type NativeHookOptions } from './kit/nativeLocations.js'
import { env } from '../config/env.js'
import { VERSION } from '../version.js'
import { OPENCODE_LEGACY_PLUGIN, OPENCODE_TUI_PLUGIN, OPENCODE_LEGACY_REMOVAL, OPENCODE_VERSION } from './opencode/contract.js'
@@ -20,59 +21,70 @@ import { COMMANDCODE_HOOK_SETTINGS } from './commandcode/contract.js'
import { DEVIN_HOOK_SETTINGS } from './devin/contract.js'
import { installNativeHookSettings } from './kit/nativeHookSettings.js'
-export const installGrokHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(GROK_HOOK_SETTINGS, port, options)
-export const installAgyHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(AGY_HOOK_SETTINGS, port, options)
-export const installCopilotHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(COPILOT_HOOK_SETTINGS, port, options)
-export const installCursorHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(CURSOR_HOOK_SETTINGS, port, options)
-export const installCommandCodeHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(COMMANDCODE_HOOK_SETTINGS, port, options)
-export const installDevinHooks = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativeHookSettings(DEVIN_HOOK_SETTINGS, port, options)
+export const installGrokHooks = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativeHookSettings(options?.environment ? { ...GROK_HOOK_SETTINGS, file: join(nativeHookLocations(options.environment).GROK_HOME, 'hooks', 'harness.json') } : GROK_HOOK_SETTINGS, port, options)
+export const installAgyHooks = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativeHookSettings(options?.environment ? { ...AGY_HOOK_SETTINGS, file: join(nativeHookLocations(options.environment).AGY_CONFIG_DIR, 'hooks.json') } : AGY_HOOK_SETTINGS, port, options)
+export const installCopilotHooks = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativeHookSettings(options?.environment ? { ...COPILOT_HOOK_SETTINGS, file: join(nativeHookLocations(options.environment).COPILOT_HOME, 'hooks', 'harness.json') } : COPILOT_HOOK_SETTINGS, port, options)
+export const installCursorHooks = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativeHookSettings(options?.environment ? { ...CURSOR_HOOK_SETTINGS, file: join(nativeHookLocations(options.environment).CURSOR_CONFIG_DIR, 'hooks.json') } : CURSOR_HOOK_SETTINGS, port, options)
+export const installCommandCodeHooks = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativeHookSettings(options?.environment ? { ...COMMANDCODE_HOOK_SETTINGS, file: join(nativeHookLocations(options.environment).COMMANDCODE_HOME, 'settings.json') } : COMMANDCODE_HOOK_SETTINGS, port, options)
+export const installDevinHooks = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativeHookSettings(options?.environment ? { ...DEVIN_HOOK_SETTINGS, file: nativeHookLocations(options.environment).DEVIN_CONFIG_PATH } : DEVIN_HOOK_SETTINGS, port, options)
const pluginValues = (port: number) => ({
port: String(port), credential: JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential')), version: JSON.stringify(VERSION),
})
-export const installKiloPlugin = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativePlugin(KILO_PLUGIN, pluginValues(port), options)
-export const installPiExtension = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativePlugin(PI_EXTENSION, pluginValues(port), options)
-export const installAmpPlugin = (port: number, options?: HookPreparationOptions): Promise<boolean> => installNativePlugin(AMP_PLUGIN, pluginValues(port), options)
-export const installHermesHooks = (port: number, selectedHome?: string, options?: HookPreparationOptions): Promise<boolean> =>
- installNativeYamlHooks(HERMES_HOOK_SETTINGS, home => command(port, 'hermes', env.CODEX_HOME, home), selectedHome, options)
+export const installKiloPlugin = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativePlugin(options?.environment ? { ...KILO_PLUGIN, file: join(nativeHookLocations(options.environment).KILO_PLUGIN_DIR, 'launcher-register.js') } : KILO_PLUGIN, pluginValues(port), options)
+export const installPiExtension = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativePlugin(options?.environment ? { ...PI_EXTENSION, file: join(nativeHookLocations(options.environment).PI_AGENT_DIR, 'extensions', 'launcher-register.ts') } : PI_EXTENSION, pluginValues(port), options)
+export const installAmpPlugin = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativePlugin(options?.environment ? { ...AMP_PLUGIN, file: join(nativeHookLocations(options.environment).AMP_PLUGIN_DIR, 'launcher-register.ts') } : AMP_PLUGIN, pluginValues(port), options)
+export const installHermesHooks = (port: number, selectedHome?: string, options?: NativeHookOptions): Promise<boolean> =>
+ installNativeYamlHooks(HERMES_HOOK_SETTINGS, home => command(port, 'hermes', env.CODEX_HOME, home, options?.environment), selectedHome,
+ { ...options, createMissing: !!selectedHome && !!options?.environment })
/** Install both discovery surfaces for v1; v2 must not load our incompatible v1 export. */
interface OpencodeInstallation { port: number; executable?: string; major?: number | null; done: Promise<boolean>; proofs: HookPreparationProof[] }
-let opencodeInstallation: OpencodeInstallation | undefined
-export async function installOpencodePlugin(port: number, snapshot?: OpencodeLaunchSnapshot, options: HookPreparationOptions = {}): Promise<boolean> {
+const opencodeInstallations = new Map<string, { current: OpencodeInstallation; users: number }>()
+export async function installOpencodePlugin(port: number, snapshot?: OpencodeLaunchSnapshot, options: NativeHookOptions = {}): Promise<boolean> {
const deadline = performance.now() + (options.timeoutMs ?? OPENCODE_VERSION.timeoutMs)
+ const root = options.environment ? nativeHookLocations(options.environment).OPENCODE_PLUGIN_DIR : dirname(OPENCODE_LEGACY_PLUGIN.file)
+ const legacyRule = { ...OPENCODE_LEGACY_PLUGIN, file: join(root, 'launcher-register.js') }
+ const tuiRule = { ...OPENCODE_TUI_PLUGIN, file: join(dirname(root), 'plugins', 'launcher-register', 'tui.js') }
+ const removalRule = { ...OPENCODE_LEGACY_REMOVAL, file: legacyRule.file }
+ let routes: ReturnType<typeof hookPreparationRoutes>
+ try { routes = hookPreparationRoutes([legacyRule.file, tuiRule.file]) } catch { return false }
const installation: OpencodeInstallation = { port, executable: snapshot?.identity, done: Promise.resolve(false), proofs: [] }
- opencodeInstallation = installation
+ if (opencodeInstallations.size >= 128 && !opencodeInstallations.has(root)) return false
+ const group = opencodeInstallations.get(root) ?? { current: installation, users: 0 }
+ group.current = installation; group.users++
+ opencodeInstallations.set(root, group)
+ try {
installation.done = (async () => {
const values = pluginValues(port)
const major = snapshot ? snapshot.major : await opencodeMajorVersion()
installation.major = major
// A newer request may have installed an upgraded/downgraded engine's hooks
// while this probe waited. Only the latest request can change those files.
- if (installation !== opencodeInstallation || snapshot?.current() === false) return false
+ if (installation !== group.current || snapshot?.current() === false) return false
// Keep the existing first-install route until installer-only continuation
// can return through launch preparation. A missing executable also gives
// null here; refusing it would prevent create from reaching its installer.
// Whole-launch preparation must confirm a version before native dispatch.
- try { return await runHookPreparation([OPENCODE_LEGACY_PLUGIN.file, OPENCODE_TUI_PLUGIN.file], async attempt => {
+ try { routes.verify(); return await runHookPreparation([legacyRule.file, tuiRule.file], async attempt => {
// Inspect both destinations before publishing. A foreign legacy plugin
// cannot authorize even the first half of an upgrade's writes.
- const legacy = major === 1 ? prepareNativePlugin(OPENCODE_LEGACY_PLUGIN, values) : prepareNativePluginRemoval(OPENCODE_LEGACY_REMOVAL)
- const tui = prepareNativePlugin(OPENCODE_TUI_PLUGIN, values)
+ const legacy = major === 1 ? prepareNativePlugin(legacyRule, values) : prepareNativePluginRemoval(removalRule)
+ const tui = prepareNativePlugin(tuiRule, values)
legacy.verify(); tui.verify()
const removedOrInstalled = await legacy.commit(attempt), installed = await tui.commit(attempt)
removedOrInstalled.verify(); installed.verify()
return snapshot?.current() !== false
}, { ...options, timeoutMs: Math.max(0, deadline - performance.now()), confirmed: proof => installation.proofs.push(proof), identity: JSON.stringify([port, snapshot?.identity, major]),
- current: () => opencodeInstallation?.port === port && opencodeInstallation.executable === installation.executable
- && opencodeInstallation.major === major && performance.now() < deadline && snapshot?.current() !== false && options.current?.() !== false }) } catch (error) {
+ current: () => group.current.port === port && group.current.executable === installation.executable
+ && group.current.major === major && performance.now() < deadline && snapshot?.current() !== false && options.current?.() !== false }) } catch (error) {
console.error('[hooks] OpenCode preparation held:', error)
return false
}
})()
let current = installation, installed = await current.done
- while (current !== opencodeInstallation) {
- current = opencodeInstallation!
+ while (current !== group.current) {
+ current = group.current
// Two healthy creates must not fail merely because they overlap. Follow the
// current installation without restoring an obsolete request's write rights.
// A port change or continuing churn cannot make this caller wait forever.
@@ -89,6 +101,11 @@ export async function installOpencodePlugin(port: number, snapshot?: OpencodeLau
}
if (!installed || performance.now() >= deadline || options.current?.() === false || snapshot?.current() === false || current.proofs.some(proof => !proof.current())) return false
if (performance.now() >= deadline) return false
- for (const proof of current.proofs) options.confirmed?.(proof)
+ try { routes.verify() } catch { return false }
+ if (performance.now() >= deadline || options.current?.() === false || snapshot?.current() === false) return false
+ for (const proof of current.proofs) options.confirmed?.({ ...proof, current: () => {
+ try { routes.verify(); return proof.current() } catch { return false }
+ } })
return true
+ } finally { if (--group.users === 0) opencodeInstallations.delete(root) }
}
diff --git a/cli/src/engines/nativeLaunch.spec.ts b/cli/src/engines/nativeLaunch.spec.ts
new file mode 100644
index 000000000..4bdc7f7e4
--- /dev/null
+++ b/cli/src/engines/nativeLaunch.spec.ts
@@ -0,0 +1,224 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { inspectNativeLaunch } from './nativeLaunch.js'
+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[] }))
+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) => {
+ 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)
+ if (fixture.stalled) fixture.pending.push(settle); else queueMicrotask(settle)
+ return { stdin: { end: vi.fn() } }
+} }))
+vi.mock('./hooks.js', () => ({ engineHooks: { claude: { installIn: vi.fn(async () => fixture.hooks) }, codex: { installIn: vi.fn(async () => fixture.hooks) } } }))
+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 = [] })
+afterEach(() => { vi.clearAllMocks(); vi.unstubAllEnvs() })
+
+it('needs no executable, hooks or probes for a terminal', async () => {
+ const prepared = await inspectNativeLaunch('terminal')
+ expect(prepared.ok).toBe(true)
+ if (!prepared.ok) throw new Error('terminal was held')
+ expect(prepared.launch.current()).toBe(true)
+ expect(await prepared.launch.prepareHooks(19473, () => true)).toBe(true)
+ expect(await prepared.launch.permission({ bypassPermission: true })).toBe('supported')
+ expect(captureLaunchExecutable).not.toHaveBeenCalled()
+})
+it('retains one executable for version, permission and OpenCode hooks', async () => {
+ const prepared = await inspectNativeLaunch('opencode', { bypassPermission: true })
+ expect(prepared.ok).toBe(true)
+ if (!prepared.ok) throw new Error('fixture was held')
+ expect(prepared.launch.opencodeMajor).toBe(2)
+ expect(await prepared.launch.prepareHooks(19473, () => true)).toBe(true)
+ expect(hooks.installOpencodePlugin).toHaveBeenCalledWith(19473, expect.objectContaining({ command: '/fixture/engine', major: 2 }), expect.any(Object))
+ expect(fixture.calls).toEqual(['/fixture/engine', '/fixture/engine'])
+ fixture.current = false
+ expect(prepared.launch.current()).toBe(false)
+ expect(await prepared.launch.prepareHooks(19473, () => true)).toBe(false)
+ expect(await prepared.launch.permission({ bypassPermission: true })).toBe('unknown')
+})
+it('holds an unavailable version without caching a permanent unknown', async () => {
+ fixture.version = 'unreadable'
+ expect(await inspectNativeLaunch('opencode')).toMatchObject({ ok: false, unavailable: 'native' })
+ fixture.version = '1.18.0'
+ expect(await inspectNativeLaunch('opencode')).toMatchObject({ ok: true, launch: { opencodeMajor: 1 } })
+})
+
+it('revokes every hook write when a retained configuration loses authority', async () => {
+ const result = await inspectNativeLaunch('codex')
+ if (!result.ok) throw Error('fixture held')
+ let configCurrent = true
+ expect(result.launch.retain?.({ files: [], current: () => configCurrent })).toBe(true)
+ configCurrent = false
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(false)
+ expect(engineHooks.codex.installIn).not.toHaveBeenCalled()
+ configCurrent = true
+ vi.mocked(engineHooks.codex.installIn).mockImplementationOnce(async (_port, _home, options) => {
+ expect(options!.current!()).toBe(true)
+ configCurrent = false
+ expect(options!.current!()).toBe(false)
+ return true
+ })
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(false)
+ expect(result.launch.current()).toBe(false)
+})
+it('keeps installer-only work distinct from a confirmed executable', async () => {
+ const recipe = { command: 'fixture install', source: 'https://example.test', executable: { names: ['fixture'] } }
+ vi.mocked(captureLaunchExecutable).mockResolvedValueOnce({ state: 'install', recipe, environment: { HOME: '/fixture/home', PATH: '/fixture/bin' } })
+ expect(await inspectNativeLaunch('opencode')).toMatchObject({ ok: false, unavailable: 'native', install: recipe })
+ expect(hooks.installOpencodePlugin).not.toHaveBeenCalled()
+})
+it('holds incomplete capture and relative homes', async () => {
+ vi.mocked(captureLaunchExecutable).mockResolvedValueOnce({ state: 'held', detail: 'fixture shell unavailable' })
+ expect(await inspectNativeLaunch('codex')).toMatchObject({ ok: false, detail: 'fixture shell unavailable' })
+ expect(await inspectNativeLaunch('codex', { codexHome: 'relative' })).toMatchObject({ ok: false, unavailable: 'native' })
+})
+it.each(['claude', 'codex', 'hermes'] as const)('prepares the captured %s profile and pins it after shell startup', async engine => {
+ const prepared = await inspectNativeLaunch(engine)
+ if (!prepared.ok) throw new Error('fixture was held')
+ expect(Object.values(prepared.launch.environment)).toContain(`/fixture/${engine}`)
+ expect(await prepared.launch.prepareHooks(19473, () => true)).toBe(true)
+ if (engine === 'hermes') expect(hooks.installHermesHooks).toHaveBeenCalledWith(19473, '/fixture/hermes', expect.any(Object))
+ else expect(engineHooks[engine].installIn).toHaveBeenCalledWith(19473, `/fixture/${engine}`, expect.any(Object))
+ fixture.hooks = false
+ expect(await prepared.launch.prepareHooks(19473, () => true)).toBe(false)
+ expect(await prepared.launch.prepareHooks(19473, () => false)).toBe(false)
+})
+it('does not treat a longer flag as support for the selected permission mode', async () => {
+ const prepared = await inspectNativeLaunch('opencode')
+ if (!prepared.ok) throw new Error('fixture was held')
+ fixture.help = '--auto-update'
+ expect(await prepared.launch.permission({ bypassPermission: true })).toBe('unsupported')
+})
+
+it.each(['claude', 'codex'] as const)('confirms the final %s home before acknowledging hooks or readiness', async engine => {
+ const confirmHome = vi.fn<() => void>(() => { throw Error('adoption storage unavailable') })
+ const result = await inspectNativeLaunch(engine, {}, { confirmHome })
+ if (!result.ok) throw Error('fixture held')
+ const variable = engine === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME'
+ const selected = `/fixture/${engine}`
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(false)
+ expect(confirmHome).toHaveBeenCalledWith(engine, selected)
+ expect(result.launch.ready?.()).toBe(false)
+ confirmHome.mockImplementation(() => {})
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(true)
+ expect(result.launch.ready?.()).toBe(true)
+ expect(result.launch.environment[variable]).toBe(selected)
+})
+
+it('does not adopt a home when hooks fail or the owner is revoked', async () => {
+ const confirmHome = vi.fn()
+ const result = await inspectNativeLaunch('codex', {}, { confirmHome })
+ if (!result.ok) throw Error('fixture held')
+ fixture.hooks = false
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(false)
+ expect(confirmHome).not.toHaveBeenCalled()
+ fixture.hooks = true
+ expect(await result.launch.prepareHooks(19473, () => false)).toBe(false)
+ expect(confirmHome).not.toHaveBeenCalled()
+ let owner = true
+ confirmHome.mockImplementation(() => { owner = false })
+ expect(await result.launch.prepareHooks(19473, () => owner)).toBe(false)
+ expect(result.launch.ready?.()).toBe(false)
+})
+
+it('does not adopt Claude settings as a session store when the daemon names a separate transcript root', async () => {
+ vi.mocked(captureLaunchExecutable).mockResolvedValueOnce({ state: 'ready',
+ executable: { command: '/fixture/engine', identity: 'fixture', current: () => true },
+ environment: { HOME: '/fixture/home', PATH: '/fixture/bin', CLAUDE_PROJECTS_DIR: '/fixture/archive' },
+ })
+ const confirmHome = vi.fn()
+ const result = await inspectNativeLaunch('claude', {}, { confirmHome })
+ if (!result.ok) throw Error(result.detail)
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(true)
+ expect(engineHooks.claude.installIn).toHaveBeenCalledWith(19473, '/fixture/home/.claude', expect.any(Object))
+ expect(confirmHome).not.toHaveBeenCalled()
+})
+
+it('bounds actual probe concurrency and recovers after the children settle', async () => {
+ fixture.stalled = true
+ const running = Array.from({ length: 10 }, () => inspectNativeLaunch('opencode'))
+ await vi.waitFor(() => expect(fixture.pending).toHaveLength(8))
+ expect(fixture.calls).toHaveLength(8)
+ fixture.stalled = false
+ for (const settle of fixture.pending.splice(0)) settle()
+ const answers = await Promise.all(running)
+ expect(answers.filter(answer => answer.ok)).toHaveLength(8)
+ expect(answers.filter(answer => !answer.ok)).toHaveLength(2)
+ expect(await inspectNativeLaunch('opencode')).toMatchObject({ ok: true })
+})
+it('retries unknown permission answers and matches only complete flag tokens', async () => {
+ const prepared = await inspectNativeLaunch('opencode')
+ if (!prepared.ok) throw Error(prepared.detail)
+ fixture.failed = true
+ expect(await prepared.launch.permission({ bypassPermission: true })).toBe('unknown')
+ fixture.failed = false; fixture.help = '--prefix--auto --auto-update'
+ expect(await prepared.launch.permission({ bypassPermission: true })).toBe('unsupported')
+})
+
+it('does not restore a daemon location that the captured shell unset', async () => {
+ vi.stubEnv('OPENCODE_CONFIG_DIR', '/fixture/daemon-config')
+ vi.stubEnv('FIXTURE_NATIVE_CREDENTIAL', 'private-value')
+ const prepared = await inspectNativeLaunch('opencode', { bypassPermission: true })
+ if (!prepared.ok) throw Error(prepared.detail)
+ expect(fixture.environments).toHaveLength(2)
+ for (const environment of fixture.environments) {
+ expect(environment.OPENCODE_CONFIG_DIR).toBeUndefined()
+ expect(environment.FIXTURE_NATIVE_CREDENTIAL).toBe('private-value')
+ expect(environment.HOME).toBe('/fixture/home')
+ }
+})
+
+it('publishes locations and proofs together and revokes authority while replacement hooks are pending or fail', async () => {
+ const result = await inspectNativeLaunch('codex')
+ if (!result.ok) throw Error(result.detail)
+ expect(result.launch.ready?.()).toBe(false)
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(true)
+ expect(result.launch.ready?.()).toBe(true)
+ let finish!: (value: boolean) => void
+ vi.mocked(engineHooks.codex.installIn).mockImplementationOnce(() => new Promise(done => { finish = done }))
+ const replacing = result.launch.prepareHooks(19473, () => true, { CODEX_HOME: '/fixture/home-b' })
+ expect(result.launch.current()).toBe(false)
+ expect(result.launch.ready?.()).toBe(false)
+ expect(result.launch.environment.CODEX_HOME).toBe('/fixture/codex')
+ finish(false)
+ expect(await replacing).toBe(false)
+ expect(result.launch.current()).toBe(false)
+ expect(result.launch.environment.CODEX_HOME).toBe('/fixture/codex')
+ expect(await result.launch.prepareHooks(19473, () => true, { CODEX_HOME: '/fixture/home-b' })).toBe(true)
+ expect(result.launch.environment.CODEX_HOME).toBe('/fixture/home-b')
+ expect(result.launch.ready?.()).toBe(true)
+})
+it('rejects a permission reply from a prior preparation revision', async () => {
+ const result = await inspectNativeLaunch('opencode')
+ if (!result.ok) throw Error(result.detail)
+ fixture.stalled = true
+ const answer = result.launch.permission({ bypassPermission: true })
+ expect(fixture.pending).toHaveLength(1)
+ expect(await result.launch.prepareHooks(19473, () => true, { OPENCODE_CONFIG_DIR: '/fixture/new-config' })).toBe(true)
+ fixture.stalled = false
+ fixture.pending.shift()!()
+ expect(await answer).toBe('unknown')
+ expect(await result.launch.permission({ bypassPermission: true })).toBe('supported')
+})
+
+it.each([
+ ['claude', 'explicit'], ['claude', 'generated'], ['codex', 'explicit'], ['codex', 'generated'],
+] as const)('keeps a %s %s profile scoped to its session across repeated preparations', async (engine, kind) => {
+ const confirmHome = vi.fn()
+ const home = '/fixture/session-profile', variable = engine === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME'
+ const source = kind === 'explicit' ? engine === 'claude' ? { claudeHome: home } : { codexHome: home } : {}
+ const result = await inspectNativeLaunch(engine, source, { confirmHome })
+ if (!result.ok) throw Error(result.detail)
+ expect(await result.launch.prepareHooks(19473, () => true, kind === 'generated' ? { [variable]: home } : {})).toBe(true)
+ expect(result.launch.environment[variable]).toBe(home)
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(true)
+ expect(confirmHome).not.toHaveBeenCalled()
+})
diff --git a/cli/src/engines/nativeLaunch.ts b/cli/src/engines/nativeLaunch.ts
new file mode 100644
index 000000000..717f84a08
--- /dev/null
+++ b/cli/src/engines/nativeLaunch.ts
@@ -0,0 +1,163 @@
+/** Eager preparation shared by every way core starts a native engine. */
+import { execFile } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { isAbsolute, join } from 'node:path'
+import { permissionFlagToVerify, type PermissionLaunchChoice } from '../lib/engineLaunch.js'
+import type { EngineInstallRecipe } from '../lib/engineInstall.js'
+import { engineHooks } from './hooks.js'
+import * as hooks from './nativeHooks.js'
+import { captureLaunchExecutable, LAUNCH_LOCATION_VARIABLES } from './kit/launchExecutable.js'
+import type { HookPreparationProof } from './kit/nativeHookFiles.js'
+import { nativeHookLocations, nativeProcessEnvironment, type NativeHookOptions } from './kit/nativeLocations.js'
+import { parseMajor, type NativeExecutableSnapshot } from './kit/nativeVersion.js'
+import { OPENCODE_VERSION } from './opencode/contract.js'
+import { type AgentEngine, isTerminalEngine } from './types.js'
+
+export interface NativeLaunchSource extends PermissionLaunchChoice {
+ codexHome?: string | null
+ hermesHome?: string | null
+ claudeHome?: string | null
+}
+export interface NativeLaunch {
+ token?: string
+ executable?: NativeExecutableSnapshot
+ opencodeMajor: number | null
+ /** Set again after the pane's rc files, before the exact prepared executable. */
+ readonly environment: Readonly<Record<string, string>>
+ readonly clearEnvironment?: readonly string[]
+ readonly proofs: readonly HookPreparationProof[]
+ retain?(proof: HookPreparationProof): boolean
+ ready?(): boolean
+ current(): boolean
+ prepareHooks(port: number, current: () => boolean, environment?: Readonly<Record<string, string>>, clear?: readonly string[]): Promise<boolean>
+ permission(choice: PermissionLaunchChoice): Promise<'supported' | 'unsupported' | 'unknown'>
+}
+export type NativeLaunchResult =
+ | { ok: true; launch: NativeLaunch }
+ | { ok: false; error: 'NATIVE_LAUNCH_HELD'; unavailable: 'native'; detail: string; install?: EngineInstallRecipe; environment?: Record<string, string> }
+const waiting = (detail: string): Extract<NativeLaunchResult, { ok: false }> => ({ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail })
+const noNative: NativeLaunch = {
+ opencodeMajor: null, environment: {}, proofs: [], current: () => true,
+ prepareHooks: async () => true, permission: async () => 'supported',
+}
+
+let probes = 0
+/** 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> {
+ if (probes >= 8) return null
+ probes++
+ return new Promise(done => {
+ try {
+ const child = execFile(executable, [...args], {
+ env: nativeProcessEnvironment(environment), encoding: 'utf8', timeout: 5_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024,
+ }, (error, output) => { probes--; done(error ? null : output) })
+ child.stdin?.end()
+ } catch { probes--; done(null) }
+ })
+}
+
+/** 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 } = {},
+): Promise<NativeLaunchResult> {
+ if (isTerminalEngine(engine)) return { ok: true, launch: { ...noNative, environment: {}, proofs: [] } }
+ source = { ...source }
+ const captured = await captureLaunchExecutable(engine)
+ if (captured.state === 'held') return waiting(captured.detail)
+ if (captured.state === 'install') return { ...waiting(`Waiting for ${engine} to be installed before preparing its launch.`), install: captured.recipe, environment: captured.environment }
+ const { executable } = captured
+ const selected: Record<string, string> = Object.fromEntries(Object.entries(captured.environment).filter((entry): entry is [string, string] => entry[1] !== undefined))
+ if (source.codexHome) selected.CODEX_HOME = source.codexHome
+ if (source.claudeHome) selected.CLAUDE_CONFIG_DIR = source.claudeHome
+ if (source.hermesHome) selected.HERMES_HOME = source.hermesHome
+ // Empty location variables use their native default. Relative locations cannot
+ // be prepared independently of a changing pane cwd.
+ if (Object.entries(selected).some(([key, path]) => key !== 'PATH' && path && (!isAbsolute(path) || path.includes('\0') || path.length > 4096))) {
+ return waiting('Waiting for absolute native engine locations.')
+ }
+ try { nativeHookLocations(selected) } catch { return waiting('Waiting to confirm native engine locations.') }
+ const environment = Object.freeze(selected)
+ const initialHomes = nativeHookLocations(environment)
+ const implicitHome = engine === 'claude' && !source.claudeHome
+ && 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)
+ // 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.')
+ let proofs: readonly HookPreparationProof[] = [], selectedEnvironment = environment
+ const dependencies: HookPreparationProof[] = []
+ const dependenciesCurrent = () => dependencies.every(proof => proof.current())
+ 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'>()
+ const launch: NativeLaunch = {
+ token: randomUUID(), executable, opencodeMajor, current, ready: () => prepared && current(),
+ get environment() { return selectedEnvironment },
+ get proofs() { return [...dependencies, ...proofs] },
+ retain(proof) {
+ if (!current() || dependencies.length >= 16 || !proof.current()) return false
+ dependencies.push(proof); return true
+ },
+ get clearEnvironment() { return LAUNCH_LOCATION_VARIABLES.filter(key => !(key in selectedEnvironment)) },
+ async prepareHooks(port, owner, overrides = {}, clear = []) {
+ if (preparing || !executable.current() || !owner() || !dependenciesCurrent()) return false
+ preparing = true; valid = false; const attemptRevision = ++revision
+ permissions.clear()
+ try {
+ const chosen = { ...selectedEnvironment }
+ for (const key of clear) if (LAUNCH_LOCATION_VARIABLES.includes(key as typeof LAUNCH_LOCATION_VARIABLES[number])) delete chosen[key]
+ for (const key of LAUNCH_LOCATION_VARIABLES) if (overrides[key] !== undefined) chosen[key] = overrides[key]
+ if (Object.entries(chosen).some(([key, path]) => key !== 'PATH' && path && (!isAbsolute(path) || path.includes('\0') || path.length > 4096))) return false
+ const homes = nativeHookLocations(chosen)
+ const confirmed: HookPreparationProof[] = []
+ const options: NativeHookOptions = { environment: chosen,
+ current: () => preparing && revision === attemptRevision && executable.current() && owner() && dependenciesCurrent(),
+ confirmed: proof => confirmed.push(proof) }
+ const home = engine === 'codex' ? homes.CODEX_HOME : engine === 'claude' ? homes.CLAUDE_HOME : homes.HERMES_HOME
+ const installed = port === 0 ? true : engine === 'claude' || engine === 'codex' ? await engineHooks[engine].installIn(port, home, options)
+ : engine === 'hermes' ? await hooks.installHermesHooks(port, home, options)
+ : engine === 'opencode' ? await hooks.installOpencodePlugin(port, { ...executable, major: opencodeMajor! }, options)
+ : await installers[engine]?.(port, options) ?? true
+ if (!installed || !executable.current() || !owner() || [...dependencies, ...confirmed].some(proof => !proof.current())) return false
+ // A login shell can move the session store without an explicit profile.
+ // Codex's explicit/generated profiles belong to their registry row;
+ // adopting them globally would refresh a held package's hooks at boot
+ // before its Store dependencies are ready.
+ if ((engine === 'claude' || engine === 'codex') && home === implicitHome) deps.confirmHome?.(engine, home)
+ if (!executable.current() || !owner() || [...dependencies, ...confirmed].some(proof => !proof.current())) return false
+ // The command locations and the proofs become dispatch authority together.
+ // A failed or pending replacement can never expose B with A's proof set.
+ selectedEnvironment = Object.freeze(chosen); proofs = Object.freeze(confirmed)
+ valid = true; prepared = true
+ return true
+ } catch (error) {
+ console.warn(`[launch] native hook preparation held · ${error instanceof Error ? error.message : error}`)
+ return false
+ } finally { preparing = false }
+ },
+ async permission(choice) {
+ const flag = permissionFlagToVerify(engine, choice)
+ if (!flag) return 'supported'
+ if (!current()) return 'unknown'
+ const known = permissions.get(flag)
+ if (known) return known
+ const observedRevision = revision
+ const help = await read(executable.command, ['--help'], selectedEnvironment)
+ if (help === null || !current() || observedRevision !== revision) 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.')
+ return { ok: true, launch }
+}
+
+const installers: Partial<Record<AgentEngine, (port: number, options: NativeHookOptions) => Promise<boolean>>> = {
+ cursor: hooks.installCursorHooks, commandcode: hooks.installCommandCodeHooks, devin: hooks.installDevinHooks,
+ amp: hooks.installAmpPlugin, kilo: hooks.installKiloPlugin, grok: hooks.installGrokHooks, agy: hooks.installAgyHooks,
+ copilot: hooks.installCopilotHooks, pi: hooks.installPiExtension,
+}
diff --git a/cli/src/engines/nativeLaunchCompatibility.golden.spec.ts b/cli/src/engines/nativeLaunchCompatibility.golden.spec.ts
new file mode 100644
index 000000000..83c4513d3
--- /dev/null
+++ b/cli/src/engines/nativeLaunchCompatibility.golden.spec.ts
@@ -0,0 +1,119 @@
+/** Healthy launch behavior from main, before native preparation is shared by all entry points. */
+import { execFile } from 'node:child_process'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, beforeAll, expect, it, vi } from 'vitest'
+import { shellSingleQuote } from '../lib/shellQuote.js'
+
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/native-launch-compatibility.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_NATIVE_LAUNCH_GOLDEN === '1'
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+let root: string
+
+beforeAll(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'native-launch-golden-')))
+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })
+ vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date('2026-10-11T00:00:00Z'))
+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'HERMES_HOME', 'OPENCODE_DATA_DIR', 'OPENCODE_CONFIG_DIR', 'ZDOTDIR']) {
+ const directory = join(root, name.toLowerCase()); mkdirSync(directory); vi.stubEnv(name, directory)
+ }
+ for (const name of ['CLAUDE_PATH', 'CODEX_PATH', 'CURSOR_PATH', 'OPENCODE_PATH', 'PI_PATH', 'HERMES_PATH', 'COMMANDCODE_PATH', 'DEVIN_PATH', 'MUSE_PATH', 'AMP_PATH', 'KILO_PATH', 'GROK_PATH', 'AGY_PATH', 'COPILOT_PATH', 'HARNESS_GRID_BIN']) vi.stubEnv(name, '')
+ vi.stubEnv('TZ', 'UTC'); vi.stubEnv('SHELL', '/bin/sh'); vi.stubEnv('PATH', '/usr/bin:/bin')
+ vi.resetModules()
+})
+afterAll(() => {
+ Object.defineProperty(process, 'platform', platform)
+ vi.useRealTimers(); vi.unstubAllEnvs(); rmSync(root, { recursive: true, force: true })
+})
+const normalize = (value: unknown): unknown => JSON.parse(JSON.stringify(value).split(root).join('<root>')
+ .split(process.execPath).join('<node>').split(dirname(process.execPath)).join('<node-dir>'))
+
+it('preserves native arguments, first messages and healthy installer effects', async () => {
+ const { ENGINES } = await import('./types.js')
+ const { buildEngineCommandArgv, buildEngineLaunchArgv } = await import('../lib/engineLaunch.js')
+ const { engineBin } = await import('../lib/engineBin.js')
+ const { env } = await import('../config/env.js')
+ const { inspectNativeLaunch } = await import('./nativeLaunch.js')
+ const { createNativeInstallations, NATIVE_INSTALL_WORKER } = await import('./kit/nativeInstall.js')
+ const { launchScriptOf } = await import('../testing/launchScript.js')
+ const actual: Record<string, unknown> = {}
+ const commands = join(root, 'commands'); mkdirSync(commands)
+ vi.stubEnv('PATH', `${commands}:/usr/bin:/bin`)
+ for (const engine of ENGINES.filter(engine => engine !== 'terminal')) {
+ const command = engineBin(engine), executable = join(commands, command)
+ writeFileSync(executable, '#!/bin/sh\ncase "$1" in --version) printf "1.0.0\\n";; --help) printf -- "--auto --permission-mode --approve-for-me\\n";; esac\n', { mode: 0o700 })
+ const prepared = await inspectNativeLaunch(engine)
+ expect(prepared.ok).toBe(true)
+ if (!prepared.ok) throw Error(prepared.detail)
+ expect(prepared.launch.executable?.command).toBe(executable)
+ expect(await prepared.launch.prepareHooks(0, () => true)).toBe(true)
+ for (const [name, options] of Object.entries({
+ fresh: {}, resume: { resumeSessionId: 'fixture-conversation' }, fork: { forkSessionId: 'fixture-parent' },
+ permission: { permissionMode: 'auto' as const, bypassPermission: true, extraArgs: ['--model', 'fixture/model'] },
+ first: { firstPrompt: 'literal ; $(first message)' },
+ })) {
+ try {
+ const argv = buildEngineCommandArgv(engine, { ...options, native: prepared.launch })
+ expect(argv[0]).toBe(executable)
+ actual[`${engine} ${name}`] = [command, ...argv.slice(1)]
+ }
+ catch (error) { actual[`${engine} ${name}`] = { refused: (error as Error).name, detail: (error as Error).message } }
+ }
+ }
+ for (const kind of ['installed', 'vendor', 'fallback', 'npm'] as const) {
+ const directory = join(root, kind); mkdirSync(directory)
+ const trace = join(directory, 'trace'), binary = join(directory, 'engine'), source = join(directory, 'source')
+ writeFileSync(source, `#!/bin/sh\ncase "$1" in --version) printf '1.0.0\\n'; exit 0;; esac\nprintf 'engine\\n' >>${shellSingleQuote(trace)}\nprintf '%s\\n' "$@" >>${shellSingleQuote(trace)}\n`, { mode: 0o700 })
+ if (kind === 'installed') writeFileSync(binary, readFileSync(source), { mode: 0o700 })
+ const install = `printf 'install:%s\\n' "\${npm_config_prefix:-vendor}" >>${shellSingleQuote(trace)}; cp ${shellSingleQuote(source)} ${shellSingleQuote(binary)}`
+ const recipe = { source: 'private fixture',
+ command: kind === 'fallback' ? `printf 'primary\\n' >>${shellSingleQuote(trace)}` : install,
+ ...(kind === 'fallback' ? { fallback: install } : {}),
+ executable: { names: ['harness-fixture-missing'], absolutePaths: [binary], ...(kind === 'npm' ? { npmGlobal: true } : {}) },
+ }
+ // The only npm is a private prerequisite fixture. No package manager or network command runs.
+ const bin = join(directory, 'bin'); mkdirSync(bin)
+ writeFileSync(join(bin, 'npm'), '#!/bin/sh\nexit 1\n', { mode: 0o700 })
+ vi.stubEnv('PATH', `${bin}:/usr/bin:/bin`)
+ env.OPENCODE_PATH = binary
+ const environment = { HOME: process.env.HOME!, PATH: `${bin}:/usr/bin:/bin`, SHELL: '/bin/sh' }
+ let completed: Promise<void> | undefined
+ const installation = createNativeInstallations({ directory: join(directory, 'claims'), node: () => process.execPath,
+ dispatch: (node, file, hash) => {
+ completed = new Promise((done, failed) => {
+ execFile(node, ['-e', NATIVE_INSTALL_WORKER, file, hash], { env: { ...process.env, ...environment }, timeout: 10_000 },
+ error => error ? failed(error) : done())
+ })
+ },
+ })
+ await installation.ensure('opencode', recipe, environment, kind, () => true)
+ expect(completed).toBeDefined()
+ await completed
+ expect(await installation.ensure('opencode', recipe, environment, kind, () => true)).toEqual({ complete: true })
+ expect(existsSync(trace) ? readFileSync(trace, 'utf8') : '').not.toContain('engine\n')
+ const prepared = await inspectNativeLaunch('opencode')
+ expect(prepared.ok).toBe(true)
+ if (!prepared.ok) throw Error(prepared.detail)
+ expect(await prepared.launch.prepareHooks(0, () => true)).toBe(true)
+ const argv = buildEngineLaunchArgv('opencode', { native: prepared.launch, firstPrompt: 'literal ; $(first message)' }, '/bin/sh', process.execPath, '/fixture/grid', null)
+ const script = launchScriptOf(argv)
+ const result = await new Promise<{ code: number | string; stderr: string }>(done => {
+ execFile('/bin/sh', ['-c', script, ...argv.slice(argv.indexOf('harness-engine'))],
+ { env: { ...process.env, PATH: `${bin}:/usr/bin:/bin` }, timeout: 10_000 },
+ (error, _stdout, stderr) => done({ code: error?.code ?? 0, stderr }))
+ })
+ expect(result).toEqual({ code: 0, stderr: '' })
+ actual[`installation ${kind}`] = { code: result.code, trace: readFileSync(trace, 'utf8').split('\n').filter(Boolean), executable: existsSync(binary) }
+ }
+ if (RECORD) writeFileSync(GOLDEN, JSON.stringify(normalize(actual), null, 2) + '\n')
+ else expect(normalize(actual)).toEqual(JSON.parse(readFileSync(GOLDEN, 'utf8')))
+}, 60_000)
+
+it('contains no host paths or host executable', () => {
+ const text = readFileSync(GOLDEN, 'utf8')
+ expect(text).not.toContain(root)
+ expect(text).not.toContain(process.execPath)
+ expect(text).not.toMatch(/\/Users\/|\/home\/runner|native-launch-golden-/)
+})
diff --git a/cli/src/engines/nativeLaunchLocations.spec.ts b/cli/src/engines/nativeLaunchLocations.spec.ts
new file mode 100644
index 000000000..4c75af6c4
--- /dev/null
+++ b/cli/src/engines/nativeLaunchLocations.spec.ts
@@ -0,0 +1,95 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { AgentEngine } from './types.js'
+
+let root = '', home = '', bin = ''
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'native-launch-locations-'))
+ home = join(root, 'shell-home'); bin = join(root, 'bin')
+ mkdirSync(home); mkdirSync(bin)
+ for (const key of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR']) {
+ const value = key === 'HOME' ? home : join(root, key)
+ mkdirSync(value, { recursive: true }); vi.stubEnv(key, value)
+ }
+ // Both the binaries and every selected hook destination belong to this case.
+ vi.stubEnv('PATH', bin); vi.stubEnv('SHELL', '/bin/sh')
+ for (const key of ['XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'CLAUDE_CONFIG_DIR', 'CLAUDE_PROJECTS_DIR', 'CODEX_HOME',
+ 'GROK_HOME', 'AGY_HOME', 'AGY_CONFIG_DIR', 'COPILOT_HOME', 'CURSOR_HOME', 'CURSOR_CONFIG_DIR', 'CURSOR_DATA_DIR',
+ 'OPENCODE_PLUGIN_DIR', 'OPENCODE_CONFIG_DIR', 'KILO_PLUGIN_DIR', 'PI_HOME', 'PI_CODING_AGENT_DIR', 'PI_CODING_AGENT_SESSION_DIR',
+ 'HERMES_HOME', 'COMMANDCODE_HOME', 'DEVIN_HOME', 'DEVIN_CONFIG_PATH', 'AMP_PLUGIN_DIR', 'ZDOTDIR']) vi.stubEnv(key, '')
+ for (const engine of ['CLAUDE', 'CODEX', 'CURSOR', 'GROK', 'AGY', 'COPILOT', 'OPENCODE', 'KILO', 'PI', 'AMP', 'HERMES', 'COMMANDCODE', 'DEVIN']) vi.stubEnv(`${engine}_PATH`, '')
+ for (const name of ['claude', 'codex', 'cursor-agent', 'grok', 'agy', 'copilot', 'opencode', 'kilo', 'pi', 'amp', 'hermes', 'cmd', 'devin']) {
+ writeFileSync(join(bin, name), '#!/bin/sh\nprintf "2.0.0\\n"\n', { mode: 0o700 })
+ }
+ vi.resetModules()
+})
+afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); rmSync(root, { recursive: true, force: true }) })
+
+it.each([
+ ['claude', '.claude/settings.json'], ['codex', '.codex/hooks.json'], ['cursor', '.cursor/hooks.json'],
+ ['grok', '.grok/hooks/harness.json'], ['agy', '.gemini/config/hooks.json'], ['copilot', '.copilot/hooks/harness.json'],
+ ['opencode', '.config/opencode/plugins/launcher-register/tui.js'], ['kilo', '.config/kilo/plugin/launcher-register.js'],
+ ['pi', '.pi/agent/extensions/launcher-register.ts'], ['amp', '.config/amp/plugins/launcher-register.ts'],
+ ['hermes', '.hermes/config.yaml'], ['commandcode', '.commandcode/settings.json'], ['devin', '.config/devin/config.json'],
+] as [AgentEngine, string][])('prepares %s at the captured home even after daemon environment drift', async (engine, relative) => {
+ const { inspectNativeLaunch } = await import('./nativeLaunch.js')
+ const result = await inspectNativeLaunch(engine)
+ expect(result.ok).toBe(true)
+ if (!result.ok) throw Error(result.detail)
+ const drift = join(root, 'changed-home'); mkdirSync(drift)
+ vi.stubEnv('HOME', drift); vi.stubEnv('XDG_CONFIG_HOME', join(drift, 'config'))
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(true)
+ expect(existsSync(join(home, relative))).toBe(true)
+ expect(existsSync(join(drift, relative))).toBe(false)
+ expect(result.launch.environment.HOME).toBe(home)
+ expect(result.launch.environment.PATH).toBe(bin)
+ expect(result.launch.current()).toBe(true)
+})
+
+it('prepares redirected model homes and bakes that exact home into notifications', async () => {
+ const { inspectNativeLaunch } = await import('./nativeLaunch.js')
+ for (const [engine, variable, relative] of [['grok', 'GROK_HOME', 'hooks/harness.json'], ['pi', 'PI_CODING_AGENT_DIR', 'extensions/launcher-register.ts']] as const) {
+ const result = await inspectNativeLaunch(engine)
+ if (!result.ok) throw Error(result.detail)
+ const selected = join(root, `model-${engine}`)
+ expect(await result.launch.prepareHooks(19473, () => true, { [variable]: selected })).toBe(true)
+ expect(existsSync(join(selected, relative))).toBe(true)
+ expect(result.launch.environment[variable]).toBe(selected)
+ if (engine === 'grok') expect(readFileSync(join(selected, relative), 'utf8')).toContain(`--grok-home '${selected}'`)
+ }
+})
+
+it('keeps overlapping OpenCode preparation isolated by selected config root', async () => {
+ const { inspectNativeLaunch } = await import('./nativeLaunch.js')
+ const a = await inspectNativeLaunch('opencode'), b = await inspectNativeLaunch('opencode')
+ if (!a.ok || !b.ok) throw Error('Private executable was not prepared')
+ const roots = [join(root, 'opencode-a'), join(root, 'opencode-b')]
+ expect(await Promise.all([a.launch.prepareHooks(19473, () => true, { OPENCODE_CONFIG_DIR: roots[0] }),
+ b.launch.prepareHooks(19473, () => true, { OPENCODE_CONFIG_DIR: roots[1] })])).toEqual([true, true])
+ for (const dir of roots) expect(existsSync(join(dir, 'plugins/launcher-register/tui.js'))).toBe(true)
+ expect(a.launch.current()).toBe(true); expect(b.launch.current()).toBe(true)
+})
+
+it('pins overridden locations even when the owner disabled hook installation', async () => {
+ const { inspectNativeLaunch } = await import('./nativeLaunch.js')
+ const result = await inspectNativeLaunch('grok')
+ if (!result.ok) throw Error(result.detail)
+ const selected = join(root, 'disabled-grok')
+ expect(await result.launch.prepareHooks(0, () => true, { GROK_HOME: selected })).toBe(true)
+ expect(result.launch.environment.GROK_HOME).toBe(selected)
+ expect(existsSync(selected)).toBe(false)
+})
+
+it('keeps Claude settings separate from a daemon transcript-root override', async () => {
+ const archive = join(root, 'archive', 'projects')
+ vi.stubEnv('CLAUDE_PROJECTS_DIR', archive)
+ const { inspectNativeLaunch } = await import('./nativeLaunch.js')
+ const result = await inspectNativeLaunch('claude')
+ if (!result.ok) throw Error(result.detail)
+ expect(await result.launch.prepareHooks(19473, () => true)).toBe(true)
+ expect(existsSync(join(home, '.claude/settings.json'))).toBe(true)
+ expect(existsSync(join(root, 'archive/settings.json'))).toBe(false)
+ expect(readFileSync(join(home, '.claude/settings.json'), 'utf8')).toContain(`--claude-projects-dir '${archive}'`)
+})
diff --git a/cli/src/engines/prepareNativeLaunch.spec.ts b/cli/src/engines/prepareNativeLaunch.spec.ts
new file mode 100644
index 000000000..53b722dbd
--- /dev/null
+++ b/cli/src/engines/prepareNativeLaunch.spec.ts
@@ -0,0 +1,54 @@
+import { expect, it, vi } from 'vitest'
+import { createNativeLaunchPreparer } from './prepareNativeLaunch.js'
+import type { NativeLaunch, NativeLaunchResult } from './nativeLaunch.js'
+
+const absent: NativeLaunchResult = { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Not installed',
+ install: { command: 'fixture-installer', source: 'fixture', executable: { names: ['fixture'] } }, environment: { HOME: '/fixture/home', PATH: '/fixture/bin' } }
+const ready: NativeLaunchResult = { ok: true, launch: { current: () => true } as NativeLaunch }
+it('installs under the saved request and requires a fresh post-install snapshot', async () => {
+ const ensure = vi.fn().mockResolvedValueOnce({ complete: false, detail: 'Installation in progress' }).mockResolvedValue({ complete: true })
+ const inspect = vi.fn().mockResolvedValueOnce(absent).mockResolvedValueOnce(absent).mockResolvedValue(ready)
+ const prepare = createNativeLaunchPreparer({ installations: { ensure, status: vi.fn(async () => null) }, inspect })
+ const authority = { id: 'fixture-request', current: () => true }
+ expect(await prepare('opencode', {}, authority)).toMatchObject({ ok: false, detail: 'Installation in progress' })
+ expect(await prepare('opencode', {}, authority)).toBe(ready)
+ expect(ensure.mock.calls.map(args => args[3])).toEqual(['fixture-request', 'fixture-request'])
+ expect(inspect).toHaveBeenCalledTimes(3)
+})
+it('does not install on uncertain executable evidence and revokes every asynchronous continuation', async () => {
+ const ensure = vi.fn().mockResolvedValue({ complete: true })
+ const inspect = vi.fn().mockResolvedValue({ ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Unreadable executable' })
+ const prepare = createNativeLaunchPreparer({ installations: { ensure, status: vi.fn(async () => null) }, inspect })
+ let current = true
+ const authority = { id: 'fixture-request', current: () => current }
+ expect(await prepare('codex', {}, authority)).toMatchObject({ detail: 'Unreadable executable' })
+ expect(ensure).not.toHaveBeenCalled()
+ current = false
+ expect(await prepare('codex', {}, authority)).toMatchObject({ ok: false })
+ expect(inspect).toHaveBeenCalledOnce()
+ current = true
+ inspect.mockImplementationOnce(async () => { current = false; return absent })
+ expect(await prepare('codex', {}, authority)).toMatchObject({ ok: false })
+ expect(ensure).not.toHaveBeenCalled()
+ current = true
+ inspect.mockResolvedValue(absent)
+ ensure.mockImplementationOnce(async () => { current = false; return { complete: true } })
+ expect(await prepare('codex', {}, authority)).toMatchObject({ ok: false })
+ expect(inspect).toHaveBeenCalledTimes(3)
+ current = true
+ inspect.mockResolvedValueOnce(absent).mockImplementationOnce(async () => { current = false; return ready })
+ expect(await prepare('codex', {}, authority)).toMatchObject({ ok: false })
+})
+
+it('does not mistake a newly visible executable for its still-running installer’s completion', async () => {
+ const ensure = vi.fn(async () => ({ complete: false as const, detail: 'Installing' }))
+ const status = vi.fn().mockResolvedValueOnce({ complete: false, detail: 'Installer still unconfirmed' }).mockResolvedValue({ complete: true })
+ const inspect = vi.fn().mockResolvedValueOnce(absent).mockResolvedValue(ready)
+ const prepare = createNativeLaunchPreparer({ installations: { ensure, status }, inspect })
+ const authority = { id: 'fixture-original-request', current: () => true }
+ expect(await prepare('codex', {}, authority)).toMatchObject({ ok: false, detail: 'Installing' })
+ expect(await prepare('codex', {}, authority)).toMatchObject({ ok: false, detail: 'Installer still unconfirmed' })
+ expect(await prepare('codex', {}, authority)).toBe(ready)
+ expect(ensure).toHaveBeenCalledOnce()
+ expect(status).toHaveBeenCalledWith('codex', authority.id, authority.current)
+})
diff --git a/cli/src/engines/prepareNativeLaunch.ts b/cli/src/engines/prepareNativeLaunch.ts
new file mode 100644
index 000000000..3d2b7a8ed
--- /dev/null
+++ b/cli/src/engines/prepareNativeLaunch.ts
@@ -0,0 +1,32 @@
+import type { CreationAuthority } from '../lib/agentCreationReceipt.js'
+import type { createNativeInstallations } from './kit/nativeInstall.js'
+import { inspectNativeLaunch, type NativeLaunchResult, type NativeLaunchSource } from './nativeLaunch.js'
+import type { AgentEngine } from './types.js'
+
+/** Installation is its own durable effect. It never contains the agent argv or
+ * first prompt, and completing it still requires fresh executable evidence. */
+export function createNativeLaunchPreparer({ installations, inspect = inspectNativeLaunch }: {
+ installations: Pick<ReturnType<typeof createNativeInstallations>, 'ensure' | 'status'>
+ inspect?: typeof inspectNativeLaunch
+}) {
+ 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 })
+ 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) {
+ // A helper can create the executable before finishing its other writes.
+ // Consult durable history on every ready path, including after a core crash.
+ 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
+ }
+ if (!found.install || !found.environment) return found
+ const installed = await installations.ensure(engine, found.install, found.environment, authority.id, authority.current)
+ if (!installed.complete) return held(installed.detail)
+ 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/__fixtures__/grid-config-compatibility.golden.json b/cli/src/lib/__fixtures__/grid-config-compatibility.golden.json
new file mode 100644
index 000000000..2c4e4aa94
--- /dev/null
+++ b/cli/src/lib/__fixtures__/grid-config-compatibility.golden.json
@@ -0,0 +1,34 @@
+{
+ "pi-0": {
+ "files": {
+ "models.json": "{\"providers\":{\"fixture\":{\"apiKey\":\"GRID_API_KEY\"}}}\n",
+ "settings.json": "{\"skills\":[\"/fixture/skills\"]}\n"
+ },
+ "links": {},
+ "conversation": "{\"fixture\":\"retained conversation\"}\n"
+ },
+ "opencode-1": {
+ "files": {
+ "opencode.json": "{\"provider\":{\"fixture\":{\"npm\":\"@ai-sdk/openai-compatible\"}}}\n"
+ },
+ "links": {},
+ "conversation": "{\"fixture\":\"retained conversation\"}\n"
+ },
+ "grok-2": {
+ "files": {
+ "settings.json": "{\"baseUrl\":\"https://fixture.invalid/v1\"}\n"
+ },
+ "links": {
+ "sessions": "<root>/native-sessions"
+ },
+ "conversation": "{\"fixture\":\"retained conversation\"}\n"
+ },
+ "pi-3": {
+ "files": {
+ "models.json": "{\"providers\":{\"other\":{\"apiKey\":\"GRID_API_KEY\"}}}\n",
+ "settings.json": "{\"skills\":[\"/fixture/skills\"]}\n"
+ },
+ "links": {},
+ "conversation": "{\"fixture\":\"retained conversation\"}\n"
+ }
+}
diff --git a/cli/src/lib/agentCreationReceipt.spec.ts b/cli/src/lib/agentCreationReceipt.spec.ts
index aab1d5105..cabac0173 100644
--- a/cli/src/lib/agentCreationReceipt.spec.ts
+++ b/cli/src/lib/agentCreationReceipt.spec.ts
@@ -133,6 +133,53 @@ describe('recoverable undispatched creation intents', () => {
const held = { service: 'models', detail: 'Waiting for the selected model.' }
const created = { state: 'created' as const, agentId: 'fixture-agent' }
+ it('persists the current hold reason independently of dispatch authority', async () => {
+ const { directory, receipts } = fixture()
+ const nativeHold = { service: 'native', detail: 'Waiting for the engine installation.' }
+ await receipts.runIntent(id, fingerprint, request, held, async (_request, authority) => {
+ expect(authority.id).toBe(id)
+ expect(authority.current()).toBe(true)
+ authority.hold(nativeHold)
+ return null
+ })
+ expect(new AgentCreationReceipts(directory).status(id)).toEqual({ state: 'pending', held: nativeHold })
+ writeFileSync(join(directory, `${id}.hold`), 'corrupt status')
+ expect(receipts.status(id)).toEqual({ state: 'pending', held })
+ let current!: () => boolean
+ expect(await receipts.runIntent(id, fingerprint, request, held, async (_request, authority) => {
+ current = authority.current
+ return async () => { expect(current()).toBe(true); return created }
+ })).toEqual(created)
+ expect(current()).toBe(false)
+ })
+
+ it('revokes preparation authority immediately when cancellation wins', async () => {
+ const { directory, receipts } = fixture()
+ await receipts.runIntent(id, fingerprint, request, held, async (_request, authority) => {
+ expect(authority.current()).toBe(true)
+ new AgentCreationReceipts(directory).cancelIntent(id)
+ expect(authority.current()).toBe(false)
+ authority.hold({ service: 'native', detail: 'This stale status must not be published.' })
+ expect(fs.existsSync(join(directory, `${id}.hold`))).toBe(false)
+ return async () => { throw Error('Must never dispatch') }
+ })
+ expect(receipts.status(id)).toEqual({ state: 'cancelled' })
+ })
+
+ it.each(['matching', 'conflicting', 'corrupt'])('revokes dispatch authority when a %s result appears during an effect', async kind => {
+ const { directory, receipts } = fixture()
+ let wasCurrent = true
+ await expect(receipts.runIntent(id, fingerprint, request, held, async (_request, authority) => async () => {
+ expect(authority.current()).toBe(true)
+ const claim = JSON.parse(readFileSync(join(directory, `${id}.json.claim`), 'utf8'))
+ const result = { fingerprint, token: kind === 'matching' ? claim.token : 'different-token', outcome: created }
+ writeFileSync(join(directory, `${id}.json.result`), kind === 'corrupt' ? '{' : JSON.stringify(result), { mode: 0o600 })
+ wasCurrent = authority.current()
+ return { state: 'unconfirmed' }
+ })).rejects.toThrow('CREATION_STORAGE_FAILED')
+ expect(wasCurrent).toBe(false)
+ })
+
it('persists a held request, resumes it in another core and dispatches once across two cores', async () => {
const { directory, receipts } = fixture()
const offline = vi.fn(async () => null)
diff --git a/cli/src/lib/agentCreationReceipt.ts b/cli/src/lib/agentCreationReceipt.ts
index 9fb0ad9c6..496661483 100644
--- a/cli/src/lib/agentCreationReceipt.ts
+++ b/cli/src/lib/agentCreationReceipt.ts
@@ -15,6 +15,13 @@ export type AgentCreationStatus = AgentCreationOutcome
export interface CreationHold { service: string; detail: string }
export interface PendingCreationIntent { id: string; fingerprint: string; request: Record<string, unknown>; held: CreationHold }
+export interface CreationAuthority {
+ readonly id: string
+ /** The original durable intent still owns preparation, or this callback's exact dispatch claim. */
+ current(): boolean
+ /** Status only; a hold is never permission to repeat an effect. */
+ hold(reason: CreationHold): void
+}
/** An undispatched request can be recovered. A claimed request cannot: even a
* dead owner may have left a live child, or changed a project before it died. */
@@ -140,11 +147,11 @@ export class AgentCreationReceipts {
}
/** Persist the complete private request before looking up its dependencies.
- * `prepare` may repeat service-owned credential refreshes, but MUST NOT prepare
- * projects, write launch configuration, signal or dispatch a process. It hands
- * back the effect callback only when its dependencies are ready. */
+ * `prepare` may repeat service-owned credential refreshes and independently
+ * journalled preparation. It MUST NOT signal or dispatch the agent process.
+ * It hands back that effect only when all dependencies are ready. */
runIntent(id: string, fingerprint: string, request: Record<string, unknown>, held: CreationHold,
- prepare: (request: Record<string, unknown>) => Promise<(() => Promise<AgentCreationOutcome>) | null>,
+ prepare: (request: Record<string, unknown>, authority: CreationAuthority) => Promise<(() => Promise<AgentCreationOutcome>) | null>,
): Promise<AgentCreationStatus> {
const running = this.inFlight.get(id)
if (running) {
@@ -175,9 +182,33 @@ export class AgentCreationReceipts {
}
return current
}
+ let dispatchToken: string | undefined
+ let alive = true
+ const authority: CreationAuthority = {
+ id,
+ current: () => {
+ if (!alive) return false
+ try {
+ if ('cancelled' in currentReceipt()) return false
+ const claim = this.claim(id)
+ if (!claim) return !dispatchToken && this.intentStatus(id, saved, false).state === 'pending'
+ const status = this.intentStatus(id, saved, false)
+ return !!dispatchToken && status.state === 'unconfirmed' && !this.intentResults.has(id)
+ && !this.readIntentPart(this.intentFile(id, 'result'))
+ && claim.kind === 'dispatch' && claim.fingerprint === fingerprint && claim.token === dispatchToken
+ } catch { return false }
+ },
+ hold: reason => {
+ if (!authority.current() || dispatchToken) return
+ if (!reason.service || reason.service.length > 128 || !reason.detail || reason.detail.length > 2000) return
+ // This replaceable sidecar is presentation only. The immutable intent,
+ // exclusive claim and exact result remain the entire dispatch authority.
+ this.writeHold(id, { checksum: saved.checksum, held: { ...reason } })
+ },
+ }
const result = Promise.resolve().then(async (): Promise<AgentCreationStatus> => {
let effect: (() => Promise<AgentCreationOutcome>) | null
- try { effect = await prepare(saved.request) }
+ try { effect = await prepare(saved.request, authority) }
catch { effect = null }
const current = this.intentStatus(id, currentReceipt(), false)
if (!effect || current.state !== 'pending') return current
@@ -185,6 +216,7 @@ export class AgentCreationReceipts {
// Exactly the successful publisher executes. In particular, seeing our
// own claim after a failed directory fsync never grants a second attempt.
if (!this.publish(this.intentFile(id, 'claim'), claim, true)) return this.intentStatus(id, saved, false)
+ dispatchToken = claim.token
// A directory or primary intent replaced during service preparation must
// not inherit this callback's authority, even if a later cancel created a
// fresh tombstone at the same pathname. The open descriptor pins identity.
@@ -203,7 +235,7 @@ export class AgentCreationReceipts {
return this.intentStatus(id, currentReceipt(), false)
}
return outcome
- }).finally(() => { directory.close(); clearTimeout(replyTimer); this.inFlight.delete(id) })
+ }).finally(() => { alive = false; directory.close(); clearTimeout(replyTimer); this.inFlight.delete(id) })
// The client gets its held receipt promptly while the SAME preparation
// continues. A slow successful service answer can still win dispatch;
// reconnects must not start several preparations for that one request.
@@ -295,7 +327,7 @@ export class AgentCreationReceipts {
}
if (!claim) {
if (result) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')
- return { state: 'pending', held: receipt.held }
+ return { state: 'pending', held: this.readHold(id, receipt) }
}
if (claim.fingerprint !== receipt.fingerprint) throw new AgentCreationReceiptError('CREATION_STORAGE_FAILED')
if (claim.kind === 'cancel') {
@@ -335,6 +367,28 @@ export class AgentCreationReceipts {
finally { if (opened) rmSync(temporary, { force: true }) }
}
+ private readHold(id: string, receipt: Extract<IntentReceipt, { checksum: string }>): CreationHold {
+ try {
+ const value = JSON.parse(readPrivateStateFile(join(this.directory, `${id}.hold`), 16_384))
+ if (value.checksum === receipt.checksum && typeof value.held?.service === 'string' && value.held.service.length <= 128
+ && typeof value.held.detail === 'string' && value.held.detail.length <= 2000) return value.held
+ } catch { /* Missing or damaged status cannot grant or revoke dispatch. */ }
+ return receipt.held
+ }
+
+ private writeHold(id: string, value: { checksum: string; held: CreationHold }): void {
+ const target = join(this.directory, `${id}.hold`), temporary = `${target}.${randomUUID()}.tmp`
+ let fd: number | undefined
+ try {
+ secureStateDirectory(this.directory, false)
+ fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ writeFileSync(fd, JSON.stringify(value)); fsyncSync(fd)
+ renameSync(temporary, target); this.syncDirectory()
+ } finally {
+ if (fd !== undefined) { closeSync(fd); rmSync(temporary, { force: true }) }
+ }
+ }
+
private syncDirectory(path = this.directory, ancestor = false): void {
const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | (ancestor ? 0 : constants.O_NOFOLLOW))
try { fsyncSync(fd) } finally { closeSync(fd) }
diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.ts
index 582e9d9ba..7cfa597a7 100644
--- a/cli/src/lib/createAgentPane.ts
+++ b/cli/src/lib/createAgentPane.ts
@@ -26,6 +26,7 @@ const DEFAULT_MAX_ATTEMPTS = 3
export interface CreateAgentPaneDeps {
tmuxBackend: Pick<TerminalBackend<TmuxRuntimeRef>, 'create' | 'kill'>
registry: { openPendingAgent: (input: {
+ nativeToken?: string
engine: AgentEngine
runtimes: TmuxRuntimeRef[]
primaryRuntimeKey?: string
@@ -44,6 +45,7 @@ export interface CreateAgentPaneDeps {
forkedFrom?: ForkOrigin | null
externalResume?: ExternalResumeIntent
}) => RegisteredSession | null }
+ nativeToken?: string
engine: AgentEngine
cwd?: string | null
bypassPermission?: boolean
@@ -108,6 +110,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<
return { ok: false, error: missing ? 'TMUX_UNAVAILABLE' : 'SPAWN_FAILED', detail: spawned.reason }
}
const pending = deps.registry.openPendingAgent({
+ ...(deps.nativeToken ? { nativeToken: deps.nativeToken } : {}),
engine: deps.engine,
runtimes: [spawned.runtime],
primaryRuntimeKey: terminalRouteKey(spawned.runtime),
diff --git a/cli/src/lib/engineHomes.ts b/cli/src/lib/engineHomes.ts
index 6793c2198..81a8d5002 100644
--- a/cli/src/lib/engineHomes.ts
+++ b/cli/src/lib/engineHomes.ts
@@ -360,7 +360,7 @@ export function launchClaudeConfigDir(environment: NodeJS.ProcessEnv = launchEnv
/** The home an engine's launch contract declares (engines/facets/launch.ts `LaunchHome`), for a launch made now. */
export function launchHomeOf(home: LaunchHome, profile: string | null | undefined, environment: NodeJS.ProcessEnv = launchEnvironment()): string {
- return 'setting' in home ? launchHome(home.setting, profile, environment) : movedHome(environment[home.variable]) || homedir()
+ return 'setting' in home ? launchHome(home.setting, profile, environment) : movedHome(environment[home.variable]) || movedHome(environment.HOME) || homedir()
}
/** The environment that runs an agent on its own profile `home`, for an engine whose sessions follow one (its
diff --git a/cli/src/lib/engineInstall.ts b/cli/src/lib/engineInstall.ts
index 577225975..baa31314d 100644
--- a/cli/src/lib/engineInstall.ts
+++ b/cli/src/lib/engineInstall.ts
@@ -143,12 +143,12 @@ export function npmEnginePrefix(): string {
}
/** The same candidates are used by launch, availability checks, and process discovery. */
-export function engineInstallPaths(recipe: EngineInstallRecipe): string[] {
+export function engineInstallPaths(recipe: EngineInstallRecipe, home = homedir()): string[] {
return [...new Set([
- ...(recipe.executable.homeRelativePaths ?? []).map((path) => join(homedir(), path)),
+ ...(recipe.executable.homeRelativePaths ?? []).map((path) => join(home, path)),
...(recipe.executable.absolutePaths ?? []),
...(recipe.executable.npmGlobal
- ? recipe.executable.names.map((name) => join(npmEnginePrefix(), 'bin', name))
+ ? recipe.executable.names.map((name) => join(home, '.local', 'bin', name))
: []),
])]
}
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 7a511687e..46a1bc4e3 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -1,3 +1,7 @@
+import { LAUNCH_LOCATION_VARIABLES } from '../engines/kit/nativeLocations.js'
+import type { NativeLaunch } from '../engines/nativeLaunch.js'
+import { nativeLaunchGuard } from '../engines/kit/nativeLaunchGuard.js'
+import { nativePaneHold, NATIVE_LAUNCH_MARKER } from './nativePaneHold.js'
import { execFile } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
@@ -19,6 +23,7 @@ import { managedNodePath } from './nodeRuntime.js'
import { RAISE_OPEN_FILES_SH } from './openFiles.js'
import { ENGINE_EXIT_PANE_OPTION } from './engineExitOption.js'
import { shellSingleQuote } from './shellQuote.js'
+import { harnessPaneOwner } from './harnessSessionLabel.js'
export { shellSingleQuote }
@@ -190,6 +195,8 @@ export function namedAgentArgs(engine: AgentEngine, agent: string, opencodeMajor
}
export interface LaunchCommandOptions {
+ /** One executable and its prepared settings, retained through every launch fact. */
+ native?: NativeLaunch
bypassPermission?: boolean
/** A mode from [PERMISSION_MODES]; when the engine has it, it decides the flags and
* `bypassPermission` is ignored. */
@@ -339,7 +346,7 @@ export function supportsNativeFork(engine: AgentEngine): boolean {
/** The executable argv, before the interactive-shell wrapper is applied. */
export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandOptions = {}): string[] {
- const argv = [engineBin(engine)]
+ const argv = [opts.native?.executable?.command ?? engineBin(engine)]
// A fork is a resume that leaves the source alone; the two are exclusive, and the fork wins.
const fork = opts.forkSessionId ? LAUNCH_FORK_FLAG[engine] : undefined
const resumeFlag = fork ? fork.lead : opts.resumeSessionId ? LAUNCH_RESUME_FLAG[engine] : undefined
@@ -421,7 +428,7 @@ export function interactiveEngineShell(shell: string | undefined = undefined): I
* update answer before the engine exists, while an agent switch is still showing the old pane.
* DISABLE_UPDATE_PROMPT would auto-update instead; DISABLE_AUTO_UPDATE skips that work entirely.
* Keep ordinary terminal launches unchanged, and keep loading rc files for PATH/version managers. */
-function engineShellArgv(shell: InteractiveEngineShell, args: readonly string[]): string[] {
+export function engineShellArgv(shell: InteractiveEngineShell, args: readonly string[]): string[] {
if (!isPosixShell(shell.path)) return throughPosixShell(shell, args)
const prefix = basename(shell.path).toLowerCase() === 'zsh'
? ['/usr/bin/env', 'DISABLE_AUTO_UPDATE=true', ...zshNewUserGuard()]
@@ -552,7 +559,7 @@ export function buildEngineLaunchArgv(
const command = buildEngineCommandArgv(engine, opts)
// An engine whose declared startup runs in the script gets one even where the daemon has no login shell.
const interactive = interactiveEngineShell(shell)
- ?? (startupNeedsScript(launchContract(engine)) ? { path: posixRunner(), args: ['-c'], label: 'shell' } : null)
+ ?? (opts.native || startupNeedsScript(launchContract(engine)) ? { path: posixRunner(), args: ['-c'], label: 'shell' } : null)
if (!interactive) return command
const enginePrelude = engineFallbackPrelude(engine, interactive.path, tmuxBinary)
// The clear comes FIRST, before the install as well as before the engine. An installer is a child
@@ -561,7 +568,8 @@ export function buildEngineLaunchArgv(
// of this launch is that the agent's environment is the one the user asked for.
// Then the grid's PATH entry at the FRONT (its dir holds only `grid`), and — for a DSH agent — Harness's
// Node at the END, only when the shell found none. The two never meet: one prepends, one appends.
- const prelude = enginePrelude + clearEnvPrelude(opts.clearEnv) + gridPanePrelude(gridBinary) + noDevtoolsPrelude() + (opts.harnessNode ? harnessNodePrelude(runtimeNode) : '')
+ const nativeEnv = Object.entries(opts.native?.environment ?? {}).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}\n`).join('')
+ const prelude = enginePrelude + clearEnvPrelude(opts.clearEnv) + clearEnvPrelude(opts.native?.clearEnvironment) + nativeEnv + gridPanePrelude(gridBinary) + noDevtoolsPrelude() + (opts.harnessNode ? harnessNodePrelude(runtimeNode) : '')
// rc files (notably nvm) call getcwd() before running this command. Start the shell in a safe
// directory and enter the selected workspace only after those files have loaded: an IDE can replace
// a workspace inode between the desktop picker resolving it and tmux spawning the pane.
@@ -571,19 +579,28 @@ export function buildEngineLaunchArgv(
+ 'shift\n'
: ''
// The engine is found (or installed first), then run at the script's top level (`engineRunScript`).
- const engineFound = opts.installIfMissing
+ const engineFound = opts.native ? 'harness_engine_bin=$1\n' : opts.installIfMissing
? installIfMissingScript(opts.installIfMissing, runtimeNode, { engine, messageWaiting: Boolean(opts.firstPrompt) })
: opts.installFirst
? installFirstScript(opts.installFirst)
: 'harness_engine_bin=$1\n'
- const body = `${JOB_CONTROL}${SIGNAL_GUARD}${engineFound}shift\n${engineRunScript(engine, tmuxBinary)}`
+ const heldCommand = `/bin/sh -c ${shellSingleQuote('trap \'\' INT QUIT TSTP; printf \'%s\\n\' \"$1\"; while :; do sleep 3600; done')} harness-held ${shellSingleQuote('Waiting for native launch preparation to be confirmed.')} ${shellSingleQuote(opts.native?.token ?? '')}`
+ // tmux retains pane_start_command across exec. Transition this pane to the
+ // inert command so core can recognize its exact token after a crash, using the
+ // same server-side predicate as every other held launch. No engine has run.
+ const waiting = nativePaneHold(opts.native?.token ?? '', tmuxBinary, heldCommand, runtimeNode, harnessPaneOwner(env.ADAPTER_DATA_DIR))
+ const guard = opts.native ? nativeLaunchGuard(opts.native, runtimeNode, waiting) : ''
+ const body = `${JOB_CONTROL}${SIGNAL_GUARD}${engineFound}shift\n${guard}${engineRunScript(engine, tmuxBinary)}`
// The open-files raise goes ahead of everything, the installer included: a pane inherits the tmux
// SERVER's soft limit, which is launchd's 256 whenever the desktop app started the daemon that
// started the server, and an engine (Claude Code refuses outright) or an npm install under 256 is
// the failure the person then reads in the pane. See openFiles.ts.
const wait = opts.waitForPid ? waitForPidScript(opts.waitForPid) : ''
const script = RAISE_OPEN_FILES_SH + prelude + cwdPrelude + wait + body
- return engineShellArgv(interactive, [isPosixShell(interactive.path) ? sourcedOnce(script) : script, 'harness-engine', ...(opts.cwd ? [opts.cwd] : []), ...command])
+ const argv = engineShellArgv(interactive, [isPosixShell(interactive.path) ? sourcedOnce(script) : script, 'harness-engine', ...(opts.cwd ? [opts.cwd] : []), ...command])
+ // Keep the nonce outside the one-time file, including non-POSIX and inline
+ // launches. It is tmux's original launch identity, never a post-rc environment fact.
+ return opts.native ? ['/usr/bin/env', `${NATIVE_LAUNCH_MARKER}=${opts.native.token}`, ...argv] : argv
}
/**
@@ -1094,17 +1111,18 @@ const INSTALL_PROGRESS_JS = [
'process.stdin.on("end",()=>{clearInterval(tick);fs.closeSync(out);});',
].join('')
-function installIfMissingScript(recipe: EngineInstallRecipe, runtimeNode: string, friendly?: FriendlyInstall): string {
+function installIfMissingScript(recipe: EngineInstallRecipe, runtimeNode: string, friendly?: FriendlyInstall, home?: string, downloadEngine = friendly?.engine): string {
const install = recipe.command
- const label = friendly ? (friendly.engine === 'claude' ? 'Claude Code' : engineLabel(friendly.engine)) : ''
+ const label = downloadEngine ? (downloadEngine === 'claude' ? 'Claude Code' : engineLabel(downloadEngine)) : ''
const seconds = friendly ? (TYPICAL_INSTALL_SECONDS[friendly.engine] ?? 15) : 0
const names = recipe.executable.names.map(shellSingleQuote).join(' ')
- const paths = engineInstallPaths(recipe).map(shellSingleQuote).join(' ')
+ const paths = engineInstallPaths(recipe, home).map(shellSingleQuote).join(' ')
+ const prefix = home ? join(home, '.local') : npmEnginePrefix()
// Scope both npm env spellings to the installer subprocess. Do not rewrite .npmrc or install
// into a different OS user's shared prefix, and do not tie the engine to a versioned Node folder.
// Either way a subshell, run at the top level where a stop is resumed (STOP_PROOF_FUNCTIONS).
const run = (line: string) => recipe.executable.npmGlobal
- ? `(export npm_config_prefix=${shellSingleQuote(npmEnginePrefix())} NPM_CONFIG_PREFIX=${shellSingleQuote(npmEnginePrefix())}; eval ${shellSingleQuote(line)})`
+ ? `(export npm_config_prefix=${shellSingleQuote(prefix)} NPM_CONFIG_PREFIX=${shellSingleQuote(prefix)}; eval ${shellSingleQuote(line)})`
: `(eval ${shellSingleQuote(line)})`
const installCommand = run(install)
// The same line, its output into the log and the progress on the screen. Its status is the
@@ -1173,7 +1191,7 @@ function installIfMissingScript(recipe: EngineInstallRecipe, runtimeNode: string
// The waiting runs in command substitutions, out of a Ctrl+Z's reach (STOP_PROOF_FUNCTIONS), with
// the bar sent to the terminal through standard error. A wait ended early (Ctrl-C, the ten
// minutes) while the download still runs ends the pane rather than starting a second install.
- ...(friendly ? [
+ ...(downloadEngine ? [
'harness_wait_download() {',
' harness_dl_pid=$(cat "$HOME/.harness/run/downloading-$1" 2>/dev/null) || return 0',
" case \"$harness_dl_pid\" in ''|*[!0-9]*) return 0 ;; esac",
@@ -1181,7 +1199,7 @@ function installIfMissingScript(recipe: EngineInstallRecipe, runtimeNode: string
' ps -p "$harness_dl_pid" -o command= 2>/dev/null | grep -q harness-download || return 0',
' if [ "$harness_quiet" -eq 1 ]; then',
' harness_dl_w=$( ( harness_dl_i=0; while kill -0 "$harness_dl_pid" 2>/dev/null && [ "$harness_dl_i" -lt 1200 ]; do sleep 0.5; harness_dl_i=$((harness_dl_i + 1)); done ) | '
- + `${shellSingleQuote(runtimeNode)} -e ${shellSingleQuote(INSTALL_PROGRESS_JS)} ${shellSingleQuote(label)} ${seconds} "$harness_install_log" ${friendly.messageWaiting ? 1 : 0} >&2 ) || :`,
+ + `${shellSingleQuote(runtimeNode)} -e ${shellSingleQuote(INSTALL_PROGRESS_JS)} ${shellSingleQuote(label)} ${seconds} "$harness_install_log" ${friendly?.messageWaiting ? 1 : 0} >&2 ) || :`,
' else',
` printf '%s\\n' ${shellSingleQuote(`harness: ${label} is downloading in the background; waiting for it`)}`,
' harness_dl_i=0; while kill -0 "$harness_dl_pid" 2>/dev/null && [ "$harness_dl_i" -lt 1200 ]; do harness_dl_w=$(sleep 0.5) || :; harness_dl_i=$((harness_dl_i + 1)); done',
@@ -1196,8 +1214,8 @@ function installIfMissingScript(recipe: EngineInstallRecipe, runtimeNode: string
// Beside the log rather than in a temporary folder: nothing machine-specific in the script.
'harness_install_rc="$HOME/.harness/logs/install-' + friendly.engine.replace(/[^a-z0-9-]/g, '') + '-$$.rc"',
`[ -x ${shellSingleQuote(runtimeNode)} ] && mkdir -p "$HOME/.harness/logs" 2>/dev/null && harness_quiet=1`,
- `harness_find_engine "$1" || harness_wait_download ${shellSingleQuote(friendly.engine.replace(/[^a-z0-9-]/g, ''))}`,
] : []),
+ ...(downloadEngine ? [`harness_find_engine "$1" || harness_wait_download ${shellSingleQuote(downloadEngine.replace(/[^a-z0-9-]/g, ''))}`] : []),
'if ! harness_find_engine "$1"; then',
...(recipe.executable.npmGlobal ? [
' if ! command -v npm >/dev/null 2>&1; then',
@@ -1228,6 +1246,20 @@ function installIfMissingScript(recipe: EngineInstallRecipe, runtimeNode: string
].filter(Boolean).join('\n') + '\n'
}
+/** An installation dependency only. Core must rebuild a launch after this exits;
+ * no engine argv or first prompt is carried into the installer. */
+export function buildEngineInstallationArgv(engine: AgentEngine, recipe: EngineInstallRecipe,
+ environment: Record<string, string>, runtimeNode: string = managedNodePath()): string[] {
+ const shell = interactiveEngineShell(environment.SHELL) ?? { path: posixRunner(), args: ['-c'], label: 'shell' }
+ if (Object.keys(environment).some(key => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))) throw new Error('Invalid installation environment name')
+ const locations = Object.entries(environment).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}\n`).join('')
+ // A detached dependency has no foreground terminal job. Keep descendants in
+ // its one process group so a deadline also ends stopped installer children.
+ const body = RAISE_OPEN_FILES_SH + clearEnvPrelude(LAUNCH_LOCATION_VARIABLES.filter(key => !(key in environment))) + locations + 'set +m 2>/dev/null || :\n' + STOP_PROOF_FUNCTIONS
+ + installIfMissingScript(recipe, runtimeNode, undefined, environment.HOME, engine) + 'exit 0\n'
+ return engineShellArgv(shell, [body, 'harness-native-install', engineBin(engine)])
+}
+
function availabilityScript(recipe: EngineInstallRecipe | undefined): string {
const names = recipe?.executable.names.map(shellSingleQuote).join(' ') ?? ''
const paths = recipe ? engineInstallPaths(recipe).map(shellSingleQuote).join(' ') : ''
@@ -1436,8 +1468,14 @@ export async function refusePermissionFlagIfUnsupported(
engine: AgentEngine,
choice: PermissionLaunchChoice,
shell: string | undefined = undefined,
-): Promise<{ error: string; detail: string } | null> {
- const flag = await unsupportedPermissionFlag(engine, choice, shell)
+ native?: NativeLaunch,
+): Promise<{ error: string; detail: string; unavailable?: string } | null> {
+ if (native) {
+ const support = await native.permission(choice)
+ if (support === 'unknown') return { error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting to confirm the selected executable’s permission flags.' }
+ if (support === 'supported') return null
+ }
+ const flag = native ? permissionFlagToVerify(engine, choice) : await unsupportedPermissionFlag(engine, choice, shell)
if (!flag) return null
return {
error: 'CODEX_CLI_TOO_OLD',
@@ -1456,8 +1494,11 @@ export async function dropPermissionFlagIfUnsupported<T extends PermissionLaunch
engine: AgentEngine,
choice: T,
shell: string | undefined = undefined,
-): Promise<{ choice: T; droppedFlag: string | null }> {
- const droppedFlag = await unsupportedPermissionFlag(engine, choice, shell)
+ native?: NativeLaunch,
+): Promise<{ choice: T; droppedFlag: string | null; nativeHold?: string }> {
+ const support = native ? await native.permission(choice) : null
+ if (support === 'unknown') return { choice, droppedFlag: null, nativeHold: 'Waiting to confirm the selected executable’s permission flags.' }
+ const droppedFlag = support === 'supported' ? null : native ? permissionFlagToVerify(engine, choice) : await unsupportedPermissionFlag(engine, choice, shell)
if (!droppedFlag) return { choice, droppedFlag: null }
return { choice: { ...choice, permissionMode: 'ask', bypassPermission: false }, droppedFlag }
}
diff --git a/cli/src/lib/gridConfigCompatibility.golden.spec.ts b/cli/src/lib/gridConfigCompatibility.golden.spec.ts
new file mode 100644
index 000000000..d7da364cb
--- /dev/null
+++ b/cli/src/lib/gridConfigCompatibility.golden.spec.ts
@@ -0,0 +1,38 @@
+/** Healthy file and link contents from main, before immutable launch publications. */
+import { mkdirSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, beforeAll, expect, it, vi } from 'vitest'
+
+const artifact = fileURLToPath(new URL('./__fixtures__/grid-config-compatibility.golden.json', import.meta.url))
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+let root: string
+beforeAll(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'grid-config-golden-')))
+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })
+ vi.stubEnv('TZ', 'UTC'); vi.stubEnv('HOME', root); vi.stubEnv('ADAPTER_DATA_DIR', root)
+ vi.resetModules()
+})
+afterAll(() => { Object.defineProperty(process, 'platform', platform); vi.unstubAllEnvs(); rmSync(root, { recursive: true, force: true }) })
+it('preserves the files selected by fresh and changed grid launches and their borrowed sessions', async () => {
+ const { publishGridConfigDir } = await import('./publishedGridConfig.js')
+ const target = join(root, 'native-sessions'); mkdirSync(target)
+ writeFileSync(join(target, 'session.json'), '{"fixture":"retained conversation"}\n')
+ const actual: Record<string, unknown> = {}
+ for (const [name, files, links] of [
+ ['pi', [{ name: 'models.json', content: '{"providers":{"fixture":{"apiKey":"GRID_API_KEY"}}}\n' }, { name: 'settings.json', content: '{"skills":["/fixture/skills"]}\n' }], []],
+ ['opencode', [{ name: 'opencode.json', content: '{"provider":{"fixture":{"npm":"@ai-sdk/openai-compatible"}}}\n' }], []],
+ ['grok', [{ name: 'settings.json', content: '{"baseUrl":"https://fixture.invalid/v1"}\n' }], [{ name: 'sessions', target }]],
+ ['pi', [{ name: 'models.json', content: '{"providers":{"other":{"apiKey":"GRID_API_KEY"}}}\n' }, { name: 'settings.json', content: '{"skills":["/fixture/skills"]}\n' }], []],
+ ] as const) {
+ const { directory } = await publishGridConfigDir(name, files, links)
+ actual[`${name}-${Object.keys(actual).length}`] = {
+ files: Object.fromEntries(files.map(file => [file.name, readFileSync(join(directory, file.name), 'utf8')])),
+ links: Object.fromEntries(links.map(link => [link.name, readlinkSync(join(directory, link.name)).replace(root, '<root>')])),
+ conversation: readFileSync(join(target, 'session.json'), 'utf8'),
+ }
+ }
+ if (process.env.RECORD_GRID_CONFIG_GOLDEN === '1') writeFileSync(artifact, JSON.stringify(actual, null, 2) + '\n')
+ else expect(actual).toEqual(JSON.parse(readFileSync(artifact, 'utf8')))
+})
diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.ts
index bcb56745b..dda728057 100644
--- a/cli/src/lib/gridLaunch.spec.ts
+++ b/cli/src/lib/gridLaunch.spec.ts
@@ -43,6 +43,14 @@ function launchOf(engine: AgentEngine, override = WITH_MODEL, machine = PLAIN_MA
return built.launch
}
+it('borrows Grok conversations and Pi skills from the captured launch home', () => {
+ const machine = { ...PLAIN_MACHINE, grokHome: '/fixture/shell-grok', piSkillsDir: '/fixture/shell-pi/skills' }
+ expect(launchOf('grok', WITH_MODEL, machine).configDir!.links!.map(link => link.target))
+ .toEqual(expect.arrayContaining(['/fixture/shell-grok/sessions']))
+ const settings = launchOf('pi', WITH_MODEL, machine).configDir!.files.find(file => file.name === 'settings.json')!
+ expect(JSON.parse(settings.content).skills).toEqual(['/fixture/shell-pi/skills'])
+})
+
describe('parseGridLaunchOverride', () => {
it('reads absent as absent, not as a failure', () => {
// The whole no-regression promise rests on this: a client with no grid selected sends no field,
diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.ts
index ad9072a7f..74a79fcf3 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -544,7 +544,7 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
// the default the New Agent dialog shows, into a refusal at the moment of clicking Create —
// trading a 401 the user could not diagnose for a wall they could not get past. Same trade
// OpenCode faced, same answer (see `GRID_ROUTER_MODEL` in its contract above).
- build: (override) => {
+ build: (override, machine) => {
// One name, used in three places that must agree: argv, the config block's header, and the
// `model` field inside it. A mismatch would declare a credential for a model Grok never asks for.
const model = override.model ?? GRID_ROUTER_MODEL
@@ -575,7 +575,7 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
relayBaseUrl(override.baseUrl),
),
}],
- links: GROK_GRID_HOME_LINKS.map((name) => ({ name, target: join(userGrokHome(), name) })),
+ links: GROK_GRID_HOME_LINKS.map((name) => ({ name, target: join(machine.grokHome ?? userGrokHome(), name) })),
},
webSearch: webSearchWhenWired(override),
}
@@ -595,7 +595,7 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
// always creates on Auto and no longer offers a model field — a dead end, not a prompt to go and
// pick something.
pi: {
- build: (override) => {
+ build: (override, machine) => {
const model = override.model ?? GRID_ROUTER_MODEL
return {
env: { [GRID_KEY_VAR]: override.apiKey },
@@ -604,7 +604,7 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
envVar: 'PI_CODING_AGENT_DIR',
files: [
{ name: 'models.json', content: piModelsJson(relayBaseUrl(override.baseUrl), model, override.contextWindow) },
- { name: 'settings.json', content: piSettingsJson(userPiSkillsDir()) },
+ { name: 'settings.json', content: piSettingsJson(machine.piSkillsDir ?? userPiSkillsDir()) },
],
},
// Pi has no MCP client, so there is nothing to hand the server to — with or without a url.
diff --git a/cli/src/lib/gridLaunchWire.ts b/cli/src/lib/gridLaunchWire.ts
index ab7e1d5ec..1a7da0171 100644
--- a/cli/src/lib/gridLaunchWire.ts
+++ b/cli/src/lib/gridLaunchWire.ts
@@ -262,6 +262,9 @@ export interface GridLaunchRecord {
* caller (create, retarget, restore) gets the same answer from the same code.
*/
export interface GridLaunchMachine {
+ /** Original native locations captured before a grid redirects configuration. */
+ grokHome?: string
+ piSkillsDir?: string
/**
* Whether an administrator pinned Hermes settings in [HERMES_SYSTEM_MANAGED_DIR]. Hermes's web
* tools ride a managed-scope overlay that REPLACES that directory rather than adding to it, so on
diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.ts
index d21738b7d..4da279c65 100644
--- a/cli/src/lib/launchOverrides.spec.ts
+++ b/cli/src/lib/launchOverrides.spec.ts
@@ -107,7 +107,7 @@ describe('buildLaunchOverrides — a relaunch comes back where the agent was', (
gridLaunchRecord: { override: { apiKey: GRID.apiKey } },
} })
expect(calls).toEqual(['writeConfig:agent-1'])
- expect(machine).toHaveBeenCalledExactlyOnceWith('opencode')
+ expect(machine).toHaveBeenCalledExactlyOnceWith('opencode', undefined)
expect(await prepared.commit()).toMatchObject({ error: 'LAUNCH_PREPARATION_USED' })
expect(calls).toHaveLength(1)
})
@@ -193,7 +193,7 @@ describe('buildLaunchOverrides — a relaunch comes back where the agent was', (
await buildLaunchOverrides(deps({ machine }).d, 'claude', { gridLaunch: GRID, subscriptionModel: 'opus' }, 'agent-1')
expect(machine.mock.calls.every(([engine]) => engine === 'claude')).toBe(true)
await buildLaunchOverrides(deps({ machine }).d, 'opencode', { agent: 'reviewer' }, 'agent-1')
- expect(machine).toHaveBeenLastCalledWith('opencode')
+ expect(machine).toHaveBeenLastCalledWith('opencode', undefined)
expect(loadEngine).not.toHaveBeenCalled()
})
diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.ts
index 9b2c324fa..c1407e2ad 100644
--- a/cli/src/lib/launchOverrides.ts
+++ b/cli/src/lib/launchOverrides.ts
@@ -13,6 +13,7 @@
*/
import { join } from 'node:path'
+import type { NativeLaunch, NativeLaunchResult, NativeLaunchSource } from '../engines/nativeLaunch.js'
import type { AgentEngine } from '../engines/types.js'
import { subscriptionModelLaunch } from './subscriptionModel.js'
import { ownLoginProviderArgs } from '../engines/launches.js'
@@ -32,8 +33,12 @@ import { harnessEnvToClear } from '../dsh/launch.js'
import type { DshLaunchAnswer } from '../dsh/launchWire.js'
import { scmLaunchEnv } from '../scm/scmProjects.js'
import type { ScmLaunchRecord } from '../scm/types.js'
+import type { CreationAuthority } from './agentCreationReceipt.js'
+import type { publishGridConfigDir } from './publishedGridConfig.js'
+import { nativeHookLocations } from '../engines/kit/nativeLocations.js'
export interface LaunchOverrides {
+ native?: NativeLaunch
/** Layered over the pane's inherited environment. The grid key lives here, and only here. */
env: Record<string, string>
/** Appended to the engine's argv (`-c model_providers…`, `-m …`, `--mcp-config …`). */
@@ -67,8 +72,9 @@ export type LaunchPreparationResult =
| Extract<LaunchOverridesResult, { ok: false }>
export interface LaunchOverridesDeps {
+ publishConfig?: typeof publishGridConfigDir
/** The facts about THIS machine a contract needs and cannot read for itself — see `GridLaunchMachine`. */
- machine: (engine: AgentEngine) => GridLaunchMachine | Promise<GridLaunchMachine>
+ machine: (engine: AgentEngine, native?: NativeLaunch) => GridLaunchMachine | Promise<GridLaunchMachine>
/** A grid or saved-API launch, built by the models service (core/agents/launch.ts `gridLaunchThrough`): the core
* builds none itself. */
gridLaunch: (request: GridLaunchRequest) => Promise<GridLaunchAnswer>
@@ -81,6 +87,9 @@ export interface LaunchOverridesDeps {
/** Install the daemon's hooks into a non-default Codex profile. The caller decides whether hook
* installation is enabled at all. */
installCodexHooks: (codexHome: string) => boolean | Promise<boolean>
+ /** Core composes eager native preparation; absent only for legacy/golden callers. */
+ native?: (engine: AgentEngine, source: NativeLaunchSource, authority: Pick<CreationAuthority, 'id' | 'current'>) => Promise<NativeLaunchResult>
+ prepareNative?: (native: NativeLaunch, current: () => boolean, environment?: Readonly<Record<string, string>>, clear?: readonly string[]) => Promise<boolean>
/**
* Read a Codex `config.toml`, for the provider an agent goes back to when it leaves a grid.
*
@@ -96,7 +105,7 @@ export interface LaunchOverridesDeps {
}
/** Where the agent should come back: the registry row, or an override the desktop just sent. */
-export interface LaunchSource {
+export interface LaunchSource extends NativeLaunchSource {
gridLaunch?: GridLaunchOverride | null
codexHome?: string | null
/**
@@ -146,9 +155,10 @@ export async function validateLaunchOverrides(
deps: Pick<LaunchOverridesDeps, 'tmuxSupportsSessionEnv' | 'machine' | 'gridLaunch'>,
engine: AgentEngine,
source: LaunchSource,
+ native?: NativeLaunch,
): Promise<{ ok: true } | { ok: false; error: string; detail: string; unavailable?: string }> {
if (!source.gridLaunch) return { ok: true }
- const built = await deps.gridLaunch({ engine, override: source.gridLaunch, machine: await deps.machine(engine) })
+ const built = await deps.gridLaunch({ engine, override: source.gridLaunch, machine: await deps.machine(engine, native) })
if (!built.ok) return { ok: false, error: built.error, detail: built.detail, ...(built.unavailable ? { unavailable: built.unavailable } : {}) }
return tmuxRefusal(deps, engine, source.gridLaunch)
}
@@ -173,8 +183,9 @@ export async function buildLaunchOverrides(
source: LaunchSource,
configKey: string,
current: () => boolean = () => true,
+ capturedNative?: NativeLaunch,
): Promise<LaunchOverridesResult> {
- const prepared = await prepareLaunchOverrides(deps, engine, source, configKey, current)
+ const prepared = await prepareLaunchOverrides(deps, engine, source, configKey, current, capturedNative)
return prepared.ok ? prepared.commit() : prepared
}
@@ -186,12 +197,27 @@ export async function prepareLaunchOverrides(
source: LaunchSource,
configKey: string,
current: () => boolean = () => true,
+ capturedNative?: NativeLaunch,
): Promise<LaunchPreparationResult> {
const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during launch preparation.' } as const
if (!current()) return changed
+ const owner = current
source = structuredClone(source)
- const machine = { ...await deps.machine(engine) }
- const base = await prepareBaseLaunchOverrides({ ...deps, machine: () => machine }, engine, source, configKey)
+ const inspected = capturedNative ? { ok: true as const, launch: capturedNative } : await deps.native?.(engine, source, { id: configKey, current: owner })
+ if (!current()) return changed
+ if (inspected && !inspected.ok) return inspected
+ const native = inspected?.ok ? inspected.launch : undefined
+ if (engine === 'codex' && native) source.codexHome = nativeHookLocations(native.environment).CODEX_HOME
+ current = () => owner() && native?.current() !== false
+ if (!current()) return changed
+ const machine = { ...await deps.machine(engine, native) }
+ const base = await prepareBaseLaunchOverrides({ ...deps, machine: () => machine,
+ ...(native && deps.publishConfig ? { writeGridConfigDir: async (key, files, links) => {
+ const published = await deps.publishConfig!(key, files, links, current)
+ if (!native.retain?.(published.proof)) throw Error('Generated configuration authority changed')
+ return published.directory
+ } } : {}),
+ }, engine, source, configKey)
if (!current()) return changed
if (!base.ok) return base
if (source.dsh && !source.cwd) return { ok: false, error: 'DSH_WORKSPACE_MISSING', detail: `${source.dsh} has no saved workspace` }
@@ -215,6 +241,7 @@ export async function prepareLaunchOverrides(
if (!current()) return changed
if (committed) return { ok: false, error: 'LAUNCH_PREPARATION_USED', detail: 'Launch preparation must be requested again before another attempt.' }
committed = true
+ if (!current()) return changed
const written = await base.commit()
if (!current()) return changed
if (!written.ok) return written
@@ -226,6 +253,12 @@ export async function prepareLaunchOverrides(
// The workspace's own SCM binding layers last: it is the daemon's, like `HARNESS_*`, and neither a
// grid nor a DSH has a say in which workspace the pane is bound to. Nothing for git, so a git row's
// overrides are exactly what they were.
+ // File-configured engines can move their native home. Prepare hooks after
+ // those operation-owned locations are known, before any native dispatch.
+ if (native && deps.prepareNative && !await deps.prepareNative(native, owner, overrides.env, overrides.clearEnv)) {
+ return { ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting to confirm the engine’s native hook preparation.' }
+ }
+ if (!current()) return changed
const scmEnv = scmLaunchEnv(source.scmLaunch)
if (scmEnv) overrides = { ...overrides, env: { ...overrides.env, ...scmEnv } }
// The named agent rides every relaunch, in the same argv slot `agent_create` put it in. Only an
@@ -238,7 +271,7 @@ export async function prepareLaunchOverrides(
if (source.agent && supportsNamedAgent(engine, opencodeMajor)) {
overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...namedAgentArgs(engine, source.agent, opencodeMajor)] }
}
- return { ok: true, overrides: { ...overrides, clearEnv: [...overrides.clearEnv, ...harnessEnvToClear(overrides.env)] } }
+ return { ok: true, overrides: { ...overrides, ...(native ? { native, env: { ...overrides.env, ...native.environment } } : {}), clearEnv: [...overrides.clearEnv, ...harnessEnvToClear(overrides.env)] } }
} }
}
@@ -293,7 +326,7 @@ async function prepareBaseLaunchOverrides(
env[envVar] = pointAt ? join(dir, pointAt) : dir
} catch (error) {
const detail = `could not write ${engine}'s grid configuration · ${error instanceof Error ? error.message : error}`
- return { ok: false, error: 'GRID_CONFIG_FAILED', detail }
+ return { ok: false, error: 'GRID_CONFIG_FAILED', detail, ...(deps.native ? { unavailable: 'native' } : {}) }
}
}
// Derived from what this launch actually provides (the config-dir variable included), so an
@@ -315,7 +348,9 @@ async function prepareBaseLaunchOverrides(
// not the one `harness login` installed into — without this it fires no hook at all. Idempotent.
const home = source.codexHome
return { ok: true, commit: async () => {
- if (!await deps.installCodexHooks(home)) return {
+ // A production native preparation covers the selected profile before any
+ // grid/configuration commit. Legacy callers must also await and check it.
+ if (!deps.native && !await deps.installCodexHooks(home)) return {
ok: false, error: 'NATIVE_LAUNCH_HELD', unavailable: 'native', detail: 'Waiting to confirm Codex’s hooks in the selected profile.',
}
return {
diff --git a/cli/src/lib/launchPreparation.ts b/cli/src/lib/launchPreparation.ts
new file mode 100644
index 000000000..9ecfcbaf4
--- /dev/null
+++ b/cli/src/lib/launchPreparation.ts
@@ -0,0 +1,9 @@
+import type { CreationAuthority } from './agentCreationReceipt.js'
+
+/** Persist `label` with the request before doing any preparation. Retries and a
+ * reconstructed core must keep the same workspace, config and runtime keys. */
+export interface LaunchAuthority extends CreationAuthority { readonly label: string }
+
+export type LaunchPreparation<Result> =
+ | { ok: true; dispatch: () => Promise<Result> }
+ | { ok: false; error: string; detail?: string; unavailable?: string }
diff --git a/cli/src/lib/nativePaneHold.spec.ts b/cli/src/lib/nativePaneHold.spec.ts
new file mode 100644
index 000000000..c1dd51ce1
--- /dev/null
+++ b/cli/src/lib/nativePaneHold.spec.ts
@@ -0,0 +1,99 @@
+import { randomUUID } from 'node:crypto'
+import { existsSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, onTestFailed, vi } from 'vitest'
+import { heldPaneArgv } from '../core/agents/heldLaunches.js'
+import { isolatedTmux, type IsolatedTmux } from '../testing/isolatedTmux.js'
+import { resolveBinaryOnPath } from './binaryOnPath.js'
+import { nativePaneHold, NATIVE_LAUNCH_MARKER } from './nativePaneHold.js'
+import { shellSingleQuote } from './shellQuote.js'
+import { TmuxBackend } from './tmuxBackend.js'
+import { resetTmuxVersionCache } from './tmuxVersion.js'
+import { paneOwnerFormat, paneOwnerOf } from './harnessSessionLabel.js'
+
+const binary = resolveBinaryOnPath('tmux')
+const owner = 'd00df00dd00df00d'
+const hold = (token: string, binary: string | null, command: string) => nativePaneHold(token, binary, command, process.execPath, owner)
+describe.skipIf(!binary)('native guard publication on private tmux servers', () => {
+ let tmux: IsolatedTmux, other: IsolatedTmux | undefined
+ const backend = new TmuxBackend(undefined, () => owner, () => {})
+ beforeEach(async () => {
+ tmux = await isolatedTmux()
+ tmux.env.HOME = tmux.root; tmux.env.ZDOTDIR = tmux.root
+ vi.stubEnv('HOME', tmux.root); vi.stubEnv('ZDOTDIR', tmux.root)
+ vi.stubEnv('TMUX', undefined); vi.stubEnv('TMUX_PANE', undefined); vi.stubEnv('TMUX_TMPDIR', tmux.root)
+ resetTmuxVersionCache()
+ await tmux.run('new-session', '-d', '-s', 'fixture-anchor', '/bin/sleep', '300')
+ })
+ afterEach(async () => { await other?.close(); other = undefined; await tmux.close(); vi.unstubAllEnvs(); resetTmuxVersionCache() })
+ const start = async (token: string, script: string, sourced = false) => {
+ const file = join(tmux.root, randomUUID() + '.sh'); writeFileSync(file, script)
+ const result = await backend.create({ label: `harness-fixture-${randomUUID()}`, command: [
+ '/usr/bin/env', `${NATIVE_LAUNCH_MARKER}=${token}`, '/bin/sh', '-c', sourced ? `. ${shellSingleQuote(file)}` : script,
+ ] })
+ if (result.state !== 'succeeded') throw Error(result.reason)
+ return result.runtime
+ }
+ const held = (token: string) => heldPaneArgv('Private native hold.', token).map(shellSingleQuote).join(' ')
+
+ it.each([false, true])('recognizes a guard only after its inert transition: sourced %s', async sourced => {
+ const token = randomUUID(), release = join(tmux.root, 'release')
+ const script = `while [ ! -f ${shellSingleQuote(release)} ]; do sleep 0.01; done\n` + hold(token, binary!, held(token))
+ const pane = await start(token, script, sourced)
+ expect(await backend.isHeld(pane, token)).toBe(false)
+ expect(await backend.respawn(pane, { command: ['/bin/false'], expectedHeldToken: token })).toMatchObject({ dispatch: 'not_started' })
+ expect(await backend.killHeld(pane, token, () => true)).toMatchObject({ dispatch: 'not_started' })
+ writeFileSync(release, '')
+ await vi.waitFor(async () => expect(await backend.isHeld(pane, token)).toBe(true))
+ // Before tmux 3.0 a renamed/moved pane cannot borrow its old window tag.
+ const session = await tmux.run('display-message', '-p', '-t', pane.paneId, '#{session_id}')
+ await tmux.run('rename-session', '-t', session, 'foreign-' + randomUUID())
+ expect(paneOwnerOf(await tmux.run('display-message', '-p', '-t', pane.paneId, paneOwnerFormat(false)))).toBe(owner)
+ expect(await backend.killHeld(pane, token, () => true)).toMatchObject({ state: 'succeeded' })
+ })
+
+ it.each(['pane', 'socket'] as const)('does not replace a foreign pane when rc changes the %s', async changed => {
+ other = await isolatedTmux(tmux.env)
+ await other.run('new-session', '-d', '-s', 'foreign', '/bin/sleep', '300')
+ const foreign = await backend.create({ label: `harness-foreign-${randomUUID()}`, command: ['/bin/sleep', '300'] })
+ if (foreign.state !== 'succeeded') throw Error(foreign.reason)
+ const original = await tmux.run('display-message', '-p', '-t', foreign.runtime.paneId, '#{pane_pid}')
+ const otherPid = await other.run('display-message', '-p', '-t', '%0', '#{pane_pid}')
+ const token = randomUUID()
+ const redirect = changed === 'pane' ? `export TMUX_PANE=${shellSingleQuote(foreign.runtime.paneId)}\n`
+ : `export TMUX=${shellSingleQuote(other.socket + ',1,0')}; export TMUX_PANE=%0\n`
+ const pane = await start(token, redirect + hold(token, binary!, held(token)))
+ await vi.waitFor(async () => expect(await tmux.run('capture-pane', '-p', '-t', pane.paneId)).toContain('Private native hold.'))
+ expect(await tmux.run('display-message', '-p', '-t', foreign.runtime.paneId, '#{pane_pid}')).toBe(original)
+ expect(await other.run('display-message', '-p', '-t', '%0', '#{pane_pid}')).toBe(otherPid)
+ expect(await backend.isHeld(pane, token)).toBe(false)
+ })
+
+ it('bounds a stalled transition and kills its client before falling back inert', async () => {
+ const token = randomUUID(), pidFile = join(tmux.root, 'client-pid'), binary = join(tmux.root, 'stalled-tmux')
+ writeFileSync(binary, `#!${process.execPath}\nrequire('node:fs').writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); setInterval(() => {}, 1000);\n`, { mode: 0o700 })
+ const pane = await start(token, hold(token, binary, held(token)))
+ onTestFailed(async () => console.log(await tmux.run('capture-pane', '-p', '-t', pane.paneId)))
+ await vi.waitFor(() => expect(existsSync(pidFile)).toBe(true), { timeout: 3_000 })
+ const pid = Number(readFileSync(pidFile, 'utf8'))
+ await vi.waitFor(async () => expect(await tmux.run('capture-pane', '-p', '-t', pane.paneId)).toContain('Private native hold.'), { timeout: 5_000 })
+ expect(() => process.kill(pid, 0)).toThrow()
+ expect(await backend.isHeld(pane, token)).toBe(false)
+ }, 10_000)
+
+ it('rejects a delayed server command after a replacement, even if it carries the original nonce', async () => {
+ const token = randomUUID(), replacement = randomUUID(), invocation = join(tmux.root, 'invocation.json')
+ const recorder = join(tmux.root, 'record-tmux')
+ writeFileSync(recorder, `#!${process.execPath}\nrequire('node:fs').writeFileSync(${JSON.stringify(invocation)}, JSON.stringify(process.argv.slice(2)));\n`, { mode: 0o700 })
+ const pane = await start(token, hold(token, recorder, held(token)))
+ await vi.waitFor(() => expect(existsSync(invocation)).toBe(true))
+ const args = JSON.parse(readFileSync(invocation, 'utf8')) as string[]
+ // Preserve the old nonce in the new start command too: PID must independently fence it.
+ const replacementCommand = heldPaneArgv(`Replacement ${NATIVE_LAUNCH_MARKER}=${token}`, replacement)
+ expect(await backend.respawn(pane, { command: replacementCommand })).toMatchObject({ state: 'succeeded' })
+ const before = await tmux.run('display-message', '-p', '-t', pane.paneId, '#{pane_pid}')
+ await tmux.run(...args)
+ expect(await tmux.run('display-message', '-p', '-t', pane.paneId, '#{pane_pid}')).toBe(before)
+ expect(await tmux.run('display-message', '-p', '-t', pane.paneId, '#{pane_start_command}')).toContain(replacement)
+ })
+})
diff --git a/cli/src/lib/nativePaneHold.ts b/cli/src/lib/nativePaneHold.ts
new file mode 100644
index 000000000..52f841d21
--- /dev/null
+++ b/cli/src/lib/nativePaneHold.ts
@@ -0,0 +1,30 @@
+/** The native guard may replace only its own still-current shell, inside tmux. */
+import { shellSingleQuote } from './shellQuote.js'
+
+export const NATIVE_LAUNCH_MARKER = 'HARNESS_NATIVE_LAUNCH_TOKEN'
+
+/** An inline launch script mentions the held command before it ever runs it. */
+export function heldPaneFormat(token: string): string {
+ return `#{&&:#{==:#{m:*${NATIVE_LAUNCH_MARKER}=*,#{pane_start_command}},0},#{&&:#{m:*harness-held*,#{pane_start_command}},#{m:*${token}*,#{pane_start_command}}}}`
+}
+
+export function nativePaneHold(token: string, tmuxBinary: string | null, heldCommand: string, node: string, owner: string): string {
+ // This tag is captured by core, never read from a post-rc environment. Older
+ // tmux keeps pane ownership in this prefix when a pane moves between windows.
+ if (!/^[a-f0-9]{16}$/.test(owner)) throw new Error('Invalid native pane owner')
+ const command = `/usr/bin/env HARNESS_DAEMON=${owner} ${heldCommand}`
+ // Rc files can change TMUX and TMUX_PANE; neither grants authority. The target
+ // must still contain this exact live shell PID and this launch's original nonce.
+ // The predicate and respawn run together in the server. A timed-out client can
+ // leave a queued command, which cannot replace a newer pane occupant.
+ const publish = [
+ 'const [tmux,pane,pid,nonce,held]=process.argv.slice(1);',
+ 'if(/^%[0-9]+$/.test(pane)&&/^[0-9]+$/.test(pid)){',
+ 'const proof="#{&&:#{==:#{pane_id},"+pane+"},#{&&:#{==:#{pane_pid},"+pid+"},#{m:*"+nonce+"*,#{pane_start_command}}}}";',
+ 'try{require("node:child_process").execFileSync(tmux,["if-shell","-F","-t",pane,proof,"respawn-pane -k -t "+pane+" "+held],',
+ '{timeout:2000,killSignal:"SIGKILL",stdio:"ignore"})}catch{}}',
+ ].join('')
+ const transition = tmuxBinary ? `${shellSingleQuote(node)} -e ${shellSingleQuote(publish)} ${shellSingleQuote(tmuxBinary)} "${'${TMUX_PANE:-}'}" "$$" ${shellSingleQuote(`${NATIVE_LAUNCH_MARKER}=${token}`)} ${shellSingleQuote(command)}\n` : ''
+ // A missing or stalled server still leaves an inert shell, never an engine.
+ return transition + `exec ${command}`
+}
diff --git a/cli/src/lib/publishedGridConfig.spec.ts b/cli/src/lib/publishedGridConfig.spec.ts
new file mode 100644
index 000000000..03f0e9d11
--- /dev/null
+++ b/cli/src/lib/publishedGridConfig.spec.ts
@@ -0,0 +1,164 @@
+import { lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+const fault = vi.hoisted(() => ({ fail: false, current: true, onSync: undefined as (() => void) | undefined }))
+vi.mock('node:fs', async real => {
+ const actual = await real<typeof import('node:fs')>()
+ return { ...actual, fsync: (fd: number, done: (error: NodeJS.ErrnoException | null) => void) => {
+ fault.onSync?.()
+ if (fault.fail) queueMicrotask(() => done(Error('fixture disk unavailable')))
+ else actual.fsync(fd, done)
+ } }
+})
+let root: string
+let publish: typeof import('./publishedGridConfig.js').publishGridConfigDir
+beforeEach(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'published-grid-')))
+ vi.stubEnv('HOME', root); vi.stubEnv('ADAPTER_DATA_DIR', root)
+ fault.fail = false; fault.current = true; fault.onSync = undefined
+ vi.resetModules(); publish = (await import('./publishedGridConfig.js')).publishGridConfigDir
+})
+afterEach(() => { vi.unstubAllEnvs(); vi.restoreAllMocks(); rmSync(root, { recursive: true, force: true }) })
+const files = [{ name: 'models.json', content: '{"model":"fixture"}\n' }]
+
+it('publishes complete immutable versions and preserves a live version across an unavailable replacement', async () => {
+ const before = await publish('fixture-agent', files)
+ expect(before.proof.current()).toBe(true)
+ expect(lstatSync(before.directory).mode & 0o777).toBe(0o700)
+ const changed = [{ name: 'models.json', content: '{"model":"other"}\n' }]
+ fault.fail = true
+ await expect(publish('fixture-agent', changed)).rejects.toThrow('fixture disk unavailable')
+ expect(readFileSync(join(before.directory, 'models.json'), 'utf8')).toBe(files[0]!.content)
+ expect(before.proof.current()).toBe(true)
+ fault.fail = false
+ const after = await publish('fixture-agent', changed)
+ expect(after.directory).not.toBe(before.directory)
+ expect(after.proof.current()).toBe(true)
+ expect((await publish('fixture-agent', changed)).directory).toBe(after.directory)
+ expect(readFileSync(join(before.directory, 'models.json'), 'utf8')).toBe(files[0]!.content)
+})
+
+it('never overwrites changed published files or a borrowed conversation directory', async () => {
+ const target = join(root, 'native', 'sessions'), links = [{ name: 'sessions', target }]
+ const result = await publish('fixture-agent', files, links)
+ expect(readlinkSync(join(result.directory, 'sessions'))).toBe(target)
+ writeFileSync(join(target, 'conversation'), 'retained user data')
+ writeFileSync(join(result.directory, 'models.json'), 'foreign configuration')
+ expect(result.proof.current()).toBe(false)
+ await expect(publish('fixture-agent', files, links)).rejects.toThrow('published configuration was changed')
+ expect(readFileSync(join(result.directory, 'models.json'), 'utf8')).toBe('foreign configuration')
+ expect(readFileSync(join(target, 'conversation'), 'utf8')).toBe('retained user data')
+})
+
+it('invalidates borrowed-directory aliases in the retained dispatch proof', async () => {
+ const a = join(root, 'a'), b = join(root, 'b'), alias = join(root, 'home')
+ mkdirSync(a); mkdirSync(b); symlinkSync(a, alias)
+ const result = await publish('fixture-agent', files, [{ name: 'sessions', target: join(alias, 'sessions') }])
+ expect(result.proof.current()).toBe(true)
+ rmSync(alias); symlinkSync(b, alias)
+ expect(result.proof.current()).toBe(false)
+ expect(result.proof.files.some(file => file.facts.some(fact => fact.path === alias && fact.alias))).toBe(true)
+})
+
+it('holds when ownership changes during disk confirmation and safely resumes the same private publication', async () => {
+ fault.onSync = () => { fault.current = false }
+ await expect(publish('fixture-agent', files, [], () => fault.current)).rejects.toThrow()
+ fault.onSync = undefined; fault.current = true
+ const result = await publish('fixture-agent', files)
+ expect(result.proof.current()).toBe(true)
+})
+
+it('does not let a changed native alias during publication redirect borrowed sessions', async () => {
+ const a = join(root, 'a'), b = join(root, 'b'), alias = join(root, 'home')
+ mkdirSync(a); mkdirSync(b); symlinkSync(a, alias)
+ fault.onSync = () => { fault.onSync = undefined; rmSync(alias); symlinkSync(b, alias) }
+ await expect(publish('fixture-agent', files, [{ name: 'sessions', target: join(alias, 'sessions') }])).rejects.toThrow()
+ expect(() => lstatSync(join(b, 'sessions'))).toThrow()
+})
+
+it('checks every file, manifest and directory again when a completed publication is reused', async () => {
+ const first = await publish('fixture-agent', files)
+ renameSync(first.directory, first.directory + '-foreign')
+ mkdirSync(first.directory, { mode: 0o700 })
+ expect(first.proof.current()).toBe(false)
+ // A new directory cannot borrow the old completion. Its old owned files stay intact.
+ await expect(publish('fixture-agent', files)).rejects.toThrow('directory identity changed')
+ expect(readFileSync(join(first.directory + '-foreign', 'models.json'), 'utf8')).toBe(files[0]!.content)
+})
+
+it('pins a newly created directory across its first ownership-record flush', async () => {
+ let replaced = ''
+ fault.onSync = () => {
+ const parent = join(root, 'grid-launch-config')
+ const names = readdirSync(parent)
+ if (!names.some(name => name.startsWith('.harness-hook-') && name.endsWith('.tmp')
+ && JSON.parse(readFileSync(join(parent, name), 'utf8')).directory)) return
+ const leaf = names.find(name => /^[a-f0-9]{64}$/.test(name))!
+ replaced = join(parent, leaf)
+ fault.onSync = undefined
+ renameSync(replaced, replaced + '-original'); mkdirSync(replaced, { mode: 0o700 })
+ }
+ await expect(publish('fixture-agent', files)).rejects.toThrow()
+ expect(replaced).not.toBe('')
+ expect(readdirSync(replaced)).toEqual([])
+ expect(readdirSync(replaced + '-original')).toEqual([])
+ await expect(publish('fixture-agent', files)).rejects.toThrow()
+})
+
+it('retains the original native alias when a joining publisher captures its link proof', async () => {
+ const a = join(root, 'a'), b = join(root, 'b'), alias = join(root, 'home')
+ mkdirSync(join(a, 'sessions'), { recursive: true }); mkdirSync(join(b, 'sessions'), { recursive: true }); symlinkSync(a, alias)
+ const { NativePaths } = await import('../engines/kit/nativePaths.js')
+ const original = NativePaths.prototype.resolveSync
+ let linkReads = 0
+ vi.spyOn(NativePaths.prototype, 'resolveSync').mockImplementation(function (this: InstanceType<typeof NativePaths>, path, missingOkay) {
+ if (path.startsWith(join(root, 'grid-launch-config')) && path.endsWith('/sessions') && ++linkReads === 2) {
+ rmSync(alias); symlinkSync(b, alias)
+ }
+ return original.call(this, path, missingOkay)
+ })
+ const links = [{ name: 'sessions', target: join(alias, 'sessions') }]
+ const results = await Promise.allSettled([publish('fixture-agent', files, links), publish('fixture-agent', files, links)])
+ expect(linkReads).toBeGreaterThanOrEqual(2)
+ expect(results[1]!.status).toBe('rejected')
+ for (const result of results) if (result.status === 'fulfilled') expect(result.value.proof.current()).toBe(false)
+})
+
+it('holds a removed published file instead of recreating it behind an existing process', async () => {
+ const first = await publish('fixture-agent', files)
+ rmSync(join(first.directory, 'models.json'))
+ await expect(publish('fixture-agent', files)).rejects.toThrow('configuration was removed')
+ expect(first.proof.current()).toBe(false)
+ expect(() => lstatSync(join(first.directory, 'models.json'))).toThrow()
+})
+
+it.each(['missing', 'replaced'] as const)('holds a %s borrowed session directory without recreating or adopting it', async kind => {
+ const target = join(root, 'native-home', 'sessions')
+ const links = [{ name: 'sessions', target }]
+ const first = await publish('fixture-agent', files, links)
+ writeFileSync(join(target, 'conversation'), 'original history')
+ renameSync(target, target + '-retained')
+ if (kind === 'replaced') mkdirSync(target)
+ await expect(publish('fixture-agent', files, links)).rejects.toThrow()
+ expect(first.proof.current()).toBe(false)
+ expect(readFileSync(join(target + '-retained', 'conversation'), 'utf8')).toBe('original history')
+ if (kind === 'missing') expect(() => lstatSync(target)).toThrow()
+ else expect(readdirSync(target)).toEqual([])
+})
+
+it('does not recreate a removed publication directory that a live engine may still name', async () => {
+ const first = await publish('fixture-agent', files)
+ renameSync(first.directory, first.directory + '-retained')
+ await expect(publish('fixture-agent', files)).rejects.toThrow()
+ expect(() => lstatSync(first.directory)).toThrow()
+ expect(readFileSync(join(first.directory + '-retained', 'models.json'), 'utf8')).toBe(files[0]!.content)
+})
+
+it.each([
+ ['../escape', 'content'], ['.harness-config.json', 'content'], ['same/name', 'content'], ['models.json', 'x'.repeat(1024 * 1024)],
+])('holds invalid or oversized configuration %s', async (name, content) => {
+ await expect(publish('fixture-agent', [{ name, content }])).rejects.toThrow()
+ expect(() => lstatSync(join(root, 'grid-launch-config'))).toThrow()
+})
diff --git a/cli/src/lib/publishedGridConfig.ts b/cli/src/lib/publishedGridConfig.ts
new file mode 100644
index 000000000..f75821f52
--- /dev/null
+++ b/cli/src/lib/publishedGridConfig.ts
@@ -0,0 +1,167 @@
+/** Immutable, operation-owned grid configuration. A replacement launch never
+ * edits the directory still used by the live process it may later replace. */
+import { createHash } from 'node:crypto'
+import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readlinkSync, symlinkSync } from 'node:fs'
+import { dirname, isAbsolute, join } from 'node:path'
+import { env } from '../config/env.js'
+import { NativeEvidenceBudget } from '../engines/kit/nativeEvidence.js'
+import { NativePaths, verifyNativePathFacts, type NativePathFact } from '../engines/kit/nativePaths.js'
+import { HookPreparationHeld, hookPreparationRoutes, inspectHookFile, runHookPreparation, type HookPreparationAttempt, type HookPreparationProof } from '../engines/kit/nativeHookFiles.js'
+import type { GridConfigFile, GridConfigLink } from './gridLaunchWire.js'
+
+const identity = (info: NonNullable<ReturnType<typeof lstatSync>>) => `${info.dev}:${info.ino}:${info.mode}:${info.uid}`
+const missing = (error: unknown) => (error as NodeJS.ErrnoException).code === 'ENOENT'
+function privateDirectory(path: string, create = true): void {
+ if (create) mkdirSync(path, { recursive: true, mode: 0o700 })
+ const info = lstatSync(path)
+ if (!info.isDirectory() || (info.mode & 0o777) !== 0o700 || (process.getuid && info.uid !== process.getuid())) {
+ throw new HookPreparationHeld('the generated configuration directory is not private')
+ }
+}
+async function syncDirectory(path: string, attempt: HookPreparationAttempt): Promise<void> {
+ attempt.verify()
+ const expected = identity(lstatSync(path))
+ const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
+ try {
+ if (identity(fstatSync(fd)) !== expected) throw new HookPreparationHeld('the directory changed before confirmation')
+ await attempt.flush(fd)
+ if (identity(lstatSync(path)) !== expected) throw new HookPreparationHeld('the directory changed during confirmation')
+ } finally { closeSync(fd) }
+}
+
+export async function publishGridConfigDir(key: string, inputFiles: readonly GridConfigFile[], inputLinks: readonly GridConfigLink[] = [], current = () => true): Promise<{ directory: string; proof: HookPreparationProof }> {
+ const files = inputFiles.map(file => ({ ...file })), links = inputLinks.map(link => ({ ...link }))
+ const names = [...files, ...links].map(item => item.name)
+ if (!current() || !key || key.length > 4096 || !files.length || files.length > 16 || links.length > 8
+ || new Set(names).size !== names.length || names.some(name => !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(name))
+ || files.some(file => typeof file.content !== 'string')
+ || links.some(link => !isAbsolute(link.target) || link.target.includes('\0') || link.target.length > 4096)) {
+ throw new HookPreparationHeld('the generated configuration request is invalid')
+ }
+ const content = JSON.stringify({ version: 1, key, files, links })
+ if (Buffer.byteLength(content) > 1024 * 1024) throw new HookPreparationHeld('the generated configuration exceeds its limit')
+ const digest = createHash('sha256').update(content).digest('hex')
+ // A separate root keeps the legacy age-based prune away from active publications.
+ const root = join(env.ADAPTER_DATA_DIR, 'grid-launch-config'), directory = join(root, digest)
+ const manifest = join(root, `${digest}.json`), ready = join(directory, '.harness-config.json')
+ const owner = `${manifest}.directory`, completion = `${manifest}.complete`
+ const linkRecord = (link: GridConfigLink) => `${manifest}.${link.name}.link`
+ const destinations = [manifest, owner, completion, ready, ...files.map(file => join(directory, file.name)), ...links.map(linkRecord)]
+ const rootRoute = hookPreparationRoutes([manifest])
+ const targetRoutes = links.length ? hookPreparationRoutes(links.map(link => join(link.target, '.harness-route'))) : undefined
+ rootRoute.verify(); if (!current()) throw new HookPreparationHeld('the launch request changed')
+ privateDirectory(root); rootRoute.verify()
+ let proof: HookPreparationProof | undefined
+ let linkFacts: NativePathFact[] = []
+ await runHookPreparation(destinations, async attempt => {
+ targetRoutes?.verify()
+ const intended = inspectHookFile(manifest, 0o600)
+ if (intended.content !== null && intended.content !== content) throw new HookPreparationHeld('the publication manifest changed')
+ if (intended.content === null) {
+ try { lstatSync(directory); throw new HookPreparationHeld('the generated directory has no ownership manifest') }
+ catch (error) { if (!missing(error)) throw error }
+ }
+ await intended.replace(content, attempt, intended.content === null)
+ attempt.verify()
+ const ownership = inspectHookFile(owner, 0o600)
+ if (ownership.content === null) {
+ // Only a successful mkdir can assign this previously unowned directory.
+ // A crash before its identity is durable leaves a visible hold, not an
+ // invitation to adopt another directory at the same name.
+ mkdirSync(directory, { mode: 0o700 })
+ }
+ privateDirectory(directory, false)
+ const directoryPaths = new NativePaths(new NativeEvidenceBudget(250)), selectedDirectory = directoryPaths.resolveSync(directory)!
+ const directoryFacts = directoryPaths.snapshot()
+ attempt.observe(directory, () => verifyNativePathFacts(directoryFacts))
+ const ownerBytes = JSON.stringify({ digest, directory: identity(selectedDirectory.info) })
+ if (ownership.content !== null && ownership.content !== ownerBytes) throw new HookPreparationHeld('the publication directory identity changed')
+ await ownership.replace(ownerBytes, attempt, ownership.content === null)
+ const settled = inspectHookFile(completion, 0o600), completedBefore = inspectHookFile(ready, 0o600)
+ if ((settled.content !== null && settled.content !== ownerBytes)
+ || (completedBefore.content !== null && completedBefore.content !== digest)) throw new HookPreparationHeld('the publication completion changed')
+ for (const file of files) {
+ const target = join(directory, file.name), previous = inspectHookFile(target, 0o600)
+ // Engines and people may have edited a prior publication. Preserve it.
+ if (previous.content !== null && previous.content !== file.content) throw new HookPreparationHeld('a published configuration was changed')
+ if (previous.content === null && (settled.content !== null || completedBefore.content !== null)) throw new HookPreparationHeld('a published configuration was removed')
+ await previous.replace(file.content, attempt, previous.content === null)
+ }
+ for (const link of links) {
+ const path = join(directory, link.name)
+ const remembered = inspectHookFile(linkRecord(link), 0o600)
+ if (remembered.content !== null) {
+ const saved = JSON.parse(remembered.content)
+ if (saved.version !== 1 || saved.target !== link.target || !Array.isArray(saved.facts)) throw new HookPreparationHeld('the borrowed native authority changed')
+ verifyNativePathFacts(saved.facts)
+ } else {
+ if (settled.content !== null || completedBefore.content !== null) throw new HookPreparationHeld('the borrowed native authority is missing')
+ try { lstatSync(path); throw new HookPreparationHeld('the native link has no retained authority') }
+ catch (error) { if (!missing(error)) throw error }
+ }
+ const route = hookPreparationRoutes([join(link.target, '.harness-route')])
+ targetRoutes?.verify(); route.verify(); attempt.verify()
+ mkdirSync(link.target, { recursive: true, mode: 0o700 })
+ route.verify()
+ // The borrowed native directory may be an existing, verified alias.
+ const targetPaths = new NativePaths(new NativeEvidenceBudget(250)), target = targetPaths.resolveSync(link.target)
+ if (!target?.info.isDirectory()) throw new HookPreparationHeld('the borrowed native location is not a directory')
+ const retained = targetPaths.snapshot()
+ const authorityBytes = JSON.stringify({ version: 1, target: link.target, facts: retained })
+ if (remembered.content !== null && remembered.content !== authorityBytes) throw new HookPreparationHeld('the borrowed native location changed')
+ attempt.observe(link.target, () => verifyNativePathFacts(retained))
+ await remembered.replace(authorityBytes, attempt, remembered.content === null)
+ for (let parent = target.path, depth = 0; ; parent = dirname(parent)) {
+ if (depth++ > 256) throw new HookPreparationHeld('the borrowed location exceeds its depth limit')
+ verifyNativePathFacts(retained); route.verify(); await syncDirectory(parent, attempt)
+ if (parent === '/') break
+ }
+ attempt.verify(); route.verify(); verifyNativePathFacts(retained)
+ try {
+ const existing = lstatSync(path)
+ if (!existing.isSymbolicLink() || readlinkSync(path) !== link.target) throw new HookPreparationHeld('the borrowed native link changed')
+ } catch (error) {
+ if (!missing(error)) throw error
+ if (settled.content !== null || completedBefore.content !== null) throw new HookPreparationHeld('a published native link was removed')
+ symlinkSync(link.target, path, 'dir')
+ }
+ const selected = new NativePaths(new NativeEvidenceBudget(250))
+ selected.resolveSync(path)
+ const facts = selected.snapshot()
+ linkFacts.push(...facts)
+ attempt.observe(path, () => verifyNativePathFacts(facts))
+ await syncDirectory(directory, attempt)
+ }
+ const completed = inspectHookFile(ready, 0o600)
+ if (completed.content !== null && completed.content !== digest) throw new HookPreparationHeld('the publication completion changed')
+ await completed.replace(digest, attempt, completed.content === null)
+ await settled.replace(ownerBytes, attempt, settled.content === null)
+ }, { current, identity: digest, retainConflicts: true, confirmed: result => { proof = result } })
+ targetRoutes?.verify()
+ for (const link of links) {
+ const path = join(directory, link.name)
+ if (!lstatSync(path).isSymbolicLink() || readlinkSync(path) !== link.target) throw new HookPreparationHeld('the borrowed native link changed before acknowledgement')
+ const saved = JSON.parse(inspectHookFile(linkRecord(link), 0o600).content ?? 'null')
+ if (!saved || saved.version !== 1 || saved.target !== link.target || !Array.isArray(saved.facts)) throw new HookPreparationHeld('the borrowed native authority is missing')
+ verifyNativePathFacts(saved.facts)
+ linkFacts.push(...saved.facts)
+ }
+ // Joined publishers still retain their own link routes, not a peer's closure.
+ for (const link of links) {
+ const paths = new NativePaths(new NativeEvidenceBudget(250)); paths.resolveSync(join(directory, link.name)); linkFacts.push(...paths.snapshot())
+ }
+ const retained = new Map<string, NativePathFact>()
+ for (const fact of [...linkFacts, ...targetRoutes?.facts ?? []]) {
+ const previous = retained.get(fact.path)
+ if (previous && JSON.stringify(previous) !== JSON.stringify(fact)) throw new HookPreparationHeld('the borrowed native route changed before acknowledgement')
+ retained.set(fact.path, fact)
+ }
+ linkFacts = [...retained.values()]
+ const published = proof!
+ const confirmed: HookPreparationProof = {
+ files: published.files.map((file, index) => index === 0 ? { ...file, facts: [...file.facts, ...linkFacts] } : file),
+ current: () => { try { targetRoutes?.verify(); if (linkFacts.length) verifyNativePathFacts(linkFacts); return published.current() } catch { return false } },
+ }
+ if (!current() || !confirmed.current()) throw new HookPreparationHeld('the generated configuration changed before acknowledgement')
+ return { directory, proof: confirmed }
+}
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index bff1a274c..fe701cf10 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -61,7 +61,7 @@ import { externalReservations, externalResumePending, externalResumeIds, parseEx
export type { ProcessIdentity } from './terminalTypes.js'
export type AgentLaunch =
- | { state: 'starting' }
+ | { state: 'starting'; nativeToken?: string }
| { state: 'ready' }
| { state: 'failed'; error: string; detail?: string }
/**
@@ -69,7 +69,7 @@ export type AgentLaunch =
* grid or saved-API agent while models is not running. Nothing about the agent is wrong. It waits in a pane
* that says why, and is launched once the service is ready. Never a failure: a restore tries it again.
*/
- | { state: 'held'; service: string; detail: string }
+ | { state: 'held'; service: string; detail: string; nativeToken?: string }
/** Claude Code's hooks report `model` as {id, display_name}; Codex/Cursor report a plain string. This is
* the boundary where hook JSON becomes persisted state, so anything else is dropped rather than stored —
@@ -687,11 +687,13 @@ function normalizedForkedFrom(value: unknown): { forkedFrom: ForkOrigin } | Reco
function normalizedLaunch(value: unknown): AgentLaunch | undefined {
if (!value || typeof value !== 'object') return undefined
const launch = value as { state?: unknown; error?: unknown; detail?: unknown }
- if (launch.state === 'starting' || launch.state === 'ready') return { state: launch.state }
+ const token = (value as { nativeToken?: unknown }).nativeToken
+ const nativeToken = typeof token === 'string' && /^[a-f0-9-]{36}$/.test(token) ? token : undefined
+ if (launch.state === 'starting' || launch.state === 'ready') return { state: launch.state, ...(launch.state === 'starting' && nativeToken ? { nativeToken } : {}) }
if (launch.state === 'held') {
const held = value as { service?: unknown; detail?: unknown }
if (typeof held.service !== 'string' || !/^[a-z][a-z-]{0,39}$/.test(held.service) || typeof held.detail !== 'string') return undefined
- return { state: 'held', service: held.service, detail: held.detail.slice(0, 500) }
+ return { state: 'held', service: held.service, detail: held.detail.slice(0, 500), ...(nativeToken ? { nativeToken } : {}) }
}
if (launch.state !== 'failed' || typeof launch.error !== 'string' || !launch.error) return undefined
const error = launch.error.slice(0, 80)
@@ -1566,6 +1568,7 @@ class Registry {
/** Register a terminal route before its engine process exists. */
openPendingAgent(input: {
+ nativeToken?: string
engine: AgentEngine
runtimes: TerminalRuntimeRef[]
primaryRuntimeKey?: string
@@ -1602,7 +1605,7 @@ class Registry {
const entry: RegisteredSession = {
schemaVersion: 2,
active: !externalResume,
- launch: externalResume ? { state: 'held', service: 'search', detail: 'Waiting for the search service to verify this conversation.' } : { state: 'starting' },
+ launch: externalResume ? { state: 'held', service: 'search', detail: 'Waiting for the search service to verify this conversation.' } : { state: 'starting', ...(input.nativeToken ? { nativeToken: input.nativeToken } : {}) },
...(externalResume ? { externalResume } : {}),
defaultName: normalizedDefaultName(input.defaultName) ?? this.automaticName(input.label?.trim() || engineLabel(input.engine), new Date(now)),
agentId,
@@ -1653,7 +1656,7 @@ class Registry {
/** A stopped agent gets a new terminal route while keeping its saved conversation and identity.
* Archived routes/processes are evidence only: none of them may be indexed or signalled here. */
- resumePendingAgent(saved: RegisteredSession, runtimes: TerminalRuntimeRef[]): RegisteredSession | null {
+ resumePendingAgent(saved: RegisteredSession, runtimes: TerminalRuntimeRef[], nativeToken?: string): RegisteredSession | null {
if (this.writeBlocked || this.agents.has(saved.agentId)
|| (saved.sessionId && this.bySession(saved.sessionId))) return null
const routes = normalizedRuntimes(runtimes)
@@ -1664,7 +1667,7 @@ class Registry {
boundAt: null,
lastHookAt: 0,
active: true,
- launch: { state: 'starting' },
+ launch: { state: 'starting', ...(nativeToken ? { nativeToken } : {}) },
processIdentity: null,
runtimes: routes,
primaryRuntimeKey: selectedRuntimeKey(routes, ''),
diff --git a/cli/src/lib/restoreAgents.spec.ts b/cli/src/lib/restoreAgents.spec.ts
index f5b51f6cd..d7f157c90 100644
--- a/cli/src/lib/restoreAgents.spec.ts
+++ b/cli/src/lib/restoreAgents.spec.ts
@@ -8,6 +8,7 @@ import { AgentRestartCoordinator } from './restartAgent.js'
import { createHeldLaunches } from '../core/agents/heldLaunches.js'
import { createPaneSwap } from '../core/agents/swap.js'
import { createPaneOperations } from '../core/agents/paneOperations.js'
+import { createAgentRestarter, type RestartDeps } from '../core/agents/restart.js'
vi.mock('./captureResumeIdentity.js', () => ({ captureResumeIdentity: async (entry: RegisteredSession) => entry }))
@@ -65,6 +66,111 @@ interface Harness {
released: string[]
}
+it.each(['held alive', 'held gone', 'starting alive', 'starting gone'] as const)('preserves the original native first launch through recovery: %s', async phase => {
+ const entry = row({ sessionId: '', launch: phase.startsWith('held')
+ ? { state: 'held', service: 'native', nativeToken: 'original', detail: 'Original launch held' }
+ : { state: 'starting', nativeToken: 'original' } })
+ const h = harness([entry], { alivePanes: phase.endsWith('alive') ? ['%3'] : [] })
+ h.deps.waitingPane = async () => true
+ h.deps.keepAbandoned = vi.fn()
+ const held = createHeldLaunches({ registry: h.deps.registry, restore: only => restoreAgents({ ...h.deps, only }), log: () => {} })
+ await held.boot(() => restoreAgents(h.deps))
+ expect(entry.launch).toMatchObject({ state: 'held', nativeToken: 'original' })
+ expect(await held.restartHeld(entry.agentId)).toMatchObject({ ok: false, error: 'SERVICE_UNAVAILABLE' })
+ await held.restoreHeld()
+ held.close()
+ expect(h.launches).toEqual([])
+ expect(h.paneCreates).toBe(0)
+ expect(h.respawns).toBe(0)
+ expect(h.deps.keepAbandoned).not.toHaveBeenCalled()
+})
+
+it('revokes an active held restore when shutdown begins during launch preparation', async () => {
+ const entry = row({ launch: heldLaunch('native') }), before = structuredClone(entry)
+ const h = harness([entry], { alivePanes: ['%3'] })
+ let finish!: (launch: RestoreLaunch) => void, preparationCurrent!: () => boolean
+ h.deps.buildLaunch = vi.fn(async (_entry, control) => {
+ preparationCurrent = control.current!
+ expect(preparationCurrent()).toBe(true)
+ return new Promise<RestoreLaunch>(done => { finish = done })
+ })
+ h.deps.keepAbandoned = vi.fn()
+ const held = createHeldLaunches({ registry: h.deps.registry, log: () => {},
+ restore: (only, current) => restoreAgents({ ...h.deps, only, cancelled: () => !current() }) })
+ await held.boot(async () => {})
+ const pending = held.restoreHeld()
+ await vi.waitFor(() => expect(h.deps.buildLaunch).toHaveBeenCalledOnce())
+ held.close()
+ expect(preparationCurrent()).toBe(false)
+ finish({ argv: ['must-not-run-after-shutdown'] })
+ await pending
+ expect(entry).toEqual(before)
+ expect(h.paneCreates).toBe(0)
+ expect(h.respawns).toBe(0)
+ expect(h.deps.keepAbandoned).not.toHaveBeenCalled()
+})
+
+it.each([false, 'unknown'] as const)('keeps an unrecognized inert launch held after crash and watcher expiry: %s', async waiting => {
+ const entry = row({ sessionId: '', launch: { state: 'starting', nativeToken: 'original' } })
+ const h = harness([entry], { alivePanes: ['%3'], budgetMs: 0 })
+ h.deps.waitingPane = vi.fn(async () => waiting)
+ h.deps.keepAbandoned = vi.fn()
+ await restoreAgents(h.deps)
+ await settled(h, 1)
+ expect(entry.launch).toMatchObject({ state: 'held', service: 'native', nativeToken: 'original' })
+ const restart = createAgentRestarter({
+ registry: { ...h.deps.registry, resolve: (id: string) => h.rows.get(id) },
+ restartJobs: new AgentRestartCoordinator(), purgeBusy: () => false,
+ stopJobs: new Map(), pinnedControls: new Set(), tmuxBackend: null, restartHeld: () => null,
+ } as unknown as RestartDeps)
+ expect(await restart(entry.agentId)).toMatchObject({ ok: false, error: 'NATIVE_LAUNCH_HELD' })
+ expect(h.launches).toEqual([])
+ expect(h.paneCreates).toBe(0)
+ expect(h.respawns).toBe(0)
+ expect(h.deps.keepAbandoned).not.toHaveBeenCalled()
+})
+
+it.each([false, true])('does not abandon a resume when its fresh fallback proof expires waiting for the pane: terminal %s', async terminalHost => {
+ const h = harness([row({ terminalHost })])
+ h.deps.keepAbandoned = vi.fn()
+ h.states.set('%0', [{ dead: true }])
+ let valid = true, fallback = false
+ const build = h.deps.buildLaunch
+ h.deps.buildLaunch = async (entry, options) => {
+ if (options.resumeSessionId) return build(entry, options)
+ fallback = true
+ return { argv: ['fixture-fresh'], current: () => valid, nativeToken: 'replacement' }
+ }
+ h.deps.paneOperation = async (_id, work) => { if (fallback) valid = false; return work() }
+ await restoreAgents(h.deps)
+ await vi.waitFor(() => expect(fallback).toBe(true))
+ await vi.waitFor(() => expect(h.released).toHaveLength(1))
+ expect(h.deps.keepAbandoned).not.toHaveBeenCalled()
+ expect(h.calls).not.toContain('unbind:session-a')
+ expect(h.respawns).toBe(1) // The original resume only; no fresh fallback.
+})
+
+it('publishes the fresh fallback token before dispatch and recognizes its own guard hold', async () => {
+ const h = harness([row()])
+ h.states.set('%0', [{ dead: true }, { dead: false }])
+ const build = h.deps.buildLaunch
+ h.deps.buildLaunch = async (entry, options) => options.resumeSessionId ? build(entry, options)
+ : { argv: ['fixture-fresh'], current: () => true, nativeToken: 'fresh-fallback' }
+ const respawn = h.deps.respawn
+ h.deps.respawn = async (runtime, launch, control) => {
+ if (!launch.nativeToken) return respawn(runtime, launch, control)
+ control!.onDispatch!()
+ expect(h.rows.get('agent-a')!.launch).toEqual({ state: 'starting', nativeToken: 'fresh-fallback' })
+ expect(control!.current!()).toBe(true)
+ return respawn(runtime, launch, { ...control!, onDispatch: undefined })
+ }
+ h.deps.waitingPane = vi.fn(async (_runtime, token) => token === 'fresh-fallback')
+ await restoreAgents(h.deps)
+ await vi.waitFor(() => expect(h.rows.get('agent-a')!.launch).toMatchObject({ state: 'held', nativeToken: 'fresh-fallback' }))
+ expect(h.deps.waitingPane).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%0' }, 'fresh-fallback')
+ expect(h.respawns).toBe(2) // Resume, then the one proven fresh fallback.
+})
+
function harness(rows: RegisteredSession[], opts: { livePanes?: string[]; alivePanes?: string[]; failCreate?: boolean; refuseLaunch?: boolean; budgetMs?: number; settleMs?: number } = {}): Harness {
const h: Harness = {
calls: [],
diff --git a/cli/src/lib/restoreAgents.ts b/cli/src/lib/restoreAgents.ts
index f1f269154..1f5300003 100644
--- a/cli/src/lib/restoreAgents.ts
+++ b/cli/src/lib/restoreAgents.ts
@@ -43,6 +43,8 @@ import { terminalRouteKey } from './terminalRuntime.js'
import { resumesConversation } from './resumeCapability.js'
export interface RestoreLaunch {
+ nativeToken?: string
+ current?(): boolean
argv: string[]
env?: Record<string, string>
}
@@ -395,7 +397,18 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu
// Held: its pane, alive, runs no engine on purpose, so it is neither a stopped engine nor a terminal. Its
// launch goes into that pane, or a new one if the pane went (a reboot).
if (entry.launch?.state === 'held') {
+ // A first launch/fork has no conversation to resume yet. Its saved row
+ // cannot reconstruct the original prompt or fork argv. Keep the explicit
+ // hold until that exact request can recover it; a fresh launch is different work.
+ if (entry.launch.nativeToken && !entry.sessionId) {
+ summary.skipped.push({ agentId: entry.agentId, reason: 'original native launch awaits recovery' })
+ continue
+ }
const alive = deps.livePane ? await surveyed(deps, patience, () => deps.livePane!(runtime)) : false
+ if (alive && entry.launch.nativeToken && await deps.waitingPane?.(runtime, entry.launch.nativeToken) !== true) {
+ if (current()) summary.unsurveyed.push(entry.agentId)
+ continue
+ }
if (current()) missing.push({ entry, runtime, current, ...(alive ? { alive: true as const } : {}) })
continue
}
@@ -414,6 +427,20 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu
// clock misread; a tmux server that outlived the daemon) is re-identified right here, so the
// reconciler adopts it by process instead of treating it as an unbound route.
if (!entry.processIdentity) deps.registry.updateProcessIdentity(entry.agentId, engineLive)
+ } else if (entry.launch?.state === 'starting' && entry.launch.nativeToken) {
+ const waiting = await deps.waitingPane?.(runtime, entry.launch.nativeToken)
+ if (!current()) continue
+ if (waiting === true) {
+ const row = deps.registry.setLaunch(entry.agentId, { state: 'held', service: 'native', nativeToken: entry.launch.nativeToken,
+ detail: 'Waiting to confirm the engine executable and native hooks.' })!
+ const copy = { ...row }
+ if (!copy.sessionId) summary.skipped.push({ agentId: entry.agentId, reason: 'original native launch awaits recovery' })
+ else missing.push({ entry: copy, runtime, alive: true, current: restoreOwner(deps, copy) })
+ } else {
+ const route = terminalRouteKey(runtime)
+ const release = deps.holdRoute(route, (deps.budgetMs ?? DEFAULT_BUDGET_MS) + HOLD_SLACK_MS) ?? (() => deps.releaseRoute(route))
+ void watchRestoredPane(deps, entry, runtime, !!entry.sessionId, deps.budgetMs ?? DEFAULT_BUDGET_MS, current, release)
+ }
} else if (entry.externalResume?.phase === 'admitted' && entry.launch?.state === 'starting') {
// The dispatch journal precedes tmux. If its exact waiting shell remains, no engine ran;
// otherwise an installer/engine may still be starting: observe it, never respawn over it.
@@ -435,6 +462,12 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu
}
continue
}
+ if (entry.launch?.state === 'starting' && entry.launch.nativeToken && !entry.sessionId) {
+ deps.registry.setLaunch(entry.agentId, { state: 'held', service: 'native', nativeToken: entry.launch.nativeToken,
+ detail: 'The first launch was interrupted before its conversation was confirmed. The original request is held for recovery.' })
+ summary.skipped.push({ agentId: entry.agentId, reason: 'original native launch awaits recovery' })
+ continue
+ }
// A strict-resume row that was never CONFIRMED (its launch still `starting` when the daemon
// died) goes back to the archive for an explicit Open: nothing proved the engine ever loaded
// that conversation, and this pass has no way to ask. One that was confirmed — hook received,
@@ -502,7 +535,7 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu
const unavailable = new Map<string, string | undefined>()
/** Held in its waiting pane: the one it has, or a new one. False when no pane could be opened for it. */
const hold = async (entry: RegisteredSession, runtime: TmuxRuntimeRef, alive: boolean, current: () => boolean, service: string, detail?: string): Promise<boolean> => inPane(deps, entry, current, async owns => {
- const launch = { ...heldLaunch(service), ...(detail ? { detail } : {}) } as Extract<AgentLaunch, { state: 'held' }>
+ const launch = { ...heldLaunch(service), ...((entry.launch?.state === 'held' || entry.launch?.state === 'starting') && entry.launch.nativeToken ? { nativeToken: entry.launch.nativeToken } : {}), ...(detail ? { detail } : {}) } as Extract<AgentLaunch, { state: 'held' }>
let pane = runtime
if (!alive) {
const created = await deps.createPane(entry, deps.waitingLaunch?.(entry, launch) ?? { argv: [] }, { current })
@@ -570,7 +603,7 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu
let owns = initialOwner
const pane = dead
const existing = !!alive
- const dispatchCurrent = () => owns() && !deps.cancelled?.(entry.agentId)
+ const dispatchCurrent = () => owns() && !deps.cancelled?.(entry.agentId) && launch.current?.() !== false
if (!dispatchCurrent()) return
let release: (() => void) | undefined
if (existing && !isTerminalEngine(entry.engine)) {
@@ -579,12 +612,17 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu
}
let watching = false
try {
- const control = { current: dispatchCurrent, ...(entry.externalResume ? { expectedHeldToken: entry.externalResume.token } : {}), onDispatch: () => {
+ const control = { current: dispatchCurrent, ...(entry.externalResume ? { expectedHeldToken: entry.externalResume.token } : entry.launch?.state === 'held' && entry.launch.nativeToken ? { expectedHeldToken: entry.launch.nativeToken } : {}), onDispatch: () => {
if (entry.externalResume?.phase === 'admitted') {
const committed = deps.registry.beginExternalDispatch?.(entry.agentId)
if (!committed) throw new Error('External resume dispatch could not be committed')
owns = restoreOwner(deps, committed, !!deps.paneOperation)
}
+ if (launch.nativeToken) {
+ const committed = deps.registry.setLaunch(entry.agentId, { state: 'starting', nativeToken: launch.nativeToken })
+ if (!committed) throw new Error('Native launch dispatch could not be committed')
+ owns = restoreOwner(deps, committed, !!deps.paneOperation)
+ }
// Before the engine can hook/attach, not after tmux's asynchronous reply.
if (resumeSessionId) deps.engineStarted?.(resumeSessionId)
} }
@@ -627,7 +665,7 @@ export async function restoreAgents(input: RestoreAgentsDeps): Promise<RestoreSu
deps.log(`[restore] terminal · agent ${entry.agentId} · pane ${dead.paneId} → ${created.runtime.paneId}`)
return
}
- deps.registry.setLaunch(entry.agentId, { state: 'starting' })
+ deps.registry.setLaunch(entry.agentId, { state: 'starting', ...(launch.nativeToken ? { nativeToken: launch.nativeToken } : {}) })
summary.restored.push(entry.agentId)
deps.log(`[restore] ${entry.engine} · agent ${entry.agentId} · pane ${dead.paneId} → ${created.runtime.paneId}`
+ (resumeSessionId ? ` · resuming ${resumeSessionId.slice(0, 8)}` : ' · fresh session')
@@ -704,12 +742,13 @@ async function watchRestoredPane(
fail(launch.error, launch.detail)
return false
}
- return inPane(deps, entry, current, async () => {
+ const dispatchCurrent = () => current() && launch.current?.() !== false
+ return inPane(deps, entry, dispatchCurrent, async () => {
deps.keepAbandoned?.({ ...entry })
deps.registry.releaseEngine(agentId)
current = restoreOwner(deps, deps.registry.byAgent(agentId)!)
const owns = restoreOwner(deps, deps.registry.byAgent(agentId)!, !!deps.paneOperation)
- const spawned = await deps.respawn(runtime, launch, { current })
+ const spawned = await deps.respawn(runtime, launch, { current: dispatchCurrent })
if (!owns()) return false
if (!spawned.ok) {
fail('ENGINE_DID_NOT_START', `The terminal could not be reopened: ${spawned.reason ?? 'unknown reason'}`)
@@ -731,17 +770,25 @@ async function watchRestoredPane(
fail(launch.error, launch.detail)
return false
}
- return inPane(deps, entry, current, async () => {
+ const dispatchCurrent = () => current() && launch.current?.() !== false
+ return inPane(deps, entry, dispatchCurrent, async () => {
// Preparation is confirmed before archiving or unbinding. A service outage preserves the
// conversation held here, including when a refused resume falls back to a fresh launch.
deps.keepAbandoned?.({ ...entry })
deps.registry.inheritName(entry.sessionId, agentId)
deps.registry.unbindSession(entry.sessionId)
current = restoreOwner(deps, deps.registry.byAgent(agentId)!)
- const owns = restoreOwner(deps, deps.registry.byAgent(agentId)!, !!deps.paneOperation)
+ let owns = restoreOwner(deps, deps.registry.byAgent(agentId)!, !!deps.paneOperation)
// Renew before dispatch, so discovery cannot bind the new engine before its tmux reply.
release = deps.holdRoute(key, budgetMs + HOLD_SLACK_MS) ?? (() => deps.releaseRoute(key))
- const spawned = await deps.respawn(runtime, launch, { current })
+ const spawned = await deps.respawn(runtime, launch, { current: dispatchCurrent, onDispatch: () => {
+ if (launch.nativeToken) {
+ const committed = deps.registry.setLaunch(agentId, { state: 'starting', nativeToken: launch.nativeToken })
+ if (!committed) throw new Error('Native fallback dispatch could not be committed')
+ current = restoreOwner(deps, committed)
+ owns = restoreOwner(deps, committed, !!deps.paneOperation)
+ }
+ } })
if (!owns()) return false
if (!spawned.ok) {
fail('ENGINE_DID_NOT_START', `${engine} could not be relaunched fresh: ${spawned.reason ?? 'unknown reason'}`)
@@ -784,6 +831,13 @@ async function watchRestoredPane(
fail('ENGINE_DID_NOT_START', `${engine}'s restored pane disappeared before its engine process became ready.`)
return
}
+ const row = deps.registry.byAgent(agentId)
+ const nativeToken = row?.launch?.state === 'starting' ? row.launch.nativeToken : undefined
+ if (nativeToken && await deps.waitingPane?.(runtime, nativeToken) === true) {
+ if (current()) deps.registry.setLaunch(agentId, { state: 'held', service: 'native', nativeToken,
+ detail: 'The engine did not start because its executable or native hooks changed. The original launch is held for recovery.' })
+ return
+ }
// A pane tmux could not read is asked again, like one still starting.
if (engineGone(state)) {
if (!await relaunchFresh()) return
@@ -793,6 +847,16 @@ async function watchRestoredPane(
await sleep(delayMs)
delayMs = Math.min(delayMs * 2, 750)
}
+ if (!current()) return
+ const latest = deps.registry.byAgent(agentId)
+ const nativeToken = latest?.launch?.state === 'starting' ? latest.launch.nativeToken : undefined
+ if (nativeToken) {
+ // A core crash can lose the new-pane watcher while the guard's tmux
+ // publication is unavailable. No process observation is proof of failure.
+ deps.registry.setLaunch(agentId, { state: 'held', service: 'native', nativeToken,
+ detail: 'Waiting to confirm the native engine process. The original launch and terminal are preserved.' })
+ return
+ }
fail('START_TIMEOUT', `${engine} did not expose an engine process within ${Math.round(budgetMs / 60_000)} minutes. The terminal remains available.`)
} catch (error) {
deps.log(`[restore] ${engine} · agent ${agentId} · watch failed · ${error instanceof Error ? error.message : error}`)
diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.ts
index f6eada8e5..e761b2f6b 100644
--- a/cli/src/lib/resumeAgentService.spec.ts
+++ b/cli/src/lib/resumeAgentService.spec.ts
@@ -18,6 +18,7 @@ import { enginePathOverride } from './engineBin.js'
import { installedDsh } from '../dsh/installed.js'
import { createLaunchHelpers } from '../core/agents/launch.js'
import { createLaunchAuthority } from '../core/agents/launchAuthority.js'
+import type { NativeLaunch } from '../engines/nativeLaunch.js'
vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn() }))
vi.mock('./tmuxAgentDiscovery.js', () => ({ listTmuxPanes: vi.fn() }))
@@ -131,6 +132,63 @@ describe('production resume handler', () => {
expect(registry.byAgent(saved.agentId)?.permissionMode).toBe(permissionMode)
})
+ it('carries the captured native launch and token through permission, argv and registration', async () => {
+ const native: NativeLaunch = { token: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee', opencodeMajor: null,
+ environment: {}, proofs: [], current: vi.fn(() => true),
+ prepareHooks: vi.fn(async () => true), permission: vi.fn(async () => 'supported' as const) }
+ vi.mocked(deps.relaunchOverrides).mockResolvedValue({ ok: true,
+ overrides: { env: {}, extraArgs: [], clearEnv: [], native } })
+ const starting = vi.fn()
+ vi.mocked(deps.announceSession).mockImplementation(row => {
+ if (row.launch?.state === 'starting') starting(row.launch.nativeToken)
+ })
+ create.mockImplementationOnce(async request => {
+ expect(request.current()).toBe(true)
+ return { state: 'succeeded', runtime: { backend: 'tmux', paneId: pane } }
+ })
+ expect(await start()).toMatchObject({ ok: true, resumed: true })
+ expect(dropPermissionFlagIfUnsupported).toHaveBeenCalledWith('codex', expect.any(Object), undefined, native)
+ expect(buildEngineLaunchArgv).toHaveBeenCalledWith('codex', expect.objectContaining({ native }))
+ expect(starting).toHaveBeenCalledExactlyOnceWith(native.token)
+ })
+
+ it.each(['permission', 'expired'] as const)('holds a saved resume when native %s evidence is unavailable', async reason => {
+ const native: NativeLaunch = { opencodeMajor: null, environment: {}, proofs: [], current: () => reason !== 'expired',
+ prepareHooks: async () => true, permission: async () => 'supported' }
+ vi.mocked(deps.relaunchOverrides).mockResolvedValue({ ok: true,
+ overrides: { env: {}, extraArgs: [], clearEnv: [], native } })
+ if (reason === 'permission') vi.mocked(dropPermissionFlagIfUnsupported).mockImplementationOnce(async (_engine, choice) => ({
+ choice, droppedFlag: null, nativeHold: 'Waiting for the captured executable permission probe.',
+ }))
+ expect(await start()).toEqual({ ok: false, error: 'NATIVE_LAUNCH_HELD', detail: reason === 'permission'
+ ? 'Waiting for the captured executable permission probe.' : 'Waiting for fresh executable and hook evidence.' })
+ expect(create).not.toHaveBeenCalled()
+ expect(buildEngineLaunchArgv).not.toHaveBeenCalled()
+ expect(registry.byAgent(saved.agentId)).toBeUndefined()
+ expect(deps.stoppedAgents.resumeReservedAt(saved.agentId)).toBeNull()
+ expect(deps.stoppedAgents.get(saved.agentId)).toMatchObject({ sessionId: saved.sessionId, transcriptPath: saved.transcriptPath })
+ })
+
+ it.each(['native', 'cancel'] as const)('rechecks %s authority at terminal dispatch and releases an unstarted reservation', async reason => {
+ let valid = true
+ const native: NativeLaunch = { opencodeMajor: null, environment: {}, proofs: [], current: () => valid,
+ prepareHooks: async () => true, permission: async () => 'supported' }
+ vi.mocked(deps.relaunchOverrides).mockResolvedValue({ ok: true,
+ overrides: { env: {}, extraArgs: [], clearEnv: [], native } })
+ create.mockImplementationOnce(async request => {
+ expect(request.current()).toBe(true)
+ if (reason === 'native') valid = false
+ else deps.restartJobs.cancel(saved.agentId)
+ expect(request.current()).toBe(false)
+ return { state: 'failed', reason: 'launch authority changed', dispatch: 'not_started' }
+ })
+ expect(await start()).toMatchObject({ ok: false, error: reason === 'native' ? 'RESUME_UNCONFIRMED' : 'AGENT_CHANGED' })
+ expect(kill).not.toHaveBeenCalled()
+ expect(registry.byAgent(saved.agentId)).toBeUndefined()
+ expect(deps.stoppedAgents.resumeReservedAt(saved.agentId)).toBeNull()
+ expect(deps.stoppedAgents.get(saved.agentId)?.sessionId).toBe(saved.sessionId)
+ })
+
it('notes where the relaunched engine\'s writing begins, after the history is prepared and before the launch', async () => {
writeFileSync(saved.transcriptPath!, '{"type":"session_meta"}\n')
const note = vi.fn((_sessionId: string, _offset: number, _engineStarted?: boolean) => {
diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.ts
index 0c0323449..d5df913b3 100644
--- a/cli/src/lib/resumeAgentService.ts
+++ b/cli/src/lib/resumeAgentService.ts
@@ -184,9 +184,6 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
if (permissionMode !== undefined) {
if (!permissionModeFlags(saved.engine, permissionMode)) return { ok: false, error: 'INVALID_PERMISSION_MODE' }
const choice = { permissionMode, bypassPermission: permissionModeApproves(permissionMode) }
- const refusal = await refusePermissionFlagIfUnsupported(saved.engine, choice)
- if (refusal) return { ok: false, ...refusal }
- if (!current()) return resumeChanged
saved = { ...saved, ...choice }
}
if (saved.grid && !saved.gridLaunch) return { ok: false, error: 'GRID_CREDENTIAL_REQUIRED', detail: 'The saved provider configuration is unavailable.' }
@@ -230,8 +227,14 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
const built = await relaunchOverrides(saved, saved, sourceCurrent)
if (sourceError) throw sourceError
transcript?.verify()
- if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
+ if (!built.ok) return built
if (!current()) return resumeChanged
+ if (permissionMode !== undefined) {
+ const refusal = await refusePermissionFlagIfUnsupported(saved.engine,
+ { permissionMode, bypassPermission: permissionModeApproves(permissionMode) }, undefined, built.overrides.native)
+ if (!sourceCurrent()) return resumeChanged
+ if (refusal) return { ok: false, ...refusal }
+ }
if (resumeSessionId) {
try { prepareSessionResume(saved) } catch (error) {
if (error instanceof IdentityReadUnavailable) throw error
@@ -259,16 +262,18 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
permissionMode: saved.permissionMode ?? null,
bypassPermission: saved.bypassPermission === true,
}
- const { choice: permission, droppedFlag } = permissionMode === undefined
- ? await dropPermissionFlagIfUnsupported(saved.engine, savedPermission)
+ const { choice: permission, droppedFlag, nativeHold } = permissionMode === undefined
+ ? await dropPermissionFlagIfUnsupported(saved.engine, savedPermission, undefined, built.overrides.native)
: { choice: savedPermission, droppedFlag: null }
transcript?.verify()
if (!current()) return resumeChanged
+ if (nativeHold || built.overrides.native?.current() === false) return { ok: false, error: 'NATIVE_LAUNCH_HELD', detail: nativeHold ?? 'Waiting for fresh executable and hook evidence.' }
if (droppedFlag) {
console.warn(`[resume] ${sid(saved.agentId)} · ${saved.engine} does not take ${droppedFlag}`
+ ` · resuming in Ask · update ${saved.engine} to get ${saved.permissionMode ?? 'Auto'} back`)
}
const options = {
+ ...(built.overrides.native ? { native: built.overrides.native } : {}),
resumeSessionId,
bypassPermission: permission.bypassPermission === true,
...(permission.permissionMode ? { permissionMode: permission.permissionMode } : {}),
@@ -286,14 +291,15 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
// Only actual dispatch can leave an unknown allocation. A held backend
// gate releases the reservation so recovery may retry without spawning twice.
const result = await createAndRegisterPane({
- current: sourceCurrent,
+ current: () => sourceCurrent() && built.overrides.native?.current() !== false,
+ ...(built.overrides.native ? { nativeToken: built.overrides.native.token } : {}),
onDispatch: () => { allocationAttempted = true },
tmuxBackend: { ...tmuxBackend, create: async request => {
const result = await tmuxBackend.create(request)
if (result.dispatch !== 'not_started') allocationAttempted = true
return result
}, kill: runtime => tmuxBackend.kill(runtime) },
- registry: { openPendingAgent: input => sourceCurrent() ? registry.resumePendingAgent(saved, input.runtimes) : null },
+ registry: { openPendingAgent: input => sourceCurrent() ? registry.resumePendingAgent(saved, input.runtimes, input.nativeToken) : null },
maxAttempts: 1,
engine: saved.engine,
sessionLabel: buildHarnessSessionLabel(saved.engine),
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 505f378f6..484b14480 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -1,5 +1,6 @@
import { execFile } from 'node:child_process'
import { shellSingleQuote } from './shellQuote.js'
+import { heldPaneFormat } from './nativePaneHold.js'
import { patientExec } from './patientExec.js'
import type { TerminalBackend } from './terminalBackend.js'
import {
@@ -262,7 +263,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
const commands = [...setup, args]
if (request.expectedHeldToken && !/^[a-f0-9-]{36}$/.test(request.expectedHeldToken)) return terminalActionNotStarted('invalid waiting pane identity')
const command = request.expectedHeldToken
- ? ['if-shell', '-F', '-t', runtime.paneId, `#{&&:#{m:*harness-held*,#{pane_start_command}},#{m:*${request.expectedHeldToken}*,#{pane_start_command}}}`,
+ ? ['if-shell', '-F', '-t', runtime.paneId, heldPaneFormat(request.expectedHeldToken),
commands.map(parts => parts.map(shellSingleQuote).join(' ')).join('; '), 'display-message -p adoption-mismatch']
: commands.flatMap((parts, index) => index ? [';', ...parts] : parts)
const result = await new Promise<{ error: NodeJS.ErrnoException | null; stderr: string }>((resolve) => {
@@ -286,7 +287,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
async isHeld(runtime: TmuxRuntimeRef, token: string): Promise<boolean | 'unknown'> {
if (!/^%\d+$/.test(runtime.paneId) || !/^[a-f0-9-]{36}$/.test(token)) return 'unknown'
return new Promise(resolve => run('tmux', ['display-message', '-p', '-t', runtime.paneId,
- `#{&&:#{m:*harness-held*,#{pane_start_command}},#{m:*${token}*,#{pane_start_command}}}`], { timeout: 2_000 }, (error, stdout) => {
+ heldPaneFormat(token)], { timeout: 2_000 }, (error, stdout) => {
if (error) { resolve(isNoTmuxServerError(error.message) || /can't find pane: %\d+/.test(error.message) ? false : 'unknown'); return }
resolve(stdout.trim() === '1' ? true : stdout.trim() === '0' ? false : 'unknown')
}))
@@ -298,7 +299,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
const result = await inTmuxRoom('notify', () => new Promise<{ error: Error | null; stdout: string }>(resolve => {
if (!current()) { resolve({ error: new Error('Adoption changed before pane close'), stdout: '' }); return }
// Evaluated inside the tmux server, in the same command that kills: no check/use gap for %N.
- run('tmux', ['if-shell', '-F', '-t', runtime.paneId, `#{&&:#{m:*harness-held*,#{pane_start_command}},#{m:*${token}*,#{pane_start_command}}}`,
+ run('tmux', ['if-shell', '-F', '-t', runtime.paneId, heldPaneFormat(token),
`kill-pane -t ${runtime.paneId}`, 'display-message -p adoption-mismatch'], { timeout: 5_000 },
(error, stdout) => resolve({ error, stdout }))
}))
diff --git a/docs/research/2026-10-11-native-install-cost.mts b/docs/research/2026-10-11-native-install-cost.mts
new file mode 100644
index 000000000..4e5167a05
--- /dev/null
+++ b/docs/research/2026-10-11-native-install-cost.mts
@@ -0,0 +1,54 @@
+/** Private immutable installer histories; no engine, package manager, daemon or tmux. */
+import { createHash } from 'node:crypto'
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import childProcess from 'node:child_process'
+import { syncBuiltinESMExports } from 'node:module'
+
+const root = realpathSync(mkdtempSync(join(tmpdir(), 'native-install-cost-')))
+Object.defineProperty(process, 'platform', { value: 'linux' })
+Object.assign(childProcess, Object.fromEntries(['exec', 'execSync', 'execFile', 'execFileSync', 'spawn', 'spawnSync', 'fork']
+ .map(key => [key, () => { throw Error('A host subprocess is forbidden in this measurement') }])))
+syncBuiltinESMExports()
+for (const key of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'TMUX_TMPDIR', 'ZDOTDIR']) {
+ process.env[key] = join(root, key); mkdirSync(process.env[key]!, { mode: 0o700 })
+}
+process.env.SHELL = '/bin/sh'; process.env.PATH = '/fixture/bin'; process.env.TZ = 'UTC'
+process.env.HARNESS_CONNECTIONS_PORT = '0'
+delete process.env.TMUX; delete process.env.TMUX_PANE
+const hash = (text: string) => createHash('sha256').update(text).digest('hex')
+const cli = process.env.NATIVE_INSTALL_COST_CLI ?? resolve('cli')
+const { createNativeInstallations } = await import(pathToFileURL(join(cli, 'src/engines/kit/nativeInstall.ts')).href)
+try {
+ for (const count of [1, 32, 128, 1000]) {
+ const directory = join(root, `history-${count}`), environment = { HOME: process.env.HOME!, PATH: '/fixture/bin', SHELL: '/bin/sh' }
+ const recipe = { command: 'private-fixture-install', source: 'fixture', executable: { names: ['private-fixture-engine'] } }
+ let dispatches = 0
+ const controller = createNativeInstallations({ directory, node: () => '/fixture/node', dispatch: () => { dispatches++ } })
+ await controller.ensure('opencode', recipe, environment, 'seed', () => true)
+ const seed = JSON.parse(readFileSync(join(directory, '00000000.json'), 'utf8'))
+ let previous: { file: string; digest: string }[] = []
+ for (let index = 0; index < count; index++) {
+ const prefix = String(index).padStart(8, '0'), file = join(directory, `${prefix}.json`), witness = `${directory}.${prefix}.dispatch`
+ const claim = { ...seed, request: index === 0 ? 'measured-request' : `fixture-${index}`, token: `fixture-token-${index}`, previous, witness }
+ const bytes = JSON.stringify(claim), digest = hash(bytes)
+ const marker = JSON.stringify({ token: claim.token, claim: digest, kind: 'run' })
+ const result = JSON.stringify({ token: claim.token, claim: digest, code: 0, signal: null })
+ for (const [path, value] of [[file, bytes], [witness, marker], [`${file}.dispatch`, marker], [`${file}.result`, result]]) {
+ writeFileSync(path, value, { mode: 0o600 })
+ }
+ previous = [{ file, digest }, { file: `${file}.result`, digest: hash(result) }]
+ }
+ dispatches = 0
+ let last = performance.now(), maxCallbackMs = 0
+ const timer = setInterval(() => { const now = performance.now(); maxCallbackMs = Math.max(maxCallbackMs, now - last); last = now }, 1)
+ const cpu = process.cpuUsage(), start = performance.now()
+ const result = await controller.ensure('opencode', recipe, environment, 'measured-request', () => true)
+ const wallMs = performance.now() - start, used = process.cpuUsage(cpu)
+ await new Promise(done => setTimeout(done, 2)); clearInterval(timer)
+ process.stdout.write(JSON.stringify({ count, result, dispatches, wallMs, cpuMs: (used.user + used.system) / 1000,
+ maxCallbackMs, rssMiB: process.memoryUsage().rss / 1048576 }) + '\n')
+ }
+} finally { rmSync(root, { recursive: true, force: true }) }
diff --git a/docs/research/2026-10-11-native-launch-cost.json b/docs/research/2026-10-11-native-launch-cost.json
new file mode 100644
index 000000000..741f893bb
--- /dev/null
+++ b/docs/research/2026-10-11-native-launch-cost.json
@@ -0,0 +1,100 @@
+{
+ "schema": 1,
+ "baseline": "16569f3d27e1b51352904aded33e71971b7e2724",
+ "candidate": "3be7d7ca014b3246c85b45c338c73d9640c90978 plus final resume/assertion correction",
+ "receipt": "20261011T060343.168480Z-33631",
+ "nativeHooks": true,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "tmux": "tmux 3.5a",
+ "samples": [
+ {
+ "bundle": "baseline",
+ "readyMs": 2903.850002,
+ "atReady": {
+ "cpuMs": 540,
+ "rssMiB": 86.640625
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 214.4027799999999,
+ "coreCpuMs": 60,
+ "rssMiB": 87.48046875
+ },
+ {
+ "phase": "warm",
+ "requestMs": 112.28748200000018,
+ "coreCpuMs": 30,
+ "rssMiB": 88.671875
+ }
+ ]
+ },
+ {
+ "bundle": "candidate",
+ "readyMs": 3217.6684000000005,
+ "atReady": {
+ "cpuMs": 510,
+ "rssMiB": 84.796875
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 340.0986549999998,
+ "coreCpuMs": 80,
+ "rssMiB": 86.59765625
+ },
+ {
+ "phase": "warm",
+ "requestMs": 363.8914049999994,
+ "coreCpuMs": 60,
+ "rssMiB": 89.08203125
+ }
+ ]
+ },
+ {
+ "bundle": "candidate",
+ "readyMs": 2676.0425509999995,
+ "atReady": {
+ "cpuMs": 530,
+ "rssMiB": 87.66796875
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 357.45592600000055,
+ "coreCpuMs": 80,
+ "rssMiB": 89.3359375
+ },
+ {
+ "phase": "warm",
+ "requestMs": 306.4411990000008,
+ "coreCpuMs": 60,
+ "rssMiB": 91.25
+ }
+ ]
+ },
+ {
+ "bundle": "baseline",
+ "readyMs": 2482.4306109999998,
+ "atReady": {
+ "cpuMs": 530,
+ "rssMiB": 86.75
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 212.46589400000084,
+ "coreCpuMs": 60,
+ "rssMiB": 87.62890625
+ },
+ {
+ "phase": "warm",
+ "requestMs": 132.80414699999892,
+ "coreCpuMs": 30,
+ "rssMiB": 88.15625
+ }
+ ]
+ }
+ ]
+}
diff --git a/docs/research/2026-10-11-native-launch-preparation.md b/docs/research/2026-10-11-native-launch-preparation.md
index d7ae7e4cf..b2b672e12 100644
--- a/docs/research/2026-10-11-native-launch-preparation.md
+++ b/docs/research/2026-10-11-native-launch-preparation.md
@@ -1,6 +1,7 @@
# Native launch preparation
-Status: hook durability mechanics are in final validation. They are part of
+Status: hook durability mechanics landed as #1158 (`eef21b18b`, October 11
+at 01:30 UTC). Whole-launch integration is in reviewed PR #1160, awaiting final-head CI and merge. They are part of
group 2 of the [daemon core checklist](2026-10-09-daemon-core-completion.md).
The whole-launch integration below remains in progress in a separate worktree;
neither group 2 nor the daemon refactor is complete. No release is authorized.
@@ -84,6 +85,83 @@ during those waits; callback gaps measure that distinction, not actual Stop late
Whole-launch cost, readiness, and unrelated Stop latency still require integration
measurement. There is no cross-request configuration or durability cache.
+## Whole-launch integration checkpoint, October 11
+
+The former native argv and healthy installer behavior was recorded from main
+`eef21b18b` in golden-only commit `6d61d7678`. Generated Pi, OpenCode and Grok
+configuration was separately recorded in `23ba641c2`. Both artifacts remain
+unchanged. Their runners now exercise the new native snapshot, installer-only
+helper and immutable configuration publisher. Fixtures pin Linux and UTC and
+normalize private paths and executable locations.
+
+Draft #1160 retains one executable and the launch shell's native locations,
+checks bounded version/permission observations, prepares hooks before execution,
+and checks the retained evidence again after the pane's startup files. Missing
+engines run a separately journalled installer with no conversation arguments or
+first message. Seeing its new binary does not prove that installation finished.
+Durable uncertainty and failed installation hold later requests too.
+
+Generated configuration has immutable manifests, directory ownership and
+completion records. Borrowed native directories retain their original physical
+identity. A retry cannot replace edited files, recreate a removed conversation
+directory or adopt a replacement at the same path. Changed configurations use
+new directories, preserving those a live engine still reads. None are age-pruned.
+
+Plain create requests with a stable ID now keep their original input, local
+authorization and runtime label before dependency preparation. A bounded core
+retry reads the saved request afresh and publishes a visible hold reason;
+installation, models and Store preparation precede the final dispatch claim.
+Project creation, external creation, fork/restart/resume/retarget intent and
+durable Stop/Close revocation still need their complete lifecycle integration.
+This checkpoint does not complete checklist groups 2 or 3.
+
+Create, fork, restart, restore, retarget and external takeover now carry the
+captured executable through native permission checks, final hook preparation and
+dispatch. Fork preparation retains the original source authority while its native
+snapshot is being prepared. Create and fork persist the final harness-selected
+Codex home. External takeover rechecks the native proof before signalling an
+external process and before admission.
+
+Independent review corrected failed-installer bypass, borrowed-session directory
+recreation, cancelled installer recovery, final-home persistence and stale takeover
+proofs. Integration with Agent Messages also exposed required-hook proof replacement,
+foreign hook deletion, and approval of only the first managed block in an event.
+The combined publication now retains the required proof across reservations,
+preserves foreign commands and siblings, and approves every exact managed hook.
+Each correction has a regression. Exact-head landing review is still required.
+
+The new private daemon regression retains two native-held requests through a core
+crash, cancels one durably, preserves malformed hook settings, and dispatches the
+other exactly once with its saved prompt after repair. Focused core coverage and
+hook review checks pass. Broader coverage, wiring mutations, all affected private
+lanes and matched whole-launch cost remain landing gates. A Claude e2e hold under
+concurrent filesystem-heavy validation is being diagnosed; the isolated case
+passes without source changes. It is not recorded as an uninterrupted green run.
+
+The integration slice began October 11 at 01:31 UTC. At this checkpoint it
+contains implementation and local validation only. Draft CI and independent
+review overlapped implementation; no integration merge or publication occurred.
+
+## Review correction: the final native dispatch boundary
+
+Local workspace trust now precedes the retained native-hook proof. It uses the
+saved local authorization, captured home and a fresh bounded directory proof;
+workspace replacement, edits or incomplete enumeration cannot grant trust.
+Delayed pane observations retain the original route, token and conversation.
+Retarget and restore also retain their nested preparation proof through the
+actual pane mutation. OpenCode native API calls preserve the selected executable,
+absent location variables and the exact environment of an uncertain receipt.
+
+A native guard that rejects changed post-startup files must publish its inert
+state: tmux does not update `pane_start_command` when a shell calls `exec`.
+The transition checks the original pane, shell PID and launch nonce together
+inside the server before respawn. Its client has a deadline; fallback stays
+inert, and an unconfirmed process remains visibly held. The held command retains
+the daemon ownership prefix required on older tmux versions. Inline launch text
+cannot be mistaken for an already-held command. A core restart preserves an
+unbound held create/fork; it cannot silently substitute a fresh generic launch.
+Recovery of the exact original lifecycle request remains checklist group 3.
+
## Remaining launch integration
Every create/fork/restart/retarget/restore/external-resume path must use a confirmed
@@ -105,7 +183,18 @@ PR does not enable the draft whole-launch integration.
This slice began October 10 at 22:49 UTC. The checkpoint above was reached about
an hour later, including implementation, focused validation and design review.
Implementation and validation overlapped; receipt durations describe individual
-checks, not total delivery time. Merge and publication are both zero for this slice.
+checks, not total delivery time. The mechanics merge completed October 11 at
+01:30 UTC. Publication remains zero.
+
+Mechanics landing evidence: `20261011T012341.232142Z-93608` passed typecheck,
+architecture, 201 focused tests, all 2,393 core tests at 100% statements and
+branches, harnessd at 100%, and 441 unchanged hook golden cases.
+`20261011T011534.448579Z-59253` passed 359 affected tests with five explicitly
+environment-gated skips. `20261011T011530.711952Z-59124` killed all twelve wiring
+mutants by assertions. `20261011T012715.881253Z-11668` passed four eager-hook,
+three home-recovery and the original Codex tmux-crash-resume private e2e cases.
+Independent review covered head `05d4fba22` against base `93d49e9c8`; automatic
+CI and `ci/required` passed before the authorized merge. No CLI was released.
## Independent review corrections
@@ -198,3 +287,110 @@ both. The no-OpenCode golden assertion also returns to its unchanged former
artifact alongside the deferred policy. No golden fixture bytes were rerecorded.
All twelve deliberate mutations failed assertions in receipt
`20261011T011530.711952Z-59124`; final core/golden gates and private e2e remain.
+
+## Whole-launch integration acceptance, October 11
+
+The installer mechanics landed as #1158. The subsequent integration retains one
+executable and location snapshot through launch, persists plain creation intent,
+publishes immutable grid configuration and fences the final pane command. Its
+native argv and grid artifacts were recorded before implementation in commits
+`6d61d7678` and `23ba641c2`; their bytes remain unchanged.
+
+The first complete end-to-end run of #1160 (`38114019652`, head `aeea2b5a7`)
+failed. It identified these integration corrections:
+
+- A valid parent alias on macOS must not look like an unreadable installation
+ history. Absence is checked at the resolved parent while retaining and
+ reverifying the original route. A dangling leaf still holds.
+- Isolated daemons running with `NODE_ENV=test` must capture the same launch shell
+ as production. Bypassing it selected the wrong moved home and provider.
+- A saved model request reports the models dependency before asking it, including
+ when its port rejects. It retains the original request through core restart.
+- Only the original implicit shell session home may enter the global adoption
+ catalog. Explicit or generated profiles remain session-scoped, including across
+ repeated preparation. A separate Claude transcript root does not make its
+ settings directory another conversation store. Store's existing byte-preservation
+ assertion remains unchanged.
+- Required notify hooks, optional Messages hooks and approvals share one bounded
+ reservation. Identical startup/launch callers join the whole operation and each
+ retain their own revocation check. A partial optional write cannot grant success.
+- Missing-engine tests now require a saved, visibly held creation with no new
+ agent, followed by one launch of that same ID after repair. Restart preserves
+ the running conversation until its executable is available.
+
+Receipt `20261011T053720.461991Z-79891` passed moved-home crash/resume recovery,
+model-request recovery, Store preservation, missing-engine recovery and the
+four-agent 160-turn soak. The receipt was not green: the update cases exposed an
+unnecessary Claude adoption and an obsolete restart error expectation.
+Their corrections passed typecheck, 231 focused tests including the unchanged
+hook golden, and both engine reinstall/restart cases in receipt
+`20261011T054232.269856Z-30462`.
+
+Independent review agreed with the immutable-home provenance and single
+reservation design. The frozen corrected head still needs its exact-head review,
+final coverage, mutation checks, matched runtime cost and complete CI/end-to-end
+acceptance before landing. Startup maintenance still awaiting hooks is a separate
+recorded readiness move, not completed by this integration.
+
+## Final whole-launch validation, October 11 at 06:04 UTC
+
+The corrected implementation passed automatic Linux CI, including `ci/required`,
+in [run 38115806295](https://github.com/autonomous-ai/openharness/actions/runs/38115806295).
+The full [CLI end-to-end run 38115845461](https://github.com/autonomous-ai/openharness/actions/runs/38115845461)
+passed all eight Linux shards: 103 files exactly once, 579 cases passed and 20
+explicit platform/opt-in skips. The separate macOS full-disk lane also passed.
+This covers the original Codex tmux-crash resume, moved homes, stopped and live
+conversations, missing engines, Store/model outages, upgrades and the default
+160-turn soak. It does not substitute for the remaining lifecycle checklist.
+
+Local receipts:
+
+- `20261011T054548.491553Z-46263`: types, architecture/startup (30 cases), all
+ 2,501 core/services cases at 100% per-file coverage, and harnessd (265 passed,
+ one platform skip) at 100% passed.
+- `20261011T055529.833588Z-92843`: types and 382 resume cases at 100% statements,
+ branches, functions and lines passed. Five added cases exercise retained native
+ identity/token, unavailable permission evidence, expired proof, and cancellation
+ at dispatch. A redundant synchronous guard left by the moved async permission
+ probe was removed; authority remains checked after actual preparation and at
+ dispatch. The initial 377-case run passed its tests but failed coverage; it is
+ not passing gate evidence.
+- `20261011T060018.809604Z-17701`: unchanged baselines passed and all 28 broken
+ native-launch wirings failed assertions. The preceding run caught 27 by
+ assertion; the missing-Messages case instead threw a TypeError. Its lookup now
+ lets the assertion report the absent hook. The runner was not weakened.
+- `20261011T060343.168480Z-33631`: the matching candidate bundle and complete
+ startup/launch cost workload passed alone, with private homes, ports, tmux and
+ fake native engines. The baseline bundle is main `16569f3d2`; candidate is
+ `3be7d7ca0` plus the final resume/assertion correction above.
+
+The independent reviewer approved `3be7d7ca0` against `16569f3d2` and separately
+approved the three-file final correction. That correction does not change the
+end-to-end behavior exercised above. Final committed-head attestation and its
+automatic CI are still required before merging.
+
+The four alternating cost samples (baseline, candidate, candidate, baseline)
+include all thirteen startup hook installers under Node 22.23.2 and tmux 3.5a
+on macOS. [Raw measurements](2026-10-11-native-launch-cost.json) retain each sample.
+Two observations per tree are descriptive measurements, not new performance gates.
+
+| Median measurement | Main | Whole-launch integration |
+| --- | ---: | ---: |
+| Readiness | 2,693 ms | 2,947 ms |
+| Core CPU at readiness | 535 ms | 520 ms |
+| Core RSS at readiness | 86.7 MiB | 86.2 MiB |
+| Cold launch request | 213 ms | 349 ms |
+| Warm launch request | 123 ms | 335 ms |
+| Core CPU per cold/warm launch | 60 / 30 ms | 80 / 60 ms |
+| Core RSS after warm launch | 88.4 MiB | 90.2 MiB |
+
+Fresh launch-shell capture and durable per-launch confirmation add work on every
+launch, including warm launches; these results do not claim a speedup. Startup
+still awaited global maintenance in both measured trees. Moving that maintenance
+after readiness is the separately reviewed next slice.
+
+Implementation ran from 01:31 through the final correction at 06:00 UTC, interleaved
+with review and validation. The final validation receipts above occupy
+05:45–06:04; the full remote run overlaps that interval. They are not added together
+as total elapsed time. Merge and publication remain zero at this checkpoint. No
+release is authorized.