The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Keep native version probes from blocking session control (#1149)
Deef0875b08a75e
diff --git a/cli/e2e/eagerHooks.e2e.ts b/cli/e2e/eagerHooks.e2e.tsindex 9ea158eac..c3fa06e6f 100644--- a/cli/e2e/eagerHooks.e2e.ts+++ b/cli/e2e/eagerHooks.e2e.ts@@ -1,6 +1,6 @@/** Startup and pre-spawn hook preparation cannot wait for the obsolete shared optional installer. */import { execFileSync } from 'node:child_process'-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { dirname, join } from 'node:path'import { afterAll, afterEach, beforeAll, expect, it, onTestFailed } from 'vitest'@@ -32,6 +32,53 @@ it('refuses a native hook destination outside the test, including the OpenCode sexpect(() => assertHooksContained(d.root, d.env)).toThrow('supported hook engines')})+it('keeps Stop and agent listing responsive while a native launch version probe waits', async () => {+ const d = daemon = await IsolatedDaemon.create({ scriptPath: bundle, env: { HARNESS_CONNECTIONS_PORT: '0' } })+ onTestFailed(() => console.log(d.log()))+ const binary = join(d.root, 'bin', 'opencode'), entered = join(d.root, 'version-entered'), release = join(d.root, 'version-release')+ d.env.OPENCODE_PATH = binary+ d.env.OPENCODE_PLUGIN_DIR = join(d.root, 'opencode', 'plugin')+ writeFileSync(binary, `#!${process.execPath}\nconsole.log('opencode v2.0.18')\n`, { mode: 0o755 })+ await d.start()+ const c = client = await LocalClient.connect(d)+ const cwd = join(d.projectsDir, 'responsive'); mkdirSync(cwd)+ const created = await c.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 30_000)+ expect(created.error, JSON.stringify(created)).toBeUndefined()+ const id = created.agent.id+ await until('the sibling to bind', async () => {+ const list = await c.request('agents_list', { includeStopped: true })+ return list.agents.find((row: any) => row.id === id && row.status === 'active' && row.sessionId)+ }, 30_000)+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === id, 30_000)+ c.send('message', { agentId: id, content: 'native probe responsiveness fixture' }); await ended+ // Replace the fixture after startup so no earlier observation can satisfy this+ // launch. Only this test releases the child; it cannot acknowledge prematurely.+ writeFileSync(binary, `#!${process.execPath}+const fs = require('node:fs');+if (!process.argv.includes('--version')) process.exit(2);+fs.writeFileSync(${JSON.stringify(entered)}, '');+const timer = setInterval(() => { if (fs.existsSync(${JSON.stringify(release)})) { clearInterval(timer); console.log('opencode v2.0.18'); } }, 10);+`, { mode: 0o755 })+ // A connection intentionally handles its requests in order. Use another+ // private connection so this tests the core, not that connection's queue.+ const probeClient = await LocalClient.connect(d)+ let settled = false+ const launch = probeClient.request('agent_create', { engine: 'opencode', cwd, agent: 'fixture' }, 15_000)+ .finally(() => { settled = true })+ try {+ await until('the native version probe to start', () => existsSync(entered), 5_000, 10)+ expect((await c.request('agents_list', { includeStopped: true }, 1_500)).agents.some((row: any) => row.id === id)).toBe(true)+ expect((await c.request('agent_delete', { agentId: id }, 3_000)).error).toBeUndefined()+ expect(settled).toBe(false)+ expect(d.coresStarted()).toBe(1)+ } finally {+ writeFileSync(release, '')+ await launch.catch(() => {})+ probeClient.close()+ }+ expect((await launch).error).toBe('AGENT_UNSUPPORTED')+}, 90_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/scripts/handoff-2026-10-08/mutate-native-version.py b/cli/scripts/handoff-2026-10-08/mutate-native-version.pynew file mode 100644index 000000000..3f844f6a1--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/mutate-native-version.py@@ -0,0 +1,64 @@+"""Owned disposable worktree only: broken native-version wiring must fail assertions."""+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_VERSION_MUTATIONS_OWNED') == '1'+golden = 'src/engines/nativeVersion.golden.spec.ts'+probe = 'src/engines/kit/nativeVersion.spec.ts'+native = 'src/engines/kit/nativeVersion.ts'+hooks = 'src/lib/discoveryScripts.spec.ts'+create = 'src/core/agents/create.spec.ts'+mutations = [+ ('version protocol', 'src/engines/opencode/contract.ts', "args: ['--version']", "args: ['--help']", golden, ''),+ ('version parser', 'src/engines/opencode/contract.ts', r'/(\d+)\.\d+\.\d+/', r'/major=(\d+)/', golden, ''),+ ('core installer disconnected', 'src/core/engines/hooks.ts', 'return await nativeHooks.installOpencodePlugin(port) !== false', 'return true', golden, ''),+ ('production resolver blocks', 'src/engines/launchControl.ts', 'await opencodeBinAsync()', 'opencodeBin()', probe, 'production resolver'),+ ('execution selects another command', native, 'execFile(file, [...rule.args]', 'execFile(binary(), [...rule.args]', probe, 'selected for this probe once'),+ ('replacement fence removed', native, 'const current = identity === probe.identity()', 'const current = true', probe, 'executable is replaced'),+ ('output bound removed', native, 'maxBuffer: 64 * 1024', 'maxBuffer: 256 * 1024', probe, 'output flood'),+ ('stdin never closes', native, 'child.stdin?.end()', "child.stdin?.write('')", probe, 'read to EOF'),+ ('memo publication ownership lost', native, 'if (attempts.get(identity) !== ticket)', 'if (false)', probe, 'older failed probe'),+ ('confirmed observation becomes unavailable', native, 'return current ? major : null', 'return current ? memo.get(identity) ?? null : null', probe, 'newer probe of the unchanged file'),+ ('obsolete installation writes', 'src/engines/nativeHooks.ts', 'if (installation !== opencodeInstallation) return false', 'void installation', hooks, 'obsolete version probe'),+ ('healthy overlapping create refused', 'src/engines/nativeHooks.ts', 'while (current !== opencodeInstallation) {', 'while (current !== opencodeInstallation) { return false;', create, 'concurrent healthy OpenCode'),+]+environment = dict(os.environ, TZ='UTC', TMPDIR='/tmp', HARNESS_CONNECTIONS_PORT='0')+for key in ('TMUX', 'TMUX_PANE', 'RECORD_NATIVE_VERSION_GOLDEN', 'RECORD_OPENCODE_LAUNCH_GOLDEN'):+ environment.pop(key, None)+tmux = cli.parent / '.harness/tmux'+tmux.mkdir(parents=True, exist_ok=True)+environment['TMUX_TMPDIR'] = str(tmux)+++def run(files, pattern=''):+ command = ['node', 'node_modules/vitest/vitest.mjs', 'run', *files, '--maxWorkers=1']+ if pattern:+ command += ['-t', pattern]+ return subprocess.run(command, cwd=cli, env=environment, text=True, capture_output=True, timeout=180)+++baseline = run([golden, probe, hooks, create])+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/scripts/handoff-2026-10-08/mutate-opencode-launch.py b/cli/scripts/handoff-2026-10-08/mutate-opencode-launch.pyindex e7c969e4c..85d7db2ec 100644--- a/cli/scripts/handoff-2026-10-08/mutate-opencode-launch.py+++ b/cli/scripts/handoff-2026-10-08/mutate-opencode-launch.py@@ -20,7 +20,7 @@ mutations = [('fork version disconnected', 'src/core/agents/fork.ts', 'opencode.opencodeMajorVersion()', 'null', golden),('retarget native model skipped', 'src/core/agents/retarget.ts', 'if (rewritesOpencodeSession && opencode)', 'if (false)', golden),('relaunch depends on optional code', 'src/core/agents/launch.ts', "import { prepareResume, repairedItemsName }", "import { loadEngine } from '../../engines/inProcess.js'\nimport { prepareResume, repairedItemsName }", architecture),- ('composition reads optional code', 'src/core/main.ts', "opencodeMajor: engine === 'opencode' ? opencodeMajorVersion() : null", "opencodeMajor: engine === 'opencode' ? engineNow('opencode', 'an OpenCode launch was built')?.opencodeMajorVersion() ?? null : null", architecture),+ ('composition reads optional code', 'src/core/main.ts', "opencodeMajor: engine === 'opencode' ? await opencodeMajorVersion() : null", "opencodeMajor: engine === 'opencode' ? engineNow('opencode', 'an OpenCode launch was built')?.opencodeMajorVersion() ?? null : null", architecture),('retarget waits on optional reader', 'src/core/agents/retarget.ts', "const opencode = session.engine === 'opencode' ? opencodeLaunch : null", "const opencode = session.engine === 'opencode' ? await (await import('../../engines/inProcess.js')).loadEngine('opencode') : null", eager),]env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}diff --git a/cli/scripts/handoff-2026-10-08/native-version-cost.ts b/cli/scripts/handoff-2026-10-08/native-version-cost.tsnew file mode 100644index 000000000..9bbcd08ae--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/native-version-cost.ts@@ -0,0 +1,54 @@+/** Matched native-version component workload. Run each revision/workload in a fresh process. */+import { 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 { performance } from 'node:perf_hooks'++const workload = process.argv[2]+if (!['healthy', 'slow', 'cached'].includes(workload)) throw Error('Unknown workload')+const cli = process.env.NATIVE_VERSION_COST_CLI ?? resolve(import.meta.dirname, '../..')+const root = realpathSync(mkdtempSync(join(tmpdir(), 'native-version-cost-')))+try {+ // The only executable is this private fixture, using the same Node as the runner.+ const file = join(root, 'opencode'), calls = join(root, 'calls')+ writeFileSync(calls, '')+ writeFileSync(file, `#!${process.execPath}+const fs = require('node:fs');+if (process.argv.slice(2).join(' ') !== '--version') process.exit(2);+fs.appendFileSync(${JSON.stringify(calls)}, 'probe\\n');+setTimeout(() => console.log('opencode v2.0.18'), ${workload === 'slow' ? 100 : 0});+`, { mode: 0o700 })+ process.env.HOME = root+ const { majorVersion, nativeVersionProbe } = await import(pathToFileURL(join(cli, 'src/engines/kit/nativeVersion.ts')).href)+ const rule = { args: ['--version'], output: /(\d+)\.\d+\.\d+/, timeoutMs: 5_000 }+ const memo = new Map<string, number | null>()+ if (workload === 'cached' && await majorVersion(rule, nativeVersionProbe(rule, () => file), memo) !== 2) throw Error('Warmup failed')+ const iterations = workload === 'cached' ? 500 : 10+ const latenciesMs: number[] = [], callbackDelaysMs: number[] = []+ const cpu = process.cpuUsage(), start = performance.now()+ for (let index = 0; index < iterations; index++) {+ let last = performance.now(), worst = 0+ const timer = setInterval(() => { const now = performance.now(); worst = Math.max(worst, now - last); last = now }, 1)+ try {+ const started = performance.now()+ const answer = await majorVersion(rule, nativeVersionProbe(rule, () => file), workload === 'cached' ? memo : new Map())+ latenciesMs.push(performance.now() - started)+ // Let the timer see the final synchronous block before clearing it.+ await new Promise(done => setTimeout(done, 1))+ callbackDelaysMs.push(worst)+ if (answer !== 2) throw Error('The version answer changed')+ } finally { clearInterval(timer) }+ }+ const used = process.cpuUsage(cpu)+ const commands = readFileSync(calls, 'utf8').trim().split('\n').filter(Boolean).length+ if (commands !== (workload === 'cached' ? 1 : iterations)) throw Error('Unexpected number of native probes')+ const distribution = (values: number[]) => {+ const sorted = [...values].sort((a, b) => a - b)+ return { median: sorted[Math.floor(sorted.length / 2)], max: sorted.at(-1) }+ }+ process.stdout.write(JSON.stringify({ workload, iterations, commands, latencyMs: distribution(latenciesMs),+ callbackDelayMs: distribution(callbackDelaysMs), elapsedMs: performance.now() - start,+ parentCpuMs: (used.user + used.system) / 1000, peakRssMiB: process.resourceUsage().maxRSS / 1024,+ node: process.version, platform: process.platform, arch: process.arch }) + '\n')+} finally { rmSync(root, { recursive: true, force: true }) }diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 014baddb1..10f17df5b 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -3242,7 +3242,7 @@ describe('agent_create with a prompt, a name and a named agent', () => {it('passes the named agent through for opencode, and null when none was given', async () => {// v1 — pinned, so the answer does not depend on the OpenCode installed where the suite runs.- vi.spyOn(opencodeVersion, 'opencodeMajorVersion').mockReturnValue(1)+ vi.spyOn(opencodeVersion, 'opencodeMajorVersion').mockResolvedValue(1)const { seen, reply } = await create({ agent: 'harness-compute', name: 'Local model' })expect(seen).toEqual([expect.objectContaining({ engine: 'opencode', agent: 'harness-compute', name: 'Local model', prompt: null })])expect(reply).toMatchObject({ agent: expect.objectContaining({ id: 'named-1' }) })@@ -3251,7 +3251,7 @@ describe('agent_create with a prompt, a name and a named agent', () => {})it('refuses a named agent for opencode v2, whose TUI exits 1 on --agent, before any pane exists', async () => {- vi.spyOn(opencodeVersion, 'opencodeMajorVersion').mockReturnValue(2)+ vi.spyOn(opencodeVersion, 'opencodeMajorVersion').mockResolvedValue(2)const { seen, reply } = await create({ agent: 'harness-compute' })expect(reply).toMatchObject({ error: 'AGENT_UNSUPPORTED', detail: expect.stringContaining('opencode') })expect(seen).toHaveLength(0)diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 3c1aa25a0..7eb582462 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -19,6 +19,8 @@ import { clearPaneRemainOnExit } from '../../lib/tmux.js'import { tmuxSupportsSessionEnv } from '../../lib/tmuxVersion.js'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'vi.mock('../../scm/scmProjects.js', async real => ({ ...await real<object>(), prepareInstructionWrites: vi.fn(async () => {}) }))@@ -33,7 +35,8 @@ vi.mock('../../engines/inProcess.js', async (real) => {const actual = await real<typeof import('../../engines/inProcess.js')>()return { ...actual, loadEngine: vi.fn(actual.loadEngine) }})-vi.mock('../../engines/launchControl.js', () => ({ opencodeMajorVersion: vi.fn(() => 2) }))+vi.mock('../../engines/launchControl.js', () => ({ opencodeMajorVersion: vi.fn(async () => 2) }))+vi.mock('../../engines/kit/nativePlugin.js', () => ({ installNativePlugin: vi.fn(), removeNativePlugin: vi.fn() }))// 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),@@ -360,6 +363,24 @@ describe('creating an agent', () => {warn.mockRestore()})+ it('lets concurrent healthy OpenCode creates share the current native hook installation', async () => {+ const completions: Array<(major: number) => void> = []+ let entered!: () => void+ const bothEntered = new Promise<void>(done => { entered = done })+ const probe = () => new Promise<number>(done => {+ completions.push(done)+ if (completions.length === 2) entered()+ })+ vi.mocked(opencodeMajorVersion).mockImplementationOnce(probe).mockImplementationOnce(probe)+ const test = setup({ installOpencodePlugin })+ const first = test.create(request({ engine: 'opencode' }))+ const second = test.create(request({ engine: 'opencode' }))+ await bothEntered+ completions[0]!(2); completions[1]!(2)+ expect((await Promise.all([first, second])).map(result => result.ok)).toEqual([true, true])+ expect(createAndRegisterPane).toHaveBeenCalledTimes(2)+ })+it('creates OpenCode from eager facts when optional code cannot load', async () => {vi.mocked(loadEngine).mockImplementation(() => new Promise(() => {}))const t = setup()diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex cb3413a98..b9e15eb1d 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -67,7 +67,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+ gridLaunchMachine: (engine: AgentEngine) => 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>@@ -153,7 +153,7 @@ 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: gridLaunchMachine(engine) }) : null+ const built = grid ? await buildGridLaunch({ engine, override: grid, machine: await gridLaunchMachine(engine) }) : nullif (built && !built.ok) {console.warn(`[agent] create ${engine} refused · ${built.detail}`)return { ok: false, error: built.error, detail: built.detail }@@ -256,7 +256,7 @@ 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 ? opencode.opencodeMajorVersion() : null) : [])]+ const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, 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 = promptdiff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.tsindex ed688eaa0..0ac6a68a0 100644--- a/cli/src/core/agents/fork.ts+++ b/cli/src/core/agents/fork.ts@@ -105,7 +105,7 @@ export function createAgentForker({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 ? opencode.opencodeMajorVersion() : null+ const forkMajor = opencode ? await opencode.opencodeMajorVersion() : nullconst extraArgs = [...built.overrides.extraArgs, ...dshArgs, ...(source.agent && supportsNamedAgent(engine, forkMajor) ? namedAgentArgs(engine, source.agent, forkMajor) : [])]const firstPrompt = plan.level === 'native' ? (prompt ?? undefined) : plan.firstPromptconst launchOptions = {diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.tsindex 78a551f71..5d7bb8f0c 100644--- a/cli/src/core/agents/launches.spec.ts+++ b/cli/src/core/agents/launches.spec.ts@@ -167,7 +167,7 @@ describe('agent_create, refused before any pane exists', () => {expect(await ask({ engine: 'claude', cwd: '/w', agent: '../reviewer' })).toStrictEqual({ error: 'INVALID_AGENT', detail: 'agent must be 1-64 letters, digits, `-` or `_`' })expect(await ask({ engine: 'claude', cwd: '/w', agent: 7 })).toMatchObject({ error: 'INVALID_AGENT' })vi.mocked(supportsNamedAgent).mockReturnValueOnce(false)- vi.mocked(opencodeMajorVersion).mockReturnValueOnce(2)+ vi.mocked(opencodeMajorVersion).mockResolvedValueOnce(2)expect(await ask({ engine: 'opencode', cwd: '/w', agent: 'reviewer' })).toMatchObject({ error: 'AGENT_UNSUPPORTED' })expect(supportsNamedAgent).toHaveBeenLastCalledWith('opencode', 2)expect(create).not.toHaveBeenCalled()diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsindex 9eb1a7c7a..5771e9fe4 100644--- a/cli/src/core/agents/launches.ts+++ b/cli/src/core/agents/launches.ts@@ -186,7 +186,7 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeA}// v2's TUI cannot open a named agent. Its native version control is eager.const opencode = engine === 'opencode' ? opencodeLaunch : null- if (!supportsNamedAgent(engine, opencode ? opencode.opencodeMajorVersion() : null)) {+ if (!supportsNamedAgent(engine, opencode ? await opencode.opencodeMajorVersion() : null)) {reply({ error: 'AGENT_UNSUPPORTED', detail: new NamedAgentUnsupportedError(engine).message }); return}agent = payload.agentdiff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.tsindex 99615f0ce..884d22649 100644--- a/cli/src/core/agents/retarget.ts+++ b/cli/src/core/agents/retarget.ts@@ -127,7 +127,7 @@ export function createAgentRetargeter({const rewritesOpencodeSession = session.engine === 'opencode' && !!session.sessionId&& (!!grid || !!remembered?.includes('/'))const opencode = session.engine === 'opencode' ? opencodeLaunch : null- const opencodeMajor = opencode ? opencode.opencodeMajorVersion() : null+ const opencodeMajor = opencode ? await opencode.opencodeMajorVersion() : nullif (rewritesOpencodeSession && opencode && !opencode.isOpencodeV2(opencodeMajor) && !binaryOnPath('sqlite3')) {return {ok: false,diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.tsindex b7a7a93f0..4c5c9dd7f 100644--- a/cli/src/core/engines/hooks.spec.ts+++ b/cli/src/core/engines/hooks.spec.ts@@ -384,6 +384,33 @@ describe('installing every engine\'s hooks', () => {expect(loadEngine).not.toHaveBeenCalled()})+ it('keeps other native installers moving while the bounded version probe waits', async () => {+ let finish!: () => void+ vi.mocked(hooks.installOpencodePlugin).mockImplementationOnce(() => new Promise<boolean>(done => { finish = () => done(true) }))+ let completed = false+ const pending = installEngineHooks(4242).then(value => { completed = true; return value })+ expect(hooks.installCopilotHooks).toHaveBeenCalledWith(4242)+ await Promise.resolve()+ expect(completed).toBe(false)+ finish()+ const installed = await pending+ installed.close()+ expect(completed).toBe(true)+ })++ it('contains an asynchronous native installer rejection', async () => {+ vi.mocked(hooks.installOpencodePlugin).mockRejectedValueOnce(new Error('probe unavailable'))+ const installed = await installEngineHooks(4242)+ expect(hooks.installCopilotHooks).toHaveBeenCalledWith(4242)+ expect(console.warn).toHaveBeenCalledWith('[hooks] opencode install skipped · probe unavailable')+ installed.close()+ })++ it('does not launch from an obsolete native installation', async () => {+ vi.mocked(hooks.installOpencodePlugin).mockResolvedValueOnce(false)+ expect(await installOpencodePluginBeforeSpawn(4242)).toBe(false)+ })+it('installs synchronously in the original order before returning the completion promise', async () => {const order: string[] = []for (const [index, install] of installs.entries()) vi.mocked(install).mockImplementationOnce(() => { order.push(String(index)) })diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.tsindex 12e8864b8..8a20dec21 100644--- a/cli/src/core/engines/hooks.ts+++ b/cli/src/core/engines/hooks.ts@@ -211,8 +211,7 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry, pane* never depends on loading its optional interpreter.*/export async function installOpencodePluginBeforeSpawn(port: number): Promise<boolean> {- nativeHooks.installOpencodePlugin(port)- return true+ return await nativeHooks.installOpencodePlugin(port) !== false}export interface InstallEngineHooksOptions {@@ -227,7 +226,7 @@ export interface InstallEngineHooksOptions {/*** The other engines' declarations are installed in their original order, without an optional import.*/-const OTHER_INSTALLERS: Array<[string, (port: number) => void]> = [+const OTHER_INSTALLERS: Array<[string, (port: number) => void | Promise<unknown>]> = [['cursor', nativeHooks.installCursorHooks],['opencode', nativeHooks.installOpencodePlugin],['kilo', nativeHooks.installKiloPlugin],@@ -255,11 +254,16 @@ const OTHER_INSTALLERS: Array<[string, (port: number) => void]> = [* durable launch holds for preparation failures are a separate behavior change. Never rejects.*/export async function installEngineHooks(port: number, options: InstallEngineHooksOptions = {}): Promise<{ close(): void }> {- const hookStep = (vendor: string, install: () => void): void => {+ const pending: Promise<void>[] = []+ const hookStep = (vendor: string, install: () => void | Promise<unknown>): void => {if (options.only && !options.only.has(vendor)) return- try { install() } catch (error) {+ const failed = (error: unknown) => {console.warn(`[hooks] ${vendor} install skipped · ${error instanceof Error ? error.message : error}`)}+ try {+ const result = install()+ if (result) pending.push(result.then(() => {}, failed))+ } catch (error) { failed(error) }}// The homes the person moved (lib/engineHomes.ts, by each engine's declared session store) get the hooks// too: every one adopted before, those the daemon's own environment names, and those of the login shell@@ -282,5 +286,6 @@ export async function installEngineHooks(port: number, options: InstallEngineHoovoid options.loginShell?.then(adoptions.submit, error => console.warn(`[hooks] login-shell homes unavailable · ${error instanceof Error ? error.message : error}`))for (const [engine, hooks] of Object.entries(engineHooks)) hookStep(engine, () => hooks.install(port))for (const [vendor, install] of OTHER_INSTALLERS) hookStep(vendor, () => install(port))+ await Promise.all(pending)return { close: adoptions.close }}diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 732c16999..b82c86ac7 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -1956,9 +1956,9 @@ 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 = (engine: AgentEngine): GridLaunchMachine => ({+ const gridLaunchMachine = async (engine: AgentEngine): Promise<GridLaunchMachine> => ({hermesSystemManaged: existsSync(HERMES_SYSTEM_MANAGED_DIR),- opencodeMajor: engine === 'opencode' ? opencodeMajorVersion() : null,+ opencodeMajor: engine === 'opencode' ? await opencodeMajorVersion() : null,})/**diff --git a/cli/src/engines/__fixtures__/native-version.golden.json b/cli/src/engines/__fixtures__/native-version.golden.jsonnew file mode 100644index 000000000..a6370f7cc--- /dev/null+++ b/cli/src/engines/__fixtures__/native-version.golden.json@@ -0,0 +1,94 @@+{+ "linux:v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"+ ]+ ]+ ],+ "files": [+ {+ "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n const token = hookToken()\n if (!pane || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ },+ {+ "file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const router = ctx && ctx.ui && ctx.ui.router\n if (!pane || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [{ backend: \"tmux\", paneId: pane }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ }+ ]+ },+ "linux:v2": {+ "installed": true,+ "first": 2,+ "repeat": 2,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"+ ]+ ]+ ],+ "files": [+ {+ "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",+ "source": null+ },+ {+ "file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const router = ctx && ctx.ui && ctx.ui.router\n if (!pane || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [{ backend: \"tmux\", paneId: pane }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ }+ ]+ },+ "darwin:v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"+ ]+ ]+ ],+ "files": [+ {+ "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n const token = hookToken()\n if (!pane || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"+ },+ {+ "file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const router = ctx && ctx.ui && ctx.ui.router\n if (!pane || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [{ backend: \"tmux\", paneId: pane }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ }+ ]+ },+ "darwin:v2": {+ "installed": true,+ "first": 2,+ "repeat": 2,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"+ ]+ ]+ ],+ "files": [+ {+ "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",+ "source": null+ },+ {+ "file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const router = ctx && ctx.ui && ctx.ui.router\n if (!pane || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [{ backend: \"tmux\", paneId: pane }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"+ }+ ]+ }+}diff --git a/cli/src/engines/kit/nativeVersion.spec.ts b/cli/src/engines/kit/nativeVersion.spec.tsnew file mode 100644index 000000000..7dbc4154c--- /dev/null+++ b/cli/src/engines/kit/nativeVersion.spec.ts@@ -0,0 +1,96 @@+import { mkdtempSync, rmSync, writeFileSync, renameSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, expect, it, vi } from 'vitest'+import { majorVersion, nativeVersionProbe } from './nativeVersion.js'++const roots: string[] = []+const rule = { output: /(\d+)\.\d+\.\d+/, args: ['--version'], timeoutMs: 2_000 }+function fixture(source: string) {+ const root = mkdtempSync(join(tmpdir(), 'native-version-probe-')); roots.push(root)+ const file = join(root, 'engine')+ writeFileSync(file, `#!${process.execPath}\n${source}\n`, { mode: 0o700 })+ return file+}+afterEach(() => { vi.unstubAllEnvs(); vi.resetModules(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })++it('keeps core timers responsive while a native version command is running', async () => {+ const file = fixture("setTimeout(() => console.log('2.0.18'), 100)")+ let responsive = false+ const timer = setTimeout(() => { responsive = true }, 20)+ try {+ expect(await majorVersion(rule, nativeVersionProbe(rule, () => file), new Map())).toBe(2)+ expect(responsive).toBe(true)+ } finally { clearTimeout(timer) }+})++it('reads the executable selected for this probe once instead of resolving a different command for execution', async () => {+ const first = fixture("console.log('1.18.31')"), second = fixture("console.log('2.0.18')")+ let calls = 0+ expect(await majorVersion(rule, nativeVersionProbe(rule, () => ++calls === 1 ? first : second), new Map())).toBe(1)+ expect(calls).toBe(1)+})++it('discards a version answer if the selected executable is replaced while it runs', async () => {+ const file = fixture("setTimeout(() => console.log('1.18.31'), 100)")+ const replacement = `${file}.new`+ writeFileSync(replacement, `#!${process.execPath}\nconsole.log('2.0.18')\n`, { mode: 0o700 })+ const memo = new Map<string, number | null>()+ const timer = setTimeout(() => renameSync(replacement, file), 30)+ try {+ expect(await majorVersion(rule, nativeVersionProbe(rule, () => file), memo)).toBeNull()+ expect(memo.size).toBe(0)+ } finally { clearTimeout(timer) }+})++it('bounds a native process that never answers', async () => {+ const file = fixture('setInterval(() => {}, 1000)')+ const bounded = { ...rule, timeoutMs: 80 }+ expect(await majorVersion(bounded, nativeVersionProbe(bounded, () => file), new Map())).toBeNull()+}, 2_000)++it('contains an output flood without blocking other callbacks', async () => {+ const file = fixture("process.stdout.write('1.18.31\\n' + 'x'.repeat(128 * 1024))")+ expect(await majorVersion(rule, nativeVersionProbe(rule, () => file), new Map())).toBeNull()+})++it('closes stdin for native launchers that read to EOF before reporting their version', async () => {+ const file = fixture("require('node:fs').readFileSync(0); console.log('2.0.18')")+ expect(await majorVersion(rule, nativeVersionProbe(rule, () => file), new Map())).toBe(2)+})++it('does not let an older failed probe replace a newer confirmed answer', async () => {+ const memo = new Map<string, number | null>()+ let fail!: (error: Error) => void+ const old = majorVersion(rule, { identity: () => 'same-file', read: () => new Promise<string>((_done, reject) => { fail = reject }) }, memo)+ expect(await majorVersion(rule, { identity: () => 'same-file', read: () => '2.0.18' }, memo)).toBe(2)+ fail(new Error('older timeout'))+ await old+ expect(memo.get('same-file')).toBe(2)+})++it('returns a confirmed answer while a newer probe of the unchanged file is still pending', async () => {+ const memo = new Map<string, number | null>()+ let first!: (output: string) => void, second!: (output: string) => void+ const older = majorVersion(rule, { identity: () => 'same-file', read: () => new Promise<string>(done => { first = done }) }, memo)+ const newer = majorVersion(rule, { identity: () => 'same-file', read: () => new Promise<string>(done => { second = done }) }, memo)+ try {+ first('2.0.18')+ expect(await older).toBe(2)+ } finally { second('2.0.18'); await newer }+ expect(memo.get('same-file')).toBe(2)+})++it('keeps the production resolver asynchronous when only the interactive shell can find OpenCode', async () => {+ const file = fixture("console.log('2.0.18')")+ const root = roots.at(-1)!, engine = join(root, 'opencode'), shell = join(root, 'shell'), release = join(root, 'allow-shell')+ renameSync(file, engine)+ writeFileSync(shell, `#!${process.execPath}\nconst fs = require('node:fs');\nconst timer = setInterval(() => { if (fs.existsSync(${JSON.stringify(release)})) { clearInterval(timer); console.log('__HARNESS_ENGINE_PATH__=' + ${JSON.stringify(root)}); } }, 10)\n`, { mode: 0o700 })+ vi.stubEnv('HOME', root); vi.stubEnv('PATH', join(root, 'empty-path'))+ vi.stubEnv('SHELL', shell); vi.stubEnv('NODE_ENV', 'production'); vi.stubEnv('OPENCODE_PATH', '')+ vi.resetModules()+ const { opencodeMajorVersion } = await import('../launchControl.js')+ const timer = setTimeout(() => writeFileSync(release, ''), 20)+ try { expect(await opencodeMajorVersion()).toBe(2) }+ finally { clearTimeout(timer) }+}, 8_000)diff --git a/cli/src/engines/kit/nativeVersion.ts b/cli/src/engines/kit/nativeVersion.tsindex 251c3c0f7..0424ee48a 100644--- a/cli/src/engines/kit/nativeVersion.ts+++ b/cli/src/engines/kit/nativeVersion.ts@@ -1,10 +1,11 @@/** Native executable facts used by launch control, without loading an interpreter. */-import { execFileSync } from 'node:child_process'-import { statSync } from 'node:fs'+import { execFile } from 'node:child_process'+import { realpathSync, statSync } from 'node:fs'+import { resolve } from 'node:path'import { resolveBinaryOnPath } from '../../lib/binaryOnPath.js'export interface VersionRule { output: RegExp; args: readonly string[]; timeoutMs: number }-export interface VersionProbe { identity(): string | null; read(): string }+export interface VersionProbe { identity(): string | null; read(): string | Promise<string> }export function parseMajor(rule: VersionRule, output: string): number | null {const match = rule.output.exec(output)@@ -12,24 +13,58 @@ export function parseMajor(rule: VersionRule, output: string): number | null {}export function nativeVersionProbe(rule: VersionRule, binary: () => string): VersionProbe {+ // 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+ const path = () => {+ if (selected === undefined) {+ const command = binary()+ selected = command.includes('/') ? resolve(command) : resolveBinaryOnPath(command)+ }+ return selected+ }return {identity: () => {- const bin = binary(), path = bin.includes('/') ? bin : resolveBinaryOnPath(bin)- if (!path) return null- try { const info = statSync(path); return `${path}:${info.size}:${info.mtimeMs}` } catch { return null }+ const file = path()+ if (!file) return null+ try {+ const target = realpathSync(file), info = statSync(file)+ if (!info.isFile()) return null+ return `${file}:${target}:${info.dev}:${info.ino}:${info.mode}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`+ } catch { return null }},- read: () => execFileSync(binary(), [...rule.args], {- encoding: 'utf8', timeout: rule.timeoutMs, killSignal: 'SIGKILL', stdio: ['ignore', 'pipe', 'ignore'],+ read: () => new Promise<string>((done, failed) => {+ 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,+ }, (error, stdout) => { if (error) failed(error); else done(stdout) })+ child.stdin?.end()}),}}/** Compatibility behavior: one answer per installed file; absent files have no cache key. */-export function majorVersion(rule: VersionRule, probe: VersionProbe, memo: Map<string, number | null>): number | null {+const publishing = new WeakMap<Map<string, number | null>, Map<string, object>>()+export async function majorVersion(rule: VersionRule, probe: VersionProbe, memo: Map<string, number | null>): Promise<number | null> {const identity = probe.identity()if (identity !== null && memo.has(identity)) return memo.get(identity) ?? null+ const attempts = publishing.get(memo) ?? new Map<string, object>()+ publishing.set(memo, attempts)+ const ticket = {}+ if (identity !== null) attempts.set(identity, ticket)let major: number | null- try { major = parseMajor(rule, probe.read()) } catch { major = null }- if (identity !== null) memo.set(identity, major)+ try { major = parseMajor(rule, await probe.read()) } catch { major = null }+ // An upgrade may replace the executable while --version is in flight. The+ // answer belongs only to the complete file identity inspected before spawning.+ const current = identity === probe.identity()+ if (identity !== null) {+ // A late failed read cannot erase a newer successful observation of this+ // file. The synchronous implementation could never overlap in this way.+ if (attempts.get(identity) !== ticket) return current ? major : null+ attempts.delete(identity)+ if (current) memo.set(identity, major)+ }+ if (!current) return nullreturn major}diff --git a/cli/src/engines/launchControl.ts b/cli/src/engines/launchControl.tsindex 17e44d09a..0a87b33c4 100644--- a/cli/src/engines/launchControl.ts+++ b/cli/src/engines/launchControl.ts@@ -1,15 +1,20 @@/** Eager native launch control. Importing it neither probes a binary nor reads or writes a store. */-import { opencodeBin } from '../lib/engineBin.js'+import { opencodeBin, opencodeBinAsync } from '../lib/engineBin.js'import { OPENCODE_SESSION_MODEL, OPENCODE_VERSION } from './opencode/contract.js'import { majorVersion, nativeVersionProbe, parseMajor, type VersionProbe } from './kit/nativeVersion.js'import { createSessionModelControl, type NativeApiRun, type NativeModelResult, type NativeSessionModel } from './kit/nativeSessionModel.js'export { isOpencodeV2 } from './opencode/contract.js'export type OpencodeVersionProbe = VersionProbe-const versionProbe = nativeVersionProbe(OPENCODE_VERSION, opencodeBin)const versionMemo = new Map<string, number | null>()export const parseOpencodeMajor = (output: string): number | null => parseMajor(OPENCODE_VERSION, output)-export const opencodeMajorVersion = (probe: VersionProbe = versionProbe, memo = versionMemo): number | null => majorVersion(OPENCODE_VERSION, probe, memo)+export async function opencodeMajorVersion(probe?: VersionProbe, memo = versionMemo): Promise<number | null> {+ if (!probe) {+ const binary = await opencodeBinAsync()+ probe = nativeVersionProbe(OPENCODE_VERSION, () => binary)+ }+ return majorVersion(OPENCODE_VERSION, probe, memo)+}export type OpencodeSessionModel = NativeSessionModelexport type SetOpencodeSessionModelResult = NativeModelResultdiff --git a/cli/src/engines/nativeHooks.ts b/cli/src/engines/nativeHooks.tsindex 30cbdace4..3c0a4e056 100644--- a/cli/src/engines/nativeHooks.ts+++ b/cli/src/engines/nativeHooks.ts@@ -2,7 +2,7 @@import { join } from 'node:path'import { env } from '../config/env.js'import { VERSION } from '../version.js'-import { OPENCODE_LEGACY_PLUGIN, OPENCODE_TUI_PLUGIN, OPENCODE_LEGACY_REMOVAL } from './opencode/contract.js'+import { OPENCODE_LEGACY_PLUGIN, OPENCODE_TUI_PLUGIN, OPENCODE_LEGACY_REMOVAL, OPENCODE_VERSION } from './opencode/contract.js'import { KILO_PLUGIN } from './kilo/contract.js'import { PI_EXTENSION } from './pi/contract.js'import { AMP_PLUGIN } from './amp/contract.js'@@ -36,9 +36,39 @@ export const installHermesHooks = (port: number): void =>installNativeYamlHooks(HERMES_HOOK_SETTINGS, home => command(port, 'hermes', env.CODEX_HOME, home))/** Install both discovery surfaces for v1; v2 must not load our incompatible v1 export. */-export function installOpencodePlugin(port: number): void {- const values = pluginValues(port)- if (opencodeMajorVersion() === 1) installNativePlugin(OPENCODE_LEGACY_PLUGIN, values)- else removeNativePlugin(OPENCODE_LEGACY_REMOVAL)- installNativePlugin(OPENCODE_TUI_PLUGIN, values)+interface OpencodeInstallation { port: number; done: Promise<boolean> }+let opencodeInstallation: OpencodeInstallation | undefined+export async function installOpencodePlugin(port: number): Promise<boolean> {+ const installation: OpencodeInstallation = { port, done: Promise.resolve(false) }+ opencodeInstallation = installation+ installation.done = (async () => {+ const values = pluginValues(port)+ const major = await opencodeMajorVersion()+ // 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) return false+ if (major === 1) installNativePlugin(OPENCODE_LEGACY_PLUGIN, values)+ else removeNativePlugin(OPENCODE_LEGACY_REMOVAL)+ installNativePlugin(OPENCODE_TUI_PLUGIN, values)+ return true+ })()+ let current = installation, installed = await current.done+ const deadline = performance.now() + OPENCODE_VERSION.timeoutMs+ while (current !== opencodeInstallation) {+ current = opencodeInstallation!+ // 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.+ const remaining = deadline - performance.now()+ if (current.port !== port || remaining <= 0) return false+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ const result = await Promise.race([current.done, new Promise<'timeout'>(done => {+ timer = setTimeout(() => done('timeout'), remaining)+ })])+ if (result === 'timeout') return false+ installed = result+ } finally { clearTimeout(timer) }+ }+ return installed}diff --git a/cli/src/engines/nativeVersion.golden.spec.ts b/cli/src/engines/nativeVersion.golden.spec.tsnew file mode 100644index 000000000..a2b936878--- /dev/null+++ b/cli/src/engines/nativeVersion.golden.spec.ts@@ -0,0 +1,81 @@+/** Healthy native version and hook selection, recorded before the probe becomes asynchronous. */+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, existsSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterAll, expect, it, vi } from 'vitest'++const native = vi.hoisted(() => ({ major: 1, stamp: 1, calls: [] as unknown[] }))+vi.mock('node:child_process', async original => {+ const actual = await original<typeof import('node:child_process')>()+ const answer = (binary: string, args: readonly string[]) => {+ if (binary !== '/fixture/bin/opencode' || JSON.stringify(args) !== '["--version"]') throw Error('Host binaries are forbidden in this golden')+ native.calls.push([binary, args])+ return native.major === 1 ? '1.18.31\n' : 'opencode v2.0.18\n'+ }+ return { ...actual, execFileSync: answer,+ execFile: (binary: string, args: string[], _options: unknown, callback: (error: Error | null, stdout: string, stderr: string) => void) => {+ queueMicrotask(() => {+ try { callback(null, answer(binary, args), '') }+ catch (error) { callback(error as Error, '', '') }+ })+ return { kill: () => true }+ },+ exec: () => { throw Error('Host shells are forbidden in this golden') },+ execSync: () => { throw Error('Host shells are forbidden in this golden') },+ spawn: () => { throw Error('Host processes are forbidden in this golden') },+ spawnSync: () => { throw Error('Host processes are forbidden in this golden') },+ }+})+vi.mock('node:fs', async original => {+ const actual = await original<typeof import('node:fs')>()+ return { ...actual, realpathSync: Object.assign((file: string) => file === '/fixture/bin/opencode' ? file : actual.realpathSync(file), { native: actual.realpathSync.native }), statSync: (file: string, ...args: unknown[]) => file === '/fixture/bin/opencode'+ ? { dev: 1, ino: native.stamp, size: 64, mtimeMs: native.stamp, ctimeMs: native.stamp, mode: 0o100755,+ isFile: () => true, isSymbolicLink: () => false }+ : (actual.statSync as (...args: unknown[]) => unknown)(file, ...args) }+})+vi.mock('../lib/loginShellEnv.js', () => ({ loginShellEnvironment: () => ({}) }))++const GOLDEN = fileURLToPath(new URL('./__fixtures__/native-version.golden.json', import.meta.url))+const record = process.env.RECORD_NATIVE_VERSION_GOLDEN === '1'+const observations: Record<string, unknown> = {}+const expected = record ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8'))++it.each(['linux', 'darwin'])('preserves versioned native hook selection on %s', async platform => {+ const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'native-version-golden-')))+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ try {+ Object.defineProperty(process, 'platform', { ...descriptor, value: platform })+ vi.useFakeTimers({ toFake: ['Date'], now: Date.parse('2026-10-10T15:00:00Z') })+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'OPENCODE_CONFIG_DIR', 'OPENCODE_DATA_DIR']) {+ const path = join(root, name); mkdirSync(path, { recursive: true }); vi.stubEnv(name, path)+ }+ vi.stubEnv('OPENCODE_PATH', '/fixture/bin/opencode'); vi.stubEnv('TZ', 'UTC')+ vi.resetModules()+ const { installOpencodePluginBeforeSpawn } = await import('../core/engines/hooks.js')+ const { opencodeMajorVersion } = await import('./launchControl.js')+ const { OPENCODE_LEGACY_PLUGIN, OPENCODE_TUI_PLUGIN } = await import('./opencode/contract.js')+ const { VERSION } = await import('../version.js')+ const files = () => [OPENCODE_LEGACY_PLUGIN.file, OPENCODE_TUI_PLUGIN.file].map(file => ({+ file, source: existsSync(file) ? readFileSync(file, 'utf8').split(VERSION).join('<version>') : null,+ }))+ for (const major of [1, 2]) {+ native.major = major; native.stamp = major; native.calls.length = 0+ const installed = await installOpencodePluginBeforeSpawn(4242)+ const first = await opencodeMajorVersion(), repeat = await opencodeMajorVersion()+ const key = `${platform}:v${major}`+ observations[key] = JSON.parse(JSON.stringify({ installed, first, repeat, calls: native.calls, files: files() }).split(root).join('<root>'))+ if (!record) expect({ key, value: observations[key] }).toEqual({ key, value: expected[key] })+ }+ } finally {+ log.mockRestore(); vi.useRealTimers(); vi.unstubAllEnvs(); vi.resetModules()+ Object.defineProperty(process, 'platform', descriptor)+ rmSync(root, { recursive: true, force: true })+ }+}, 30_000)++afterAll(() => {+ if (record) writeFileSync(GOLDEN, JSON.stringify(observations, null, 2) + '\n')+ else expect(Object.keys(observations).sort()).toEqual(Object.keys(expected).sort())+})diff --git a/cli/src/engines/opencode/tuiFlags.spec.ts b/cli/src/engines/opencode/tuiFlags.spec.tsindex e74f6f6dc..48b8ae789 100644--- a/cli/src/engines/opencode/tuiFlags.spec.ts+++ b/cli/src/engines/opencode/tuiFlags.spec.ts@@ -25,7 +25,7 @@ describe.skipIf(!installed)('the installed opencode TUI accepts every flag we paconst help = helpResult ? `${helpResult.stdout}\n${helpResult.stderr}` : ''const major = installed ? opencodeMajorVersion() : nullconst deps: LaunchOverridesDeps = {- machine: () => ({ hermesSystemManaged: false, opencodeMajor: major }), gridLaunch: gridLaunchInProcess(),+ machine: async () => ({ hermesSystemManaged: false, opencodeMajor: await major }), gridLaunch: gridLaunchInProcess(),writeGridConfigDir: async (key) => `/state/grid-engine-config/${key}`,tmuxSupportsSessionEnv: async () => true,installCodexHooks: () => {},@@ -57,10 +57,10 @@ describe.skipIf(!installed)('the installed opencode TUI accepts every flag we pafor (const flag of flags) expect(listed(flag), `${flag} is not in \`opencode --help\` (v${major})`).toBe(true)})- it('agrees with the named-agent contract', () => {+ it('agrees with the named-agent contract', async () => {// Where the contract says yes, the flag it hands over must exist; where it says no, nothing is passed.- if (!supportsNamedAgent('opencode', major)) return- for (const flag of namedAgentArgs('opencode', 'x', major).filter((token) => token.startsWith('-'))) {+ if (!supportsNamedAgent('opencode', await major)) return+ for (const flag of namedAgentArgs('opencode', 'x', await major).filter((token) => token.startsWith('-'))) {expect(listed(flag), `${flag} is not in \`opencode --help\``).toBe(true)}})diff --git a/cli/src/engines/opencode/version.spec.ts b/cli/src/engines/opencode/version.spec.tsindex 0a8c65351..d521b33c7 100644--- a/cli/src/engines/opencode/version.spec.ts+++ b/cli/src/engines/opencode/version.spec.ts@@ -25,24 +25,24 @@ describe('isOpencodeV2', () => {})describe('opencodeMajorVersion', () => {- it('runs --version once per installed binary, and again once the binary changes', () => {+ it('runs --version once per installed binary, and again once the binary changes', async () => {let calls = 0let stamp = 'a'const probe = { identity: () => stamp, read: () => { calls++; return stamp === 'a' ? '1.18.31' : 'opencode v2.0.18' } }const cache = new Map<string, number | null>()- expect(opencodeMajorVersion(probe, cache)).toBe(1)- expect(opencodeMajorVersion(probe, cache)).toBe(1)+ expect(await opencodeMajorVersion(probe, cache)).toBe(1)+ expect(await opencodeMajorVersion(probe, cache)).toBe(1)expect(calls).toBe(1)// OpenCode updates itself in place (1.18 → 2.0 happened under a running daemon): a new file is a// new answer.stamp = 'b'- expect(opencodeMajorVersion(probe, cache)).toBe(2)+ expect(await opencodeMajorVersion(probe, cache)).toBe(2)expect(calls).toBe(2)})- it('answers null, without throwing, when the binary is missing or will not answer', () => {+ it('answers null, without throwing, when the binary is missing or will not answer', async () => {const cache = new Map<string, number | null>()- expect(opencodeMajorVersion({ identity: () => null, read: () => { throw new Error('ENOENT') } }, cache)).toBeNull()- expect(opencodeMajorVersion({ identity: () => 'x', read: () => { throw new Error('timeout') } }, cache)).toBeNull()+ expect(await opencodeMajorVersion({ identity: () => null, read: () => { throw new Error('ENOENT') } }, cache)).toBeNull()+ expect(await opencodeMajorVersion({ identity: () => 'x', read: () => { throw new Error('timeout') } }, cache)).toBeNull()})})diff --git a/cli/src/engines/opencodeLaunch.golden.spec.ts b/cli/src/engines/opencodeLaunch.golden.spec.tsindex 4d3976540..1368ea91f 100644--- a/cli/src/engines/opencodeLaunch.golden.spec.ts+++ b/cli/src/engines/opencodeLaunch.golden.spec.ts@@ -94,7 +94,7 @@ it('records create, fork, relaunch and actual retarget dispatch before the extraconst { createAgentRetargeter } = await import('../core/agents/retarget.js')const { buildEngineLaunchArgv } = await import('../lib/engineLaunch.js')const { env } = await import('../config/env.js')- const world = { dataDir: join(root, 'adapter_data_dir'), machine: () => ({ hermesSystemManaged: false, opencodeMajor: opencodeMajorVersion() }),+ const world = { dataDir: join(root, 'adapter_data_dir'), machine: async () => ({ hermesSystemManaged: false, opencodeMajor: await opencodeMajorVersion() }),tmuxSupportsSessionEnv: async () => true, readCodexConfig: () => null, setGridLaunch: () => {} }const shapes = launchShapes(world)const row = (engine: AgentEngine, named = false): RegisteredSession => ({ agentId: 'fixture-agent', sessionId: 'ses_fixture', engine, cwd: work,diff --git a/cli/src/lib/discoveryScripts.spec.ts b/cli/src/lib/discoveryScripts.spec.tsindex 37bd9403d..c4e41ed46 100644--- a/cli/src/lib/discoveryScripts.spec.ts+++ b/cli/src/lib/discoveryScripts.spec.ts@@ -6,10 +6,11 @@ import { pathToFileURL } from 'url'/** Pi and OpenCode register through generated source, so pin its process-owned wire contract directly. */const dirs: string[] = []-const version = vi.hoisted(() => ({ major: 1 as number | null }))-vi.mock('../engines/launchControl.js', () => ({ opencodeMajorVersion: () => version.major }))+const version = vi.hoisted(() => ({ major: 1 as number | null, read: undefined as undefined | (() => number | null | Promise<number | null>) }))+vi.mock('../engines/launchControl.js', () => ({ opencodeMajorVersion: () => version.read ? version.read() : version.major }))beforeEach(() => {version.major = 1+ version.read = undefinedvi.useFakeTimers({ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout'] })})afterEach(() => {@@ -26,6 +27,42 @@ function scratch(): string {}describe('generated discovery scripts', () => {+ it('does not let an obsolete version probe undo a newer plugin installation', async () => {+ const config = scratch(), pluginDir = join(config, 'plugin')+ vi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)+ const { installOpencodePlugin } = await import('./hooks.js')+ let finish!: (major: null) => void+ version.read = () => new Promise<null>(done => { finish = done })+ const obsolete = installOpencodePlugin(4242)+ version.read = () => 1+ await installOpencodePlugin(4242)+ const file = join(pluginDir, 'launcher-register.js'), confirmed = readFileSync(file, 'utf8')+ finish(null)+ await obsolete+ expect(existsSync(file)).toBe(true)+ expect(readFileSync(file, 'utf8')).toBe(confirmed)+ })++ it('bounds a superseded install waiting for its current sibling and refuses a changed port', async () => {+ const config = scratch(), pluginDir = join(config, 'plugin')+ vi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)+ const { installOpencodePlugin } = await import('./hooks.js')+ const { OPENCODE_VERSION } = await import('../engines/opencode/contract.js')+ const finishes: Array<(major: number) => void> = []+ version.read = () => new Promise<number>(done => { finishes.push(done) })+ const older = installOpencodePlugin(4242), newer = installOpencodePlugin(4242)+ finishes[0]!(1)+ await vi.advanceTimersByTimeAsync(OPENCODE_VERSION.timeoutMs)+ expect(await older).toBe(false)+ expect(existsSync(join(pluginDir, 'launcher-register.js'))).toBe(false)+ finishes[1]!(1)+ expect(await newer).toBe(true)+ const oldPort = installOpencodePlugin(4242), newPort = installOpencodePlugin(4243)+ finishes[2]!(1); finishes[3]!(1)+ expect(await oldPort).toBe(false)+ expect(await newPort).toBe(true)+ })+it('lets the Pi extension post from any terminal context without launcher metadata', async () => {const piHome = scratch()vi.resetModules()@@ -45,7 +82,7 @@ describe('generated discovery scripts', () => {vi.resetModules()vi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)const { installOpencodePlugin } = await import('./hooks.js')- installOpencodePlugin(18473)+ await installOpencodePlugin(18473)const src = readFileSync(join(pluginDir, 'launcher-register.js'), 'utf-8')expect(src).toContain('process.env.TMUX_PANE')@@ -69,7 +106,7 @@ describe('generated discovery scripts', () => {vi.stubEnv('ADAPTER_DATA_DIR', data)writeFileSync(join(data, 'hook-credential'), 'tok-123\n')const { installOpencodePlugin } = await import('./hooks.js')- installOpencodePlugin(18473)+ await installOpencodePlugin(18473)expect(existsSync(join(pluginDir, 'launcher-register.js'))).toBe(false)const tuiPath = join(config, 'plugins', 'launcher-register', 'tui.js')@@ -117,17 +154,17 @@ describe('generated discovery scripts', () => {const { installOpencodePlugin } = await import('./hooks.js')const legacy = join(pluginDir, 'launcher-register.js')const tui = join(config, 'plugins', 'launcher-register', 'tui.js')- installOpencodePlugin(18473)+ await installOpencodePlugin(18473)const original = readFileSync(legacy, 'utf8')expect(original).toContain('export const MachineRegister')const before = statSync(tui).mtimeMsversion.major = 2- installOpencodePlugin(18473)- installOpencodePlugin(18473)+ await installOpencodePlugin(18473)+ await installOpencodePlugin(18473)expect(existsSync(legacy)).toBe(false)expect(statSync(tui).mtimeMs).toBe(before)version.major = 1- installOpencodePlugin(18473)+ await installOpencodePlugin(18473)expect(readFileSync(legacy, 'utf8')).toBe(original)})@@ -144,7 +181,7 @@ describe('generated discovery scripts', () => {version.major = majorvi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)const { installOpencodePlugin } = await import('./hooks.js')- installOpencodePlugin(18473)+ await installOpencodePlugin(18473)expect(readFileSync(legacy, 'utf8')).toBe(foreign)expect(readFileSync(settings, 'utf8')).toBe(settingsText)})@@ -155,7 +192,7 @@ describe('generated discovery scripts', () => {version.major = nullvi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)const { installOpencodePlugin } = await import('./hooks.js')- installOpencodePlugin(18473)+ await installOpencodePlugin(18473)expect(existsSync(join(pluginDir, 'launcher-register.js'))).toBe(false)expect(existsSync(join(config, 'plugins', 'launcher-register', 'tui.js'))).toBe(true)})diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.tsindex 5e20f711d..ce050cd0f 100644--- a/cli/src/lib/engineBin.ts+++ b/cli/src/lib/engineBin.ts@@ -5,7 +5,7 @@* colliding `agent` alias is never assigned from its basename alone.*/-import { execFileSync } from 'node:child_process'+import { execFile, execFileSync } from 'node:child_process'import { accessSync, constants, readlinkSync, realpathSync, statSync } from 'node:fs'import { homedir } from 'node:os'import { basename, delimiter, isAbsolute, join, normalize, sep } from 'node:path'@@ -374,6 +374,48 @@ export function opencodeBin(): string {}}+/** Launch control must not run the synchronous interactive-shell fallback.+ * Resolve one captured environment asynchronously; the version probe then owns+ * and verifies the selected executable before it publishes an answer. */+export async function opencodeBinAsync(): Promise<string> {+ const configured = env.OPENCODE_PATH+ if (configured) return configured+ const ownPath = processPathEntries(), shell = process.env.SHELL, daemonPath = process.env.PATH ?? ''+ const installed = join(homedir(), '.opencode', 'bin', 'opencode')+ for (const entry of ownPath) {+ const file = join(entry, 'opencode')+ try { accessSync(file, constants.X_OK); return file } catch { /* next candidate */ }+ }+ let extra: string[] = []+ if (process.env.NODE_ENV !== 'test' && shell && isAbsolute(shell)) {+ if (interactivePathCache?.shell === shell && interactivePathCache.daemonPath === daemonPath && interactivePathCache.value.length) {+ extra = interactivePathCache.value+ } else {+ extra = await new Promise<string[]>(done => {+ const flag = basename(shell).toLowerCase() === 'zsh' ? '-lic' : '-ic'+ const marker = '__HARNESS_ENGINE_PATH__='+ try {+ const child = execFile(shell, [flag, `printf '\\n${marker}%s\\n' "$PATH"`], {+ encoding: 'utf8', timeout: 5_000, killSignal: 'SIGKILL', maxBuffer: 64 * 1024,+ }, (error, stdout) => {+ if (error) { done([]); return }+ const path = stdout.split('\n').reverse().find(line => line.startsWith(marker))?.slice(marker.length)+ done(path?.split(delimiter).filter(Boolean) ?? [])+ })+ child.stdin?.end()+ } catch { done([]) }+ })+ // Failed captures remain retryable. A later launch may find a repaired shell.+ if (extra.length) interactivePathCache = { shell, daemonPath, value: extra }+ }+ }+ for (const entry of extra) {+ const file = join(entry, 'opencode')+ try { accessSync(file, constants.X_OK); return file } catch { /* next candidate */ }+ }+ try { accessSync(installed, constants.X_OK); return installed } catch { return 'opencode' }+}+/** Resolve an installed executable for real-engine verification without trusting a colliding alias. */export function installedEngineBin(engine: AgentEngine,diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex bfc6b199c..f88a4db50 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -68,7 +68,7 @@ export type LaunchPreparationResult =export interface LaunchOverridesDeps {/** The facts about THIS machine a contract needs and cannot read for itself — see `GridLaunchMachine`. */- machine: (engine: AgentEngine) => GridLaunchMachine+ machine: (engine: AgentEngine) => 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>@@ -148,7 +148,7 @@ export async function validateLaunchOverrides(source: LaunchSource,): 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: deps.machine(engine) })+ const built = await deps.gridLaunch({ engine, override: source.gridLaunch, machine: await deps.machine(engine) })if (!built.ok) return { ok: false, error: built.error, detail: built.detail, ...(built.unavailable ? { unavailable: built.unavailable } : {}) }return tmuxRefusal(deps, engine, source.gridLaunch)}@@ -190,7 +190,7 @@ export async function prepareLaunchOverrides(const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The harness changed or stopped during launch preparation.' } as constif (!current()) return changedsource = structuredClone(source)- const machine = { ...deps.machine(engine) }+ const machine = { ...await deps.machine(engine) }const base = await prepareBaseLaunchOverrides({ ...deps, machine: () => machine }, engine, source, configKey)if (!current()) return changedif (!base.ok) return base@@ -263,7 +263,7 @@ async function prepareBaseLaunchOverrides(// back on the DEFAULT profile, reading hooks from a folder that was not the one it writes to.let ownLogin: LaunchOverrides | null = nullif (!source.gridLaunch) {- const restored = subscriptionModelLaunch(engine, source.subscriptionModel, deps.machine(engine).opencodeMajor ?? null)+ const restored = subscriptionModelLaunch(engine, source.subscriptionModel, (await deps.machine(engine)).opencodeMajor ?? null)// Ahead of the model on the command line: `-c` configures, `-m` selects, and Codex resolves the// model against the provider it has been given.const provider = ownLoginProviderArgs(engine, source.codexHome, { read: deps.readCodexConfig })@@ -279,7 +279,7 @@ async function prepareBaseLaunchOverrides(if (source.gridLaunch) {// Built once, by the models service, with a saved API's endpoint and key as saved now: a removed API is// refused first, then an engine that cannot be pointed there, then a tmux that cannot set the variables.- const built = await deps.gridLaunch({ engine, override: source.gridLaunch, machine: deps.machine(engine), refresh: true })+ const built = await deps.gridLaunch({ engine, override: source.gridLaunch, machine: await deps.machine(engine), refresh: true })if (!built.ok) return { ok: false, error: built.error, detail: built.detail, ...(built.unavailable ? { unavailable: built.unavailable } : {}) }const tmux = await tmuxRefusal(deps, engine, built.override)if (!tmux.ok) return tmuxdiff --git a/cli/src/testing/launchShapes.ts b/cli/src/testing/launchShapes.tsindex e45f7a51a..2b15939e7 100644--- a/cli/src/testing/launchShapes.ts+++ b/cli/src/testing/launchShapes.ts@@ -30,7 +30,7 @@ import { gridLaunchInProcess } from './gridLaunchInProcess.js'export interface LaunchWorld {/** The data folder: saved APIs, and the config directories written for file-configured engines. */dataDir: string- machine: () => GridLaunchMachine+ machine: () => GridLaunchMachine | Promise<GridLaunchMachine>tmuxSupportsSessionEnv: () => Promise<boolean>/** A Codex `config.toml`, as the own-login provider reads it. */readCodexConfig: (path: string) => string | nulldiff --git a/docs/research/2026-10-09-daemon-core-completion.md b/docs/research/2026-10-09-daemon-core-completion.mdindex 08f81cc3d..82f52a14f 100644--- a/docs/research/2026-10-09-daemon-core-completion.md+++ b/docs/research/2026-10-09-daemon-core-completion.md@@ -27,8 +27,8 @@ This is the remaining completion scope as of October 9, after the six extraction## Remaining blockers-1. **Complete native identity and retry.** Exact transcript lookup and native lock/descriptor enumeration are landed. Durable home adoption and its staged registry batch are [landed](2026-10-10-durable-home-adoption.md). Saved-binding file/header/root evidence and visible retry are [landed](2026-10-10-saved-binding-evidence.md). Atomic registration and live hook ownership are [landed](2026-10-10-native-hook-admission.md). Stop/Resume/Close transcript authority is [landed as #1139](2026-10-10-control-transcript-authority.md); reviewed history deletion is [landed as #1144](2026-10-10-native-history-consumers.md); [Change agent handoff authority](2026-10-10-native-handoff-authority.md) is under validation in #1145. Restart-persistent hook delivery, remaining saved-home consumers and legacy native-client acknowledgement/order still require migration. The [catalog audit](2026-10-09-native-home-catalog.md) records its fresh-evidence boundary and required remaining caller/writer migration. The native Hermes pool is landed; optional home promotion and shared handle-cache lifetime still need their authority/resource audit. An unreadable or truncated pool cannot prove absence or uniqueness. Every binding entry and transcript poll retains pending work, isolates a failed lookup, and retries without blocking sibling sessions or readiness. Surface the hold reason through the shared session state.-2. **Complete native launch preparation.** Probe executable/version facts asynchronously with a deadline and one confirmed executable snapshot per launch. Failed hook writes/removals hold launch, preserve foreign configuration and are checked consistently by create, fork, restart, retarget, restore and upgrades. Do not memoize an unavailable version as a permanent answer.+1. **Complete native identity and retry.** Exact transcript lookup and native lock/descriptor enumeration are landed. Durable home adoption and its staged registry batch are [landed](2026-10-10-durable-home-adoption.md). Saved-binding file/header/root evidence and visible retry are [landed](2026-10-10-saved-binding-evidence.md). Atomic registration and live hook ownership are [landed](2026-10-10-native-hook-admission.md). Stop/Resume/Close transcript authority is [landed as #1139](2026-10-10-control-transcript-authority.md); reviewed history deletion is [landed as #1144](2026-10-10-native-history-consumers.md); [Change agent handoff authority](2026-10-10-native-handoff-authority.md) is landed as #1145 (`ea4e800b5`, October 10 15:13:53 UTC). Restart-persistent hook delivery, remaining saved-home consumers and legacy native-client acknowledgement/order still require migration. The [catalog audit](2026-10-09-native-home-catalog.md) records its fresh-evidence boundary and required remaining caller/writer migration. The native Hermes pool is landed; optional home promotion and shared handle-cache lifetime still need their authority/resource audit. An unreadable or truncated pool cannot prove absence or uniqueness. Every binding entry and transcript poll retains pending work, isolates a failed lookup, and retries without blocking sibling sessions or readiness. Surface the hold reason through the shared session state.+2. **Complete native launch preparation.** Probe executable/version facts asynchronously with a deadline and one confirmed executable snapshot per launch. The [asynchronous version-probe change](2026-10-10-native-version-probes.md) covers bounded subprocesses and concurrent observations/installers; the whole-launch snapshot, unknown-result policy and durable hook preparation remain open. Failed hook writes/removals hold launch, preserve foreign configuration and are checked consistently by create, fork, restart, retarget, restore and upgrades. Do not memoize an unavailable version as a permanent answer.3. **Durable manual lifecycle intent and mutation authority.** Preserve create/fork/restart/retarget requests across unavailable services and daemon restart. Publish generated configuration atomically after dependencies are ready. Check immutable session ownership after every relevant await and before native writes, signals and publication. Reconcile unconfirmed OpenCode v2 mutations read-only; unreadable catalogs must not authorize mutation. Cover v1 missing-row/rollback cases and report a confirmed native change followed by failed respawn truthfully.4. **Close, turns and input stay in core.** Audit OpenCode v2 Close checkpointing against its current conversation store; unavailable checkpoint/activity evidence keeps the live session with its reason. Finish per-engine Stop/turn facts, authority across asynchronous drains, Cursor pending-task persistence, agy backstop control, input verification declarations, and Pi header/argv and unwritten-conversation handling.5. **Final architecture acceptance.** Exercise startup, discovery, binding, launch, resume, Stop, hook admission, turn closing and Close with required services absent, stalled, disconnected and recovered. Verify readiness remains independent, pending work survives without partial writes or archival, and stale completions cannot affect a replacement session. Run the relevant coverage gates, unchanged goldens and assertion-failing wiring mutations, affected private e2e/chaos lanes, and matched runtime-cost measurements. Obtain independent review and merge every completed change.diff --git a/docs/research/2026-10-10-native-handoff-authority.md b/docs/research/2026-10-10-native-handoff-authority.mdindex d2bee9a95..ddc25f19c 100644--- a/docs/research/2026-10-10-native-handoff-authority.md+++ b/docs/research/2026-10-10-native-handoff-authority.md@@ -294,3 +294,29 @@ independent review overlap that work; their intervals above are not additive elatime. Additional clean completed worktrees were narrowed to their tracked CLIcontents to recover disk space, preserving commits and private evidence. The two-GiBguard was unchanged. Merge and publication remain zero at this update.++## Final acceptance and merge++[PR #1145](https://github.com/autonomous-ai/openharness/pull/1145) merged as+`ea4e800b5f19704ab2f4663196c3949bb9b6aaa4` at October 10 15:13:53 UTC. Independent+review approved exact head `090286b8a4ac993f60643270f1ba1dbcc19c3ddf` against base+`cb242cf4c7d21b7b7cd95ac727fedb30317e9878`. The merge helper confirmed that both the+reviewed target and full tested trees match the merged tree.++[Automatic CI](https://github.com/autonomous-ai/openharness/actions/runs/38061562470)+passed all selected CLI, Desktop and TUI checks, including `ci/required`.+[Complete e2e acceptance](https://github.com/autonomous-ai/openharness/actions/runs/38061467828)+passed all eight Linux shards, macOS full-disk cases and the inventory completeness+summary. The final local receipt `20261010T145228.906119Z-66762` passed typecheck,+2,319 core cases with per-file 100% coverage, 265 harnessd cases and one existing+skip with 100% coverage, architecture, all 81 standalone hook cases and both real+private offline-registration cases. Earlier runtime goldens and all 15 assertion-+failing mutations remain applicable to unchanged publication code.++Resumed implementation/diagnosis occupied 14:13–14:52 UTC; local validation overlapped+14:18–14:55; independent review overlapped those phases. Remote acceptance waiting+began with the 14:53 push; the final e2e run occupied 14:54:23–15:12:35. Merge+verification occupied 15:13:40–15:13:53, with receipt+`20261010T151340.191117Z-merge-1145`. These overlapping intervals are not summed.+Publication remains zero. Remaining native delivery, launch and lifecycle authority+work is listed in the completion checklist; this merge does not declare it complete.diff --git a/docs/research/2026-10-10-native-version-cost.json b/docs/research/2026-10-10-native-version-cost.jsonnew file mode 100644index 000000000..22e7add06--- /dev/null+++ b/docs/research/2026-10-10-native-version-cost.json@@ -0,0 +1,133 @@+{+ "scope": "Native-version component only; private fixture executables, parent-process CPU and peak RSS. Same host and pinned Node. No startup or vendor-engine performance claim.",+ "baseline": "ea4e800b5f19704ab2f4663196c3949bb9b6aaa4",+ "candidate_base": "564460afacc66abbc42e254758fa5e3c76e9b3ff",+ "candidate_diff_sha256": "ec94697db4569c6d3e8288c1ba90c731999d06846c6c5538d03dfc6eac9ea085",+ "measurements": [+ {+ "revision": "former",+ "workload": "healthy",+ "iterations": 10,+ "commands": 10,+ "latencyMs": {+ "median": 55.837291999999934,+ "max": 786.685905+ },+ "callbackDelayMs": {+ "median": 56.646866000000045,+ "max": 786.839451+ },+ "elapsedMs": 1302.72547,+ "parentCpuMs": 10.868,+ "peakRssMiB": 77.69921875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "revision": "candidate",+ "workload": "healthy",+ "iterations": 10,+ "commands": 10,+ "latencyMs": {+ "median": 54.41744400000016,+ "max": 594.1794380000001+ },+ "callbackDelayMs": {+ "median": 2.1663409999999885,+ "max": 4.2508689999999945+ },+ "elapsedMs": 1097.88018,+ "parentCpuMs": 42.896,+ "peakRssMiB": 73.53515625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "revision": "former",+ "workload": "slow",+ "iterations": 10,+ "commands": 10,+ "latencyMs": {+ "median": 156.93449499999997,+ "max": 717.036659+ },+ "callbackDelayMs": {+ "median": 157.0008560000001,+ "max": 717.180795+ },+ "elapsedMs": 2135.671639,+ "parentCpuMs": 10.378,+ "peakRssMiB": 79.32421875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "revision": "candidate",+ "workload": "slow",+ "iterations": 10,+ "commands": 10,+ "latencyMs": {+ "median": 157.0257590000001,+ "max": 688.707009+ },+ "callbackDelayMs": {+ "median": 1.8762229999999818,+ "max": 2.7413779999999974+ },+ "elapsedMs": 2107.45578,+ "parentCpuMs": 75.195,+ "peakRssMiB": 78.66796875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "revision": "former",+ "workload": "cached",+ "iterations": 500,+ "commands": 1,+ "latencyMs": {+ "median": 0.03675199999997858,+ "max": 0.11368400000003476+ },+ "callbackDelayMs": {+ "median": 1.335805000000164,+ "max": 1.5336849999999913+ },+ "elapsedMs": 664.9937649999999,+ "parentCpuMs": 57.971,+ "peakRssMiB": 79.6328125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "revision": "candidate",+ "workload": "cached",+ "iterations": 500,+ "commands": 1,+ "latencyMs": {+ "median": 0.045546000000058484,+ "max": 0.17663900000002286+ },+ "callbackDelayMs": {+ "median": 1.3213600000001406,+ "max": 1.5952459999999746+ },+ "elapsedMs": 648.9071530000001,+ "parentCpuMs": 54.493,+ "peakRssMiB": 78.03125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ }+ ],+ "candidate_inputs": {+ "cli/src/engines/kit/nativeVersion.ts": "d45ea7439bcbda938940db040e1adb44fe5fab0a97fe14288a660f206422f5da",+ "cli/src/lib/binaryOnPath.ts": "9be2523e1379ee2653c8a062b9085fefd9e10a709732ca95b19ac3506b3a291f",+ "cli/scripts/handoff-2026-10-08/native-version-cost.ts": "50f5f8418d579557dcf7ce3551d4eb32b461c560056dea1ba58c6fa0d08e4db8"+ }+}diff --git a/docs/research/2026-10-10-native-version-probes.md b/docs/research/2026-10-10-native-version-probes.mdnew file mode 100644index 000000000..9e27ed541--- /dev/null+++ b/docs/research/2026-10-10-native-version-probes.md@@ -0,0 +1,78 @@+# Asynchronous native version probes++An OpenCode launch could run a synchronous five-second `--version` command on the+core event loop. Its executable resolver could first run a synchronous login shell+for another five seconds. A slow installation therefore blocked unrelated sessions'+Stop requests, listings and timers. This change makes both subprocesses asynchronous+and bounded, while retaining native launch control in eager code.++Each probe selects its executable once and verifies the same pathname, realpath and+file identity after the child answers. Replacement discards the observation. The+child has a deadline, a 64 KiB output limit and closed stdin. Overlapping probes may+return their own verified observations, but only the current attempt may publish to+the memo. An obsolete hook installer cannot write; same-port concurrent callers join+the current installation under a fixed follow-up deadline. A changed port or expired+join refuses preparation. All version callers await the result, and startup contains+asynchronous installer failures while allowing sibling installers to run.++## Compatibility and fault evidence++Commit `564460afacc66abbc42e254758fa5e3c76e9b3ff` recorded the former code before+the move. `nativeVersion.golden.spec.ts` exercises real core pre-spawn installation+and records version reads plus exact generated v1/v2 plugin contents on pinned Linux+and macOS. The clock, timezone and private paths are fixed; host executables are+forbidden. Its artifact and the existing OpenCode launch artifact stay unchanged.++Private regression tests cover event-loop responsiveness, resolver substitution,+executable replacement, missing replies, output floods, stdin EOF, cache completion+order, obsolete plugin writes and simultaneous creates through the actual creator+and installer. Independent review identified the production shell fallback, stdin,+cache and installation races; the corresponding assertions failed before correction.+The daemon e2e uses separate private connections because each connection deliberately+serializes requests. A fake version child waits for a release file while the other+connection lists and stops a live sibling. Both operations must finish before the+probe is released. This proves Stop/list responsiveness, not a fresh discovery scan.++`cli/scripts/handoff-2026-10-08/mutate-native-version.py` deliberately breaks the+golden wiring and the new fault protections in an owned disposable worktree. Only+assertion failures count. The existing OpenCode launch mutation recipe follows the+new awaited composition. Final validation requires types, architecture, affected+specs, per-file core/services and harnessd coverage, the private e2e lane, automatic+Linux CI and independent review of the committed head and current base.++## Matched component cost++[The measurements](2026-10-10-native-version-cost.json) compare `ea4e800b5` with the+candidate using Node 22.23.2 on the same macOS x64 host. Each workload/revision runs+in a fresh process. A private executable reports v2 immediately or after 100 ms;+cached reads reuse one successful observation. No real daemon or vendor executable+runs. The recipe is `cli/scripts/handoff-2026-10-08/native-version-cost.ts`.++| Workload | Probe median, before → after | Timer delay median, before → after | Parent CPU total, before → after | Peak RSS, before → after |+| --- | --- | --- | --- | --- |+| 10 healthy probes | 55.84 → 54.42 ms | 56.65 → 2.17 ms | 10.87 → 42.90 ms | 77.70 → 73.54 MiB |+| 10 probes with 100 ms delay | 156.93 → 157.03 ms | 157.00 → 1.88 ms | 10.38 → 75.20 ms | 79.32 → 78.67 MiB |+| 500 cached reads | 0.037 → 0.046 ms | 1.34 → 1.32 ms | 57.97 → 54.49 ms | 79.63 → 78.03 MiB |++The useful improvement is that unrelated callbacks run during a slow probe. Probe+latency remains dominated by the child, and cached reads add identity checks. CPU+includes the one-millisecond measurement timer, which can now run while a child is+pending; these small samples do not establish production CPU or full-startup cost.+Cold-start maxima are noisy and retained in the artifact. No numerical performance+gate is inferred from this run. The reported median uses the upper-middle observation+for an even sample count.++## Remaining completion scope++This is a partial implementation of launch-preparation item 2 in the+[completion checklist](2026-10-09-daemon-core-completion.md). It does not yet carry one+confirmed executable through the entire launch, change permanent caching of unknown+versions, or make hook write/removal failures durable holds. Those behaviors need+their own former-code observations and failure tests. Startup still awaits bounded+native installation; service readiness remains a separate boundary. Manual lifecycle+intent persistence and the remaining Stop/Close authority audit are still required.++Work on this phase began October 10 at 15:14 UTC, after #1145 merged. Implementation,+diagnosis and review overlapped with local validation; cost measurement completed at+15:45 UTC. Final validation, CI waiting and merge time belong in the PR evidence.+Publication is zero; no release is authorized.