Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Keep native hook installation independent of optional code (#1111)

Deeb6e15e10c7de
diff --git a/cli/e2e/eagerHooks.e2e.ts b/cli/e2e/eagerHooks.e2e.ts
new file mode 100644
index 000000000..9ea158eac
--- /dev/null
+++ b/cli/e2e/eagerHooks.e2e.ts
@@ -0,0 +1,98 @@
+/** 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 { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { afterAll, afterEach, beforeAll, expect, it, onTestFailed } from 'vitest'
+import { readLeanBundle } from '../src/harnessd/leanBundle.js'
+import { LocalClient } from './harness/client.js'
+import { assertHooksContained, CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+import { withLean } from './harness/release.js'
+
+let scratch = '', bundle = ''
+let daemon: IsolatedDaemon | undefined, client: LocalClient | undefined
+beforeAll(() => {
+ scratch = mkdtempSync(join(tmpdir(), 'eager-hooks-'))
+ bundle = join(scratch, 'build', 'cli.js')
+ execFileSync(process.execPath, ['build-bundle.mjs'], { cwd: CLI_ROOT,
+ env: { ...process.env, BUNDLE_OUT_DIR: dirname(bundle) }, stdio: 'pipe' })
+}, 120_000)
+afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })
+afterAll(() => { if (scratch) rmSync(scratch, { recursive: true, force: true }) })
+
+it('refuses a native hook destination outside the test, including the OpenCode sibling directory', async () => {
+ const d = daemon = await IsolatedDaemon.create()
+ d.env.HOOK_INSTALL_ENGINES = 'opencode'
+ expect(() => assertHooksContained(d.root, d.env)).toThrow('OPENCODE_PLUGIN_DIR')
+ d.env.OPENCODE_PLUGIN_DIR = d.root
+ expect(() => assertHooksContained(d.root, d.env)).toThrow('OpenCode plugin parent')
+ d.env.OPENCODE_PLUGIN_DIR = join(d.root, 'opencode', 'plugin')
+ expect(() => assertHooksContained(d.root, d.env)).not.toThrow()
+ d.env.HOOK_INSTALL_ENGINES = 'unknown'
+ expect(() => assertHooksContained(d.root, d.env)).toThrow('supported hook engines')
+})
+
+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))!
+ const files = Object.fromEntries([...lean.files].map(([name, value]) => [name, value.toString('utf8')]))
+ const chunks = Object.keys(files).filter(name => /^core-hooks-/.test(name))
+ expect(chunks).toHaveLength(1)
+ if (mode === 'missing') delete files[chunks[0]!]
+ else files[chunks[0]!] = "console.error('[fixture] legacy hooks stalled'); await new Promise(() => {});\n"
+ const script = join(scratch, mode, 'cli.js'); mkdirSync(dirname(script), { recursive: true })
+ writeFileSync(script, withLean(readFileSync(bundle, 'utf8'), files), { mode: 0o755 })
+ const d = daemon = await IsolatedDaemon.create({ scriptPath: script, env: { HARNESS_CONNECTIONS_PORT: '0' } })
+ onTestFailed(() => console.log(d.log()))
+ const root = join(d.root, 'native')
+ const homes: Record<string, string> = {
+ CURSOR_CONFIG_DIR: join(root, 'cursor'), CURSOR_DATA_DIR: join(root, 'cursor-data'),
+ OPENCODE_PLUGIN_DIR: join(root, 'opencode', 'plugin'), OPENCODE_DATA_DIR: join(root, 'opencode-data'),
+ KILO_PLUGIN_DIR: join(root, 'kilo', 'plugin'), PI_HOME: join(root, 'pi'),
+ AMP_PLUGIN_DIR: join(root, 'amp', 'plugins'), AMP_SESSIONS_DIR: join(root, 'amp-sessions'),
+ HERMES_HOME: join(root, 'hermes'), DEVIN_CONFIG_PATH: join(root, 'devin', 'config.json'),
+ COMMANDCODE_HOME: join(root, 'commandcode'), GROK_HOME: join(root, 'grok'),
+ AGY_CONFIG_DIR: join(root, 'agy'), COPILOT_HOME: join(root, 'copilot'),
+ }
+ Object.assign(d.env, homes, { HOOK_INSTALL_ENGINES: 'claude,codex,cursor,opencode,kilo,pi,amp,hermes,devin,commandcode,grok,agy,copilot' })
+ mkdirSync(homes.HERMES_HOME!, { recursive: true })
+ writeFileSync(join(homes.HERMES_HOME!, 'config.yaml'), 'model: fixture\n')
+ const binary = join(d.root, 'bin', 'opencode'); d.env.OPENCODE_PATH = binary
+ writeFileSync(binary, `#!${process.execPath}
+if (process.argv.includes('--version')) { console.log('opencode v2.0.18'); process.exit(0) }
+if (process.argv.includes('--help')) { console.log('--auto --session'); process.exit(0) }
+process.title = ('opencode --session ses_' + process.pid).padEnd(160);
+console.log('┃'); setInterval(() => {}, 1000);
+`, { mode: 0o755 })
+ await d.start()
+ expect(d.log()).not.toContain('[fixture] legacy hooks stalled')
+ for (const file of ['cursor/hooks.json', 'opencode/plugins/launcher-register/tui.js', 'kilo/plugin/launcher-register.js',
+ 'pi/agent/extensions/launcher-register.ts', 'amp/plugins/launcher-register.ts', 'hermes/config.yaml',
+ 'devin/config.json', 'commandcode/settings.json', 'grok/hooks/harness.json', 'agy/hooks.json', 'copilot/hooks/harness.json']) {
+ expect(readFileSync(join(root, file), 'utf8'), file).toContain(String(d.port))
+ }
+ const c = client = await LocalClient.connect(d)
+ const row = async (id: string) => ((await c.request('agents_list', { includeStopped: true })).agents as Array<Record<string, any>>).find(one => one.id === id)
+ const active = (id: string) => until('a native process to bind without optional hooks', async () => {
+ const agent = await row(id); return agent?.status === 'active' && agent.sessionId ? agent : null
+ }, 30_000, 100)
+ const create = async (kind: string) => {
+ const cwd = join(d.projectsDir, kind); mkdirSync(cwd)
+ const result = await c.request('agent_create', { engine: kind, cwd, bypassPermission: true }, 30_000)
+ expect(result.error, JSON.stringify(result)).toBeUndefined()
+ return active(result.agent.id)
+ }
+ const native = await create('opencode')
+ const sibling = await create(engine)
+ const started = c.next(frame => frame.type === 'turn_started' && frame.agentId === sibling.id, 30_000)
+ c.send('message', { agentId: sibling.id, content: '!slow 8000' }); await started
+ expect((await c.request('agent_delete', { agentId: sibling.id }, 45_000)).error).toBeUndefined()
+ await until('Stop preserves the conversation', async () => (await row(sibling.id))?.status === 'stopped', 20_000)
+ expect((await c.request('agent_resume', { agentId: sibling.id }, 45_000)).error).toBeUndefined()
+ expect((await active(sibling.id)).sessionId).toBe(sibling.sessionId)
+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === sibling.id, 30_000)
+ c.send('message', { agentId: sibling.id, content: 'after isolated hooks' }); await ended
+ expect((await active(native.id)).sessionId).toBe(native.sessionId)
+ expect(d.coresStarted()).toBe(1)
+ expect((await fetch(`http://127.0.0.1:${d.port}/api/health`)).ok).toBe(true)
+ }, 150_000)
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.ts
index d799653a3..65bde350b 100644
--- a/cli/e2e/harness/daemon.ts
+++ b/cli/e2e/harness/daemon.ts
@@ -105,8 +105,14 @@ const inside = (root: string, path: string): boolean => {
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
}
-/** The engines whose hooks a daemon under test may install: the two the fake engines stand in for. */
-const HOOK_ENGINES = new Set(['claude', 'codex'])
+/** Native-hook acceptance may opt in only with every destination explicitly under its private root. */
+const NATIVE_HOOK_PATHS: Record<string, readonly string[]> = {
+ cursor: ['CURSOR_CONFIG_DIR', 'CURSOR_DATA_DIR'], opencode: ['OPENCODE_PLUGIN_DIR'],
+ kilo: ['KILO_PLUGIN_DIR'], pi: ['PI_HOME'], amp: ['AMP_PLUGIN_DIR', 'AMP_SESSIONS_DIR'],
+ hermes: ['HERMES_HOME'], devin: ['DEVIN_CONFIG_PATH'], commandcode: ['COMMANDCODE_HOME'],
+ grok: ['GROK_HOME'], agy: ['AGY_CONFIG_DIR'], copilot: ['COPILOT_HOME'],
+}
+const HOOK_ENGINES = new Set(['claude', 'codex', ...Object.keys(NATIVE_HOOK_PATHS)])
/** The shell profiles a login shell in a pane reads, where a person moves an engine's home. */
const PROFILES = { ZDOTDIR: ['.zshenv', '.zprofile', '.zshrc', '.zlogin'], HOME: ['.bash_profile', '.bash_login', '.profile', '.bashrc'] }
@@ -122,7 +128,7 @@ export function assertHooksContained(root: string, env: NodeJS.ProcessEnv): void
if (env.DISABLE_HOOK_INSTALL === 'true') return
const engines = (env.HOOK_INSTALL_ENGINES ?? '').split(',').map((name) => name.trim()).filter(Boolean)
if (!engines.length || engines.some((name) => !HOOK_ENGINES.has(name))) {
- throw new Error(`HOOK_INSTALL_ENGINES is ${env.HOOK_INSTALL_ENGINES ?? 'unset'}: a daemon under test installs Claude Code's and Codex's hooks alone (claude,codex)`)
+ throw new Error(`HOOK_INSTALL_ENGINES is ${env.HOOK_INSTALL_ENGINES ?? 'unset'}: a daemon under test must name supported hook engines with isolated destinations`)
}
const refuse = (what: string, path: string | undefined): never => {
throw new Error(`${what} is ${path ?? 'unset'}: a daemon under test installs hooks only inside ${root}`)
@@ -134,6 +140,9 @@ export function assertHooksContained(root: string, env: NodeJS.ProcessEnv): void
check('CODEX_HOME', env.CODEX_HOME)
if (env.CLAUDE_CONFIG_DIR !== undefined) check('CLAUDE_CONFIG_DIR', env.CLAUDE_CONFIG_DIR)
check('ZDOTDIR', env.ZDOTDIR)
+ for (const engine of engines) for (const name of NATIVE_HOOK_PATHS[engine] ?? []) check(name, env[name])
+ // OpenCode's TUI plugin is a sibling of its legacy plugin directory.
+ if (engines.includes('opencode')) check('OpenCode plugin parent', dirname(env.OPENCODE_PLUGIN_DIR!))
// Not a hook, but what routes every hook: a record outside the root would send the person's hooks here.
if (env.HARNESS_HOOK_ROUTES_DIR !== undefined) check('HARNESS_HOOK_ROUTES_DIR', env.HARNESS_HOOK_ROUTES_DIR)
for (const [folder, names] of Object.entries(PROFILES) as Array<[keyof typeof PROFILES, string[]]>) {
diff --git a/cli/e2e/opencodeLaunchCost.e2e.ts b/cli/e2e/opencodeLaunchCost.e2e.ts
index 53b4bf1d8..746419819 100644
--- a/cli/e2e/opencodeLaunchCost.e2e.ts
+++ b/cli/e2e/opencodeLaunchCost.e2e.ts
@@ -1,4 +1,5 @@
/** Opt-in baseline/candidate bundle measurement; OPENCODE_COST_ROOT contains both cli.js files.
+ * OPENCODE_COST_NATIVE_HOOKS=1 includes all thirteen native installers at startup.
* Private daemons and fake native processes only. Run without other heavy validation. */
import { execFileSync } from 'node:child_process'
import { mkdirSync, writeFileSync } from 'node:fs'
@@ -18,6 +19,19 @@ it.runIf(Boolean(process.env.OPENCODE_COST_ROOT))('samples the same cold daemon
const d = await IsolatedDaemon.create({ scriptPath: join(root, which, 'cli.js'), env: { HARNESS_CONNECTIONS_PORT: '0' } })
let client: LocalClient | undefined
try {
+ if (process.env.OPENCODE_COST_NATIVE_HOOKS === '1') {
+ const home = join(d.root, 'native')
+ Object.assign(d.env, {
+ HOOK_INSTALL_ENGINES: 'claude,codex,cursor,opencode,kilo,pi,amp,hermes,devin,commandcode,grok,agy,copilot',
+ CURSOR_CONFIG_DIR: join(home, 'cursor'), CURSOR_DATA_DIR: join(home, 'cursor-data'),
+ KILO_PLUGIN_DIR: join(home, 'kilo', 'plugin'), PI_HOME: join(home, 'pi'),
+ AMP_PLUGIN_DIR: join(home, 'amp', 'plugins'), AMP_SESSIONS_DIR: join(home, 'amp-sessions'),
+ HERMES_HOME: join(home, 'hermes'), DEVIN_CONFIG_PATH: join(home, 'devin', 'config.json'),
+ COMMANDCODE_HOME: join(home, 'commandcode'), GROK_HOME: join(home, 'grok'),
+ AGY_CONFIG_DIR: join(home, 'agy'), COPILOT_HOME: join(home, 'copilot'),
+ })
+ mkdirSync(d.env.HERMES_HOME!, { recursive: true }); writeFileSync(join(d.env.HERMES_HOME!, 'config.yaml'), 'model: fixture\n')
+ }
const bin = join(d.root, 'bin', 'opencode'); d.env.OPENCODE_PATH = bin
d.env.OPENCODE_PLUGIN_DIR = join(d.root, 'opencode', 'plugin')
writeFileSync(bin, `#!${process.execPath}
@@ -41,5 +55,5 @@ console.log('┃'); setInterval(() => {}, 1000);
samples.push({ bundle: which, readyMs, atReady, launches })
} finally { client?.close(); await d.close() }
}
- writeFileSync(join(root, 'cost.json'), JSON.stringify({ node: process.version, platform: process.platform, tmux: execFileSync('tmux', ['-V'], { encoding: 'utf8' }).trim(), samples }, null, 2) + '\n')
+ writeFileSync(join(root, 'cost.json'), JSON.stringify({ nativeHooks: process.env.OPENCODE_COST_NATIVE_HOOKS === '1', node: process.version, platform: process.platform, tmux: execFileSync('tmux', ['-V'], { encoding: 'utf8' }).trim(), samples }, null, 2) + '\n')
}, 240000)
diff --git a/cli/scripts/handoff-2026-10-08/mutate-native-hooks.py b/cli/scripts/handoff-2026-10-08/mutate-native-hooks.py
new file mode 100644
index 000000000..b4d3dcb83
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-native-hooks.py
@@ -0,0 +1,53 @@
+"""Break native hook declarations and core wiring. Only assertion failures count as kills."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+golden = 'src/engines/otherHooks.golden.spec.ts'
+architecture = 'src/architecture.spec.ts'
+wiring = 'src/core/engines/hooks.spec.ts'
+mutations = [
+ ('wrong JSON event', 'src/engines/cursor/contract.ts', '"beforeSubmitPrompt"', '"afterSubmitPrompt"', golden),
+ ('fail-closed notification', 'src/engines/cursor/contract.ts', '"failClosed": false', '"failClosed": true', golden),
+ ('foreign JSON removed', 'src/engines/kit/nativeHookSettings.ts', 'blocks.filter(block => !isOurs(block))', 'blocks.filter(() => false)', golden),
+ ('wrong plugin port', 'src/engines/nativeHooks.ts', 'port: String(port)', "port: '19475'", golden),
+ ('wrong OpenCode generation', 'src/engines/nativeHooks.ts', 'opencodeMajorVersion() === 1', '(opencodeMajorVersion() ?? 0) >= 1', golden),
+ ('legacy plugin removal lost', 'src/engines/opencode/contract.ts', "contains: 'export const MachineRegister ='", "contains: 'export const NotOurPlugin ='", golden),
+ ('foreign YAML overwritten', 'src/engines/kit/nativeHookYaml.ts', 'if (foreignHooks)', 'if (false)', golden),
+ ('profile config missed', 'src/engines/hermes/contract.ts', "directory: 'profiles', file: 'config.yaml'", "directory: 'profiles', file: 'not-config.yaml'", golden),
+ ('approval event omitted', 'src/engines/kit/nativeHookYaml.ts', 'for (const event of rule.events) {', 'for (const event of rule.events.slice(1)) {', golden),
+ ('wrong installer wired', 'src/core/engines/hooks.ts', "['kilo', nativeHooks.installKiloPlugin]", "['kilo', port => nativeHooks.installKiloPlugin(port + 1)]", golden),
+ ('pre-spawn installation skipped', 'src/core/engines/hooks.ts', ' nativeHooks.installOpencodePlugin(port)', ' void port', wiring),
+ ('lazy startup restored', 'src/core/engines/hooks.ts', ' for (const [vendor, install] of OTHER_INSTALLERS)', " await (await import('../../engines/inProcess.js')).loadEngine('hooks')\n for (const [vendor, install] of OTHER_INSTALLERS)", architecture),
+]
+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}
+for name in ['TMUX', 'TMUX_PANE', 'RECORD_OTHER_ENGINES_GOLDEN']:
+ env.pop(name, None)
+
+
+def run(specs):
+ return subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', *specs, '--maxWorkers=1'],
+ cwd=cli, env=env, capture_output=True, text=True, timeout=180)
+
+
+baseline = run([golden, architecture, wiring])
+if baseline.returncode:
+ print(baseline.stdout + baseline.stderr)
+ raise SystemExit('baseline failed; no mutants ran')
+print('unchanged baseline passed', flush=True)
+for label, relative, before, after, spec in mutations[int(os.environ.get('MUTATION_START', '0')):]:
+ 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])
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError' not in output:
+ print(output)
+ raise SystemExit(f'{label}: not caught by an assertion')
+ print(f'{label}: caught by assertion', flush=True)
+ finally:
+ path.write_text(original)
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index 38287af74..31a60d792 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -430,9 +430,8 @@ describe('the daemon\'s shape', () => {
for (const [entry, batch] of FACETS_FREE_OF_THEM) {
expect([...closureOf(entry).keys()].filter(theirs), `${entry}, free of their code since ${batch}`).toEqual([])
}
- // (o2) The start's hook step loads the other engines' installers through the loader; since (o6) it reaches none
- // of their code at all (above).
- expect(closureOf('core/engines/hooks.ts').has('lib/hooks.ts'), 'core/engines/hooks.ts loads lib/hooks.ts through engines/inProcess.ts').toBe(false)
+ // Native installation is eager, composed from declarations; the legacy entry is only an alias.
+ expect(closureOf('core/engines/hooks.ts').has('lib/hooks.ts')).toBe(false)
// What an engine declares is data the kit reads: its own walk reaches the kit, the engines' types and the
// environment, and nothing of any engine's code.
const contracts = [...closure.keys()].filter((file) => /^engines\/\w+\/contract\.ts$/.test(file))
@@ -452,6 +451,15 @@ describe('the daemon\'s shape', () => {
}
})
+ it('native hook installation never loads optional code and reaches only engine declarations', () => {
+ for (const entry of ['core/engines/hooks.ts', 'engines/nativeHooks.ts', 'engines/kit/nativeHookSettings.ts',
+ 'engines/kit/nativeHookYaml.ts', 'engines/kit/nativeHookHomes.ts', 'engines/kit/nativePlugin.ts']) {
+ const imports = importsFor(entry, readFileSync(join(SRC, entry), 'utf8'))
+ expect(imports.filter(one => one.dynamic || /inProcess\.js$/.test(one.from)), entry).toEqual([])
+ expect([...closureOf(entry).keys()].filter(theirs), entry).toEqual([])
+ }
+ })
+
it('native launch control is eager and reaches only engine declarations', () => {
for (const entry of ['core/agents/create.ts', 'core/agents/fork.ts', 'core/agents/retarget.ts',
'core/agents/launch.ts', 'core/agents/launches.ts', 'core/agents/externalPreflight.ts',
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index 19f485bec..89ac15373 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -64,7 +64,7 @@ export interface CreateAgentDeps {
/** Whether engine hooks are installed at all (DISABLE_HOOK_INSTALL). */
hooksDisabled: boolean
/** OpenCode's plugin, installed again before an OpenCode spawn (core/engines/hooks.ts
- * `installOpencodePluginBeforeSpawn`): false when the other engines' installers could not be loaded. */
+ * `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
@@ -238,8 +238,7 @@ export function createAgentCreator({
if (codexHome && !hooksDisabled) engineHooks.codex.installIn(hookPort, codexHome)
// OpenCode may have upgraded from 1.x to 2.x while this daemon was running. Its new TUI must
// not discover our old server plugin; the cached version probe changes with the executable.
- // Its installer is loaded with the other engines' (engines/inProcess.ts): one that could not be loaded
- // refuses the create, since an OpenCode with no plugin never tells the daemon its session.
+ // Native installation is eager. A plugin is how this engine tells the daemon its session.
if (engine === 'opencode' && !hooksDisabled && !await installOpencodePlugin(hookPort)) {
const detail = 'OpenCode\'s plugin installer could not be loaded'
console.warn(`[agent] create opencode refused · ${detail}`)
diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.ts
index 63d273b64..3c1370b47 100644
--- a/cli/src/core/engines/hooks.spec.ts
+++ b/cli/src/core/engines/hooks.spec.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import * as hooks from '../../lib/hooks.js'
+import * as hooks from '../../engines/nativeHooks.js'
import { engineHooks } from '../../engines/hooks.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { processRows } from '../../lib/terminalAgentDiscovery.js'
@@ -19,14 +19,14 @@ vi.mock('../../lib/engineHomes.js', () => ({
adoptHomes: vi.fn(() => ({ claude: null, codex: null })),
movedHomes: vi.fn(() => []),
}))
-// The other engines' installers load through the loader; a test may make that load fail.
-const loading = vi.hoisted(() => ({ fail: false }))
+// Native installation must finish even when optional interpretation cannot be loaded.
+const loading = vi.hoisted(() => ({ stalled: false }))
vi.mock('../../engines/inProcess.js', async (real) => {
const actual = await real<typeof import('../../engines/inProcess.js')>()
- return { ...actual, loadEngine: vi.fn((name: 'hooks') => loading.fail ? Promise.resolve(null) : actual.loadEngine(name)) }
+ return { ...actual, loadEngine: vi.fn(() => loading.stalled ? new Promise(() => {}) : Promise.resolve(null)) }
})
vi.mock('../../lib/terminalAgentDiscovery.js', async (real) => ({ ...await real<object>(), processRows: vi.fn(async () => []) }))
-vi.mock('../../lib/hooks.js', async (real) => ({
+vi.mock('../../engines/nativeHooks.js', async (real) => ({
...await real<object>(),
installCursorHooks: vi.fn(),
installOpencodePlugin: vi.fn(),
@@ -343,29 +343,29 @@ describe('installing every engine\'s hooks', () => {
hooks.installCopilotHooks,
]
beforeEach(() => { vi.spyOn(console, 'warn').mockImplementation(() => {}) })
- afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); loading.fail = false })
+ afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); loading.stalled = false })
- it('points all thirteen at the bound port, the other engines\' through their installers loaded once', async () => {
+ it('points all thirteen at the bound port without loading optional code', async () => {
await installEngineHooks(4242)
for (const install of installs) expect(install).toHaveBeenCalledWith(4242)
expect(console.warn).not.toHaveBeenCalled()
- expect(loadEngine).toHaveBeenCalledTimes(1)
- expect(loadEngine).toHaveBeenCalledWith('hooks')
+ expect(loadEngine).not.toHaveBeenCalled()
})
- it('installs OpenCode\'s plugin before an OpenCode spawn, and says when its installer could not be loaded', async () => {
+ it('installs OpenCode\'s plugin before a spawn without loading optional code', async () => {
expect(await installOpencodePluginBeforeSpawn(4242)).toBe(true)
expect(hooks.installOpencodePlugin).toHaveBeenCalledWith(4242)
- loading.fail = true
- expect(await installOpencodePluginBeforeSpawn(4242)).toBe(false)
- expect(hooks.installOpencodePlugin).toHaveBeenCalledTimes(1)
+ loading.stalled = true
+ expect(await installOpencodePluginBeforeSpawn(4242)).toBe(true)
+ expect(hooks.installOpencodePlugin).toHaveBeenCalledTimes(2)
+ expect(loadEngine).not.toHaveBeenCalled()
})
- it('in the order they always ran: Claude Code and Codex in line, then the others, as one awaited step', async () => {
+ 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)) })
const done = installEngineHooks(4242)
- expect(order).toEqual(['0', '1'])
+ expect(order).toEqual(installs.map((_, index) => String(index)))
await done
expect(order).toEqual(installs.map((_, index) => String(index)))
})
@@ -384,16 +384,12 @@ describe('installing every engine\'s hooks', () => {
expect(hooks.installCursorHooks).not.toHaveBeenCalled()
})
- it('with the other engines\' installers unable to load: theirs skipped and named, Claude Code\'s and Codex\'s installed', async () => {
- loading.fail = true
+ it.each([false, true])('installs every vendor with optional imports unavailable (stalled=%s)', async (stalled) => {
+ loading.stalled = stalled
await installEngineHooks(4242, { environment: {} })
- expect(engineHooks.claude.install).toHaveBeenCalledWith(4242)
- expect(engineHooks.codex.install).toHaveBeenCalledWith(4242)
- for (const install of installs.slice(2)) expect(install).not.toHaveBeenCalled()
- for (const vendor of ['cursor', 'opencode', 'kilo', 'pi', 'amp', 'hermes', 'devin', 'commandcode', 'grok', 'agy', 'copilot']) {
- expect(console.warn).toHaveBeenCalledWith(`[hooks] ${vendor} install skipped · its installer could not be loaded`)
- }
- expect(console.warn).toHaveBeenCalledTimes(11)
+ for (const install of installs) expect(install).toHaveBeenCalledWith(4242)
+ expect(loadEngine).not.toHaveBeenCalled()
+ expect(console.warn).not.toHaveBeenCalled()
})
// lib/engineHomes.ts: with CLAUDE_CONFIG_DIR or CODEX_HOME in the person's profile, no agent ever bound.
diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.ts
index 9168f407d..6da47e538 100644
--- a/cli/src/core/engines/hooks.ts
+++ b/cli/src/core/engines/hooks.ts
@@ -8,7 +8,7 @@ import { engineHooks } from '../../engines/hooks.js'
import { sessionStoreContracts, type SessionStoreEngine } from '../../engines/sessionStoreContracts.js'
import { chooseHookAgent, type HookServerHandlers } from '../../hookServer.js'
import { adoptHomes, movedHomes } from '../../lib/engineHomes.js'
-import { loadEngine, type InProcessModules } from '../../engines/inProcess.js'
+import * as nativeHooks from '../../engines/nativeHooks.js'
import { sid } from '../../lib/log.js'
import type { registry, RegisteredSession } from '../../lib/registry.js'
import { processRows } from '../../lib/terminalAgentDiscovery.js'
@@ -188,13 +188,11 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry, pane
/**
* OpenCode's plugin, installed again before an OpenCode spawn (core/agents/create.ts): OpenCode may have moved
- * from 1.x to 2.x under a running daemon, and its new TUI must not find the old server plugin. False when the
- * other engines' installers could not be loaded.
+ * from 1.x to 2.x under a running daemon, and its new TUI must not find the old server plugin. Installation
+ * never depends on loading its optional interpreter.
*/
export async function installOpencodePluginBeforeSpawn(port: number): Promise<boolean> {
- const installers = await loadEngine('hooks')
- if (!installers) return false
- installers.installOpencodePlugin(port)
+ nativeHooks.installOpencodePlugin(port)
return true
}
@@ -208,23 +206,22 @@ export interface InstallEngineHooksOptions {
}
/**
- * The other engines' installers, in the order they have always run. Their code is loaded only here, once, as
- * the core starts (engines/inProcess.ts `hooks`), and only when one of them is to be installed.
+ * The other engines' declarations are installed in their original order, without an optional import.
*/
-const OTHER_INSTALLERS: Array<[string, (installers: InProcessModules['hooks']) => (port: number) => void]> = [
- ['cursor', (installers) => installers.installCursorHooks],
- ['opencode', (installers) => installers.installOpencodePlugin],
- ['kilo', (installers) => installers.installKiloPlugin],
- ['pi', (installers) => installers.installPiExtension],
+const OTHER_INSTALLERS: Array<[string, (port: number) => void]> = [
+ ['cursor', nativeHooks.installCursorHooks],
+ ['opencode', nativeHooks.installOpencodePlugin],
+ ['kilo', nativeHooks.installKiloPlugin],
+ ['pi', nativeHooks.installPiExtension],
// A self-update refreshes plugin files here; running engine processes pick them up according to each
// vendor's own plugin reload lifecycle.
- ['amp', (installers) => installers.installAmpPlugin],
- ['hermes', (installers) => installers.installHermesHooks],
- ['devin', (installers) => installers.installDevinHooks],
- ['commandcode', (installers) => installers.installCommandCodeHooks],
- ['grok', (installers) => installers.installGrokHooks],
- ['agy', (installers) => installers.installAgyHooks],
- ['copilot', (installers) => installers.installCopilotHooks],
+ ['amp', nativeHooks.installAmpPlugin],
+ ['hermes', nativeHooks.installHermesHooks],
+ ['devin', nativeHooks.installDevinHooks],
+ ['commandcode', nativeHooks.installCommandCodeHooks],
+ ['grok', nativeHooks.installGrokHooks],
+ ['agy', nativeHooks.installAgyHooks],
+ ['copilot', nativeHooks.installCopilotHooks],
]
/**
@@ -234,10 +231,9 @@ const OTHER_INSTALLERS: Array<[string, (installers: InProcessModules['hooks']) =
* files owned by thirteen different CLIs, and one that is malformed, read-only or mid-write is not
* a reason for the other twelve to go uninstalled — let alone for the daemon not to come up.
*
- * Claude Code's and Codex's first, in line, as before. Then the other engines' installers are loaded, at this
- * same step, which the caller awaits so that nothing it starts next (a restored pane among them) runs before
- * their hooks are in place. Installers that could not be loaded are skipped and named, as one that throws is.
- * Never rejects.
+ * Claude Code's and Codex's first, then the other engines, all in line before any restored pane starts.
+ * An unavailable interpreter cannot delay this step. A vendor whose settings throw is named and skipped;
+ * durable launch holds for preparation failures are a separate behavior change. Never rejects.
*/
export async function installEngineHooks(port: number, options: InstallEngineHooksOptions = {}): Promise<void> {
const hookStep = (vendor: string, install: () => void): void => {
@@ -264,13 +260,5 @@ export async function installEngineHooks(port: number, options: InstallEngineHoo
adopt(options.environment ?? process.env)
void options.loginShell?.then(adopt)
for (const [engine, hooks] of Object.entries(engineHooks)) hookStep(engine, () => hooks.install(port))
- const others = OTHER_INSTALLERS.filter(([vendor]) => !options.only || options.only.has(vendor))
- if (!others.length) return
- const installers = await loadEngine('hooks')
- for (const [vendor, installer] of others) {
- hookStep(vendor, () => {
- if (!installers) throw new Error('its installer could not be loaded')
- installer(installers)(port)
- })
- }
+ for (const [vendor, install] of OTHER_INSTALLERS) hookStep(vendor, () => install(port))
}
diff --git a/cli/src/engines/agy/contract.ts b/cli/src/engines/agy/contract.ts
index 2003ca470..0c72f1430 100644
--- a/cli/src/engines/agy/contract.ts
+++ b/cli/src/engines/agy/contract.ts
@@ -1,3 +1,5 @@
+import { join as hookPath } from 'node:path'
+import { env as hookEnvironment } from '../../config/env.js'
/**
* What the core knows of agy without loading its code: declared data, read in line on the hook path
* (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of agy's code.
@@ -20,3 +22,27 @@ export function agyTranscriptPath(agyHome: string, conversationId: string): stri
if (!CONVERSATION_ID.test(conversationId)) return null
return join(agyHome, 'brain', conversationId, '.system_generated', 'logs', 'transcript_full.jsonl')
}
+
+/** Hooks live in the shared customization root. Pre/PostToolUse can deny tools, so omit them; PostInvocation is a model round, not a turn. Only our named block is replaced. */
+export const AGY_HOOK_SETTINGS = {
+ file: hookPath(hookEnvironment.AGY_CONFIG_DIR, 'hooks.json'),
+ "engine": "agy",
+ "schema": "named",
+ "events": [
+ "PreInvocation",
+ "Stop"
+ ],
+ "timeout": 10,
+ "eventFlag": "--agy-event",
+ "block": "harness",
+ "messages": {
+ "current": "[hooks] agy lifecycle hooks already installed",
+ "installed": "[hooks] installed agy lifecycle hooks → {file}",
+ "after": "[hooks] (takes effect on the next agy session start)",
+ "failed": "[hooks] failed to write agy hook file:",
+ "malformed": [
+ "[hooks] agy hooks file is invalid JSON; leaving it unchanged: {file}",
+ "[hooks] fix the file, then restart harness login"
+ ]
+ }
+} as const satisfies import('../kit/nativeHookSettings.js').NativeHookSettings
diff --git a/cli/src/engines/amp/contract.ts b/cli/src/engines/amp/contract.ts
index ee748b72e..63649f588 100644
--- a/cli/src/engines/amp/contract.ts
+++ b/cli/src/engines/amp/contract.ts
@@ -1,9 +1,248 @@
+import { join as hookPath } from 'node:path'
+import { env as hookEnvironment } from '../../config/env.js'
/**
* What the core knows of Amp without loading its code: declared data, read by the kit
- * (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing.
+ * (docs/design/2026-10-08-other-engines-out-of-core.md). It imports no Amp interpreter.
*/
export const contract = {
/** Its approval rows are stacked and numbered by nothing: a row is reached by walking Down from the first
* (askQuestion.ts), and `kit/questionPane.ts` `walkKeys` turns that into keys. */
questionWalk: 'down',
} as const
+
+/** Native source runs in the engine process; the daemon only renders and installs these bytes. */
+export const AMP_PLUGIN = {
+ file: hookPath(hookEnvironment.AMP_PLUGIN_DIR, 'launcher-register.ts'),
+ template: [
+`// session-register — auto-installed by the machine adapter. Binds this Amp thread to the local
+// machine daemon (127.0.0.1:`,
+{ argument: 'port' },
+`) and writes the transcript the daemon tails, because Amp keeps none
+// on disk. No-op outside tmux.
+import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+export const description = 'Mirrors this Amp thread to the machine adapter (web + device)'
+
+const SESSIONS_DIR = `,
+JSON.stringify(hookEnvironment.AMP_SESSIONS_DIR),
+`
+
+export default function (amp: any) {
+ const pane = process.env.TMUX_PANE
+ if (!pane) return
+
+ // NOT \`process.cwd()\`: Bun runs a plugin with the PLUGIN's directory as its cwd, so that reports
+ // \`<project>/.amp/plugins\` (measured). \`PWD\` is inherited from the shell that launched plain Amp.
+ const workdir = process.env.PWD || process.cwd()
+
+ const emitted = new Set()
+ // Turn ids already opened/closed. Amp re-dispatches a message it could not deliver, firing agent.start
+ // a SECOND time for the same message id (measured: two identical turn_start records 61s apart, then a
+ // turn_end 'done' and a turn_end 'error' for the one turn). Written straight through, that is two turns
+ // on web and device and two user bubbles in history.
+ const turnsStarted = new Set()
+ const turnsEnded = new Set()
+ // Tool ids already written, so a tool seen BOTH as an event and as a message block is written once.
+ const toolCalls = new Set()
+ const toolResults = new Set()
+ let registered = false
+ let file = ''
+ let seeded = false
+
+ const line = (record: any) => {
+ try {
+ mkdirSync(SESSIONS_DIR, { recursive: true, mode: 0o700 })
+ appendFileSync(file, JSON.stringify(record) + '\\n')
+ } catch {}
+ }
+
+ const open = (threadId: string) => {
+ if (file) return
+ file = join(SESSIONS_DIR, threadId + '.jsonl')
+ // \`cwd\` on the first line is what lets the daemon re-find this session by directory after a restart,
+ // the same way it reads claude's and pi's transcripts. It must be a top-level string field.
+ line({ t: 'session', threadId, cwd: workdir, at: Date.now() })
+ }
+
+ const register = async (threadId: string) => {
+ open(threadId)
+ if (registered || !existsSync(file)) return
+ try {
+ const token = readFileSync(`,
+{ argument: 'credential' },
+`, 'utf8').trim()
+ if (!token) return
+ const res = await fetch('http://127.0.0.1:`,
+{ argument: 'port' },
+`/api/hook/session-start', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-harness-hook-token': token },
+ body: JSON.stringify({
+ engine: 'amp',
+ pluginVersion: `,
+{ argument: 'version' },
+`,
+ sessionId: threadId,
+ transcriptPath: file,
+ cwd: workdir,
+ tmuxPane: pane,
+ callerPid: process.pid,
+ runtimeHints: [
+ ...(pane ? [{ backend: 'tmux', paneId: pane }] : []),
+ ],
+ }),
+ })
+ if (res.ok) registered = true
+ } catch {}
+ }
+
+ const resultId = (block: any) => String(block.toolUseID || block.tool_use_id || '')
+
+ /**
+ * Write everything in the thread that has not been written yet.
+ *
+ * This reads message BLOCKS rather than events, because the events do not cover the thread:
+ *
+ * - no event carries assistant text at all, and
+ * - \`tool.call\`/\`tool.result\` only fire for tools the CLIENT executes. MEASURED: a \`web_search\`
+ * turn produced no tool event and no tool lease in Amp's own log, yet the message plainly held a
+ * \`tool_use\` block — Amp runs that tool on its server. Skipping blocks meant a search rendered as
+ * nothing at all on web and device while the pane showed "Explored 1 search".
+ *
+ * \`seed\` marks what already exists WITHOUT writing it, for a thread that is being resumed: those
+ * messages belong to earlier turns, and replaying them made a fresh turn open with an old answer in it.
+ */
+ const drain = async (ctx: any) => {
+ let messages: any[] = []
+ try { messages = await ctx.thread.messages({ from: 'end', limit: 20 }) } catch { return }
+ // The FIRST drain of this plugin instance only claims what it finds; it writes nothing. That covers
+ // both ways a plugin meets a thread that already has messages: a resumed thread, and a plugin reload
+ // (Amp loads a plugin ONCE per process, so reload is how a running pane picks up a new build). Without
+ // it, the next prompt replayed the whole recent history as if it had just happened.
+ const seed = !seeded
+ seeded = true
+ // The seed pass would swallow the very prompt the turn needs to open on. Measured: \`session.start\`
+ // does NOT fire when Amp launches — it fires on the first submit, and by then the thread already
+ // holds one \`user\` message. So the seed has to tell history from the live prompt, and the test is
+ // whether anything answered it: the LAST user text block with no assistant message after it is
+ // waiting, not past. On a resumed thread the last message is an assistant one, so nothing opens.
+ let liveUserId = ''
+ for (const message of messages) {
+ if (message.role === 'assistant') { liveUserId = ''; continue }
+ const parts = Array.isArray(message.content) ? message.content : []
+ const hasText = parts.some((b: any) => b && b.type === 'text' && typeof b.text === 'string' && b.text)
+ if (hasText) liveUserId = String(message.id)
+ }
+ for (const message of messages) {
+ const blocks = Array.isArray(message.content) ? message.content : []
+ for (let i = 0; i < blocks.length; i++) {
+ const block = blocks[i]
+ if (!block) continue
+ if (block.type === 'text' || block.type === 'thinking') {
+ const key = String(message.id) + '#' + i
+ if (emitted.has(key)) continue
+ const text = typeof block.text === 'string' ? block.text : block.thinking
+ if (typeof text !== 'string' || !text) continue
+ emitted.add(key)
+ // A user TEXT block opens the turn.
+ //
+ // Amp used to announce that with an \`agent.start\` event, and the handler below wrote
+ // \`turn_start\` from it. That event no longer fires — probed with a plugin that registered for
+ // sixteen candidate names on amp 0.0.1786681855 and saw only \`session.start\`, \`tool.call\`,
+ // \`tool.result\` and \`agent.end\`. The prompt now reaches a plugin no earlier than
+ // \`agent.end\`, which is the END of the turn, far too late to open one.
+ //
+ // So it is taken from the thread instead, where drain was already reading it and dropping it:
+ // measured at the first \`tool.call\` of a turn, \`messages()\` already returns the prompt, oldest
+ // first. Without this the turn opens with an empty question on web and device, and the recap
+ // loses what was asked.
+ //
+ // Only a TEXT block qualifies: a tool_result is also carried on a \`user\` message, so matching
+ // the role alone would open a turn on every tool that returned.
+ if (message.role !== 'assistant') {
+ const turnId = String(message.id)
+ if (turnsStarted.has(turnId)) continue
+ turnsStarted.add(turnId)
+ if (!seed || turnId === liveUserId) line({ t: 'turn_start', id: turnId, message: text, at: Date.now() })
+ continue
+ }
+ if (!seed) line({ t: block.type, id: message.id, i, text })
+ } else if (block.type === 'tool_use') {
+ const id = String(block.id || '')
+ if (!id || toolCalls.has(id)) continue
+ toolCalls.add(id)
+ if (!seed) line({ t: 'tool_call', id, tool: block.name, input: block.input })
+ } else if (block.type === 'tool_result') {
+ const id = resultId(block)
+ if (!id || toolResults.has(id)) continue
+ toolResults.add(id)
+ // A server-run tool puts its payload under \`run\`; a client-run one under \`content\`/\`output\`.
+ if (!seed) line({ t: 'tool_result', id, status: 'done', output: block.run ?? block.content ?? block.output })
+ }
+ }
+ }
+ }
+
+ amp.on('session.start', async (event: any, ctx: any) => {
+ await register(event.thread.id)
+ await drain(ctx)
+ })
+
+ amp.on('agent.start', async (event: any, ctx: any) => {
+ await register(event.thread.id)
+ const id = String(event.id)
+ if (!turnsStarted.has(id)) {
+ turnsStarted.add(id)
+ line({ t: 'turn_start', id: event.id, message: event.message, at: Date.now() })
+ }
+ await drain(ctx)
+ })
+
+ amp.on('tool.call', async (event: any, ctx: any) => {
+ await register(event.thread.id)
+ // CLAIM THE ID FIRST. \`drain\` runs before this card so a message's prose lands ahead of the tool it
+ // called — but by then the tool_use block for THIS tool is already in the thread, so draining without
+ // claiming wrote the card twice (measured: one Task turn produced two identical \`skill\` cards).
+ toolCalls.add(String(event.toolUseID))
+ await drain(ctx)
+ line({ t: 'tool_call', id: event.toolUseID, tool: event.tool, input: event.input })
+ })
+
+ amp.on('tool.result', async (event: any, ctx: any) => {
+ // Same rule as tool.call: claim before draining.
+ toolResults.add(String(event.toolUseID))
+ line({
+ t: 'tool_result',
+ id: event.toolUseID,
+ tool: event.tool,
+ status: event.status,
+ output: event.output,
+ })
+ await drain(ctx)
+ })
+
+ amp.on('agent.end', async (event: any, ctx: any) => {
+ await drain(ctx)
+ // \`message\` is the prompt that STARTED this turn, and agent.end carries it even when
+ // agent.start never fired (a prompt queued while Amp was connecting). Recording it here is what
+ // lets history still show what was asked — see the replay branch in the normalizer.
+ const id = String(event.id)
+ if (turnsEnded.has(id)) return
+ turnsEnded.add(id)
+ line({ t: 'turn_end', id: event.id, status: event.status, message: event.message, at: Date.now() })
+ })
+}
+`
+],
+ directories: [{ path: hookEnvironment.AMP_SESSIONS_DIR, mode: 0o700 }],
+ messages: {
+ "current": "[hooks] Amp plugin already installed",
+ "installed": "[hooks] installed Amp plugin → {file}",
+ "after": [
+ "[hooks] a NEW amp session picks this up automatically; for one already open, run",
+ "[hooks] ctrl+o → 'plugins: reload' (or restart that pane)"
+ ],
+ "failed": "[hooks] failed to write Amp plugin:"
+},
+} as const satisfies import('../kit/nativePlugin.js').NativePlugin
diff --git a/cli/src/engines/commandcode/contract.ts b/cli/src/engines/commandcode/contract.ts
index e7956ff24..a35a91ea9 100644
--- a/cli/src/engines/commandcode/contract.ts
+++ b/cli/src/engines/commandcode/contract.ts
@@ -1,3 +1,5 @@
+import { join as hookPath } from 'node:path'
+import { env as hookEnvironment } from '../../config/env.js'
/**
* What the core knows of Command Code without loading its code: declared data, read in line on the hook path
* (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of Command Code's code.
@@ -34,3 +36,25 @@ export function commandcodeTranscriptPath(cwd: string | null | undefined, sessio
if (!slug) return null
return join(env.COMMANDCODE_HOME, 'projects', slug, `${sessionId}.jsonl`)
}
+
+/** PreToolUse is this engine's only timely turn-open signal: its transcript arrives as one completed flush. There is no UserPromptSubmit or SessionEnd hook. */
+export const COMMANDCODE_HOOK_SETTINGS = {
+ file: hookPath(hookEnvironment.COMMANDCODE_HOME, 'settings.json'),
+ "engine": "commandcode",
+ "schema": "nested",
+ "events": [
+ "SessionStart",
+ "PreToolUse",
+ "Stop"
+ ],
+ "timeout": 5,
+ "messages": {
+ "current": "[hooks] Command Code session hooks already installed",
+ "installed": "[hooks] installed Command Code SessionStart/Stop hooks → {file}",
+ "after": "[hooks] (takes effect on the next commandcode session start)",
+ "failed": "[hooks] failed to write Command Code settings.json:",
+ "malformed": [
+ "[hooks] Command Code settings file is invalid JSON; leaving it unchanged: {file}"
+ ]
+ }
+} as const satisfies import('../kit/nativeHookSettings.js').NativeHookSettings
diff --git a/cli/src/engines/copilot/contract.ts b/cli/src/engines/copilot/contract.ts
index ad46f5c59..143b85706 100644
--- a/cli/src/engines/copilot/contract.ts
+++ b/cli/src/engines/copilot/contract.ts
@@ -1,3 +1,5 @@
+import { join as hookPath } from 'node:path'
+import { env as hookEnvironment } from '../../config/env.js'
/**
* What the core knows of Copilot without loading its code: declared data, read in line on the hook path
* (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of Copilot's code.
@@ -26,3 +28,24 @@ export function copilotTranscriptPath(copilotHome: string, sessionId: string): s
if (!SESSION_ID.test(sessionId)) return null
return join(copilotHome, 'session-state', sessionId, 'events.jsonl')
}
+
+/** The engine reads each JSON file in its hooks directory. This file is ours; preToolUse is fail-closed and is deliberately absent. Tool cards come from its transcript. */
+export const COPILOT_HOOK_SETTINGS = {
+ file: hookPath(hookEnvironment.COPILOT_HOME, 'hooks', 'harness.json'),
+ "engine": "copilot",
+ "schema": "file",
+ "events": [
+ "sessionStart",
+ "userPromptSubmitted",
+ "agentStop",
+ "sessionEnd"
+ ],
+ "version": 1,
+ "eventFlag": "--copilot-event",
+ "messages": {
+ "current": "[hooks] Copilot lifecycle hooks already installed",
+ "installed": "[hooks] installed Copilot lifecycle hooks → {file}",
+ "after": "[hooks] (takes effect on the next copilot session start)",
+ "failed": "[hooks] failed to write Copilot hook file:"
+ }
+} as const satisfies import('../kit/nativeHookSettings.js').NativeHookSettings
diff --git a/cli/src/engines/cursor/contract.ts b/cli/src/engines/cursor/contract.ts
index e4ab8566c..ffa510345 100644
--- a/cli/src/engines/cursor/contract.ts
+++ b/cli/src/engines/cursor/contract.ts
@@ -1,3 +1,4 @@
+import { join as hookPath } from 'node:path'
/**
* What the core knows of Cursor without loading its code: declared data, read in line on the hook path and in
* the hook command (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of Cursor's code.
@@ -24,3 +25,27 @@ export function cursorDataDir(vars: NodeJS.ProcessEnv = process.env): string {
/** Cursor's Task hooks a hook queued while no daemon ran (hook/notify.mjs writes it), in the data folder. */
export const PENDING_TASKS_FILE = 'cursor-pending-tasks.json'
+
+/** Lower-camel events and direct command entries. A failed notification must never deny an engine tool. */
+export const CURSOR_HOOK_SETTINGS = {
+ file: hookPath(cursorConfigDir(), 'hooks.json'),
+ "engine": "cursor",
+ "schema": "entries",
+ "events": [
+ "sessionStart",
+ "beforeSubmitPrompt",
+ "preToolUse",
+ "stop",
+ "sessionEnd"
+ ],
+ "version": 1,
+ "failClosed": false,
+ "messages": {
+ "current": "[hooks] Cursor lifecycle/task hooks already installed",
+ "installed": "[hooks] installed Cursor lifecycle/task hooks → {file}",
+ "failed": "[hooks] failed to write Cursor hooks.json:",
+ "malformed": [
+ "[hooks] Cursor hooks file is invalid JSON; leaving it unchanged: {file}"
+ ]
+ }
+} as const satisfies import('../kit/nativeHookSettings.js').NativeHookSettings
diff --git a/cli/src/engines/devin/contract.ts b/cli/src/engines/devin/contract.ts
new file mode 100644
index 000000000..57ba1a21a
--- /dev/null
+++ b/cli/src/engines/devin/contract.ts
@@ -0,0 +1,25 @@
+import { env as hookEnvironment } from '../../config/env.js'
+/** Native facts needed by session control without optional interpretation. */
+
+/** The vendor reads Claude's nested hook schema. Merge only Harness's blocks into its general config. */
+export const DEVIN_HOOK_SETTINGS = {
+ file: hookEnvironment.DEVIN_CONFIG_PATH,
+ "engine": "devin",
+ "schema": "nested",
+ "events": [
+ "SessionStart",
+ "UserPromptSubmit",
+ "Stop",
+ "SessionEnd"
+ ],
+ "timeout": 5,
+ "messages": {
+ "current": "[hooks] Devin session hooks already installed",
+ "installed": "[hooks] installed Devin SessionStart/UserPromptSubmit/Stop/SessionEnd hooks → {file}",
+ "after": "[hooks] (takes effect on the next devin session start)",
+ "failed": "[hooks] failed to write Devin config.json:",
+ "malformed": [
+ "[hooks] Devin config file is invalid JSON; leaving it unchanged: {file}"
+ ]
+ }
+} as const satisfies import('../kit/nativeHookSettings.js').NativeHookSettings
diff --git a/cli/src/engines/grok/contract.ts b/cli/src/engines/grok/contract.ts
index 9f56b551c..b48d6d123 100644
--- a/cli/src/engines/grok/contract.ts
+++ b/cli/src/engines/grok/contract.ts
@@ -1,3 +1,5 @@
+import { join as hookPath } from 'node:path'
+import { env as hookEnvironment } from '../../config/env.js'
/** Grok's transcript layout, including the sidecar used when the encoded cwd would be too long. */
import type { TranscriptLocation } from '../kit/sessionLocation.js'
@@ -5,3 +7,27 @@ export const GROK_TRANSCRIPT: TranscriptLocation = {
id: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
kind: 'cwd', root: 'sessions', file: 'updates.jsonl', sidecar: '.cwd',
}
+
+/** Normal Stop precedes the final assistant chunk; only StopFailure closes through this hook. */
+export const GROK_HOOK_SETTINGS = {
+ file: hookPath(hookEnvironment.GROK_HOME, 'hooks', 'harness.json'),
+ "engine": "grok",
+ "schema": "nested",
+ "events": [
+ "SessionStart",
+ "SessionEnd",
+ "UserPromptSubmit",
+ "StopFailure"
+ ],
+ "timeout": 5,
+ "messages": {
+ "current": "[hooks] Grok lifecycle/StopFailure hooks already installed",
+ "installed": "[hooks] installed Grok lifecycle/StopFailure hooks → {file}",
+ "after": "[hooks] (takes effect on the next Grok session start)",
+ "failed": "[hooks] failed to write Grok hook file:",
+ "malformed": [
+ "[hooks] Grok hooks file is invalid JSON; leaving it unchanged: {file}",
+ "[hooks] fix the file, then restart harness login"
+ ]
+ }
+} as const satisfies import('../kit/nativeHookSettings.js').NativeHookSettings
diff --git a/cli/src/engines/hermes/contract.ts b/cli/src/engines/hermes/contract.ts
index 189afbf87..f01c46f87 100644
--- a/cli/src/engines/hermes/contract.ts
+++ b/cli/src/engines/hermes/contract.ts
@@ -3,6 +3,7 @@
* core.md). It imports nothing of Hermes's code.
*/
import { join } from 'node:path'
+import { env as hookEnvironment } from '../../config/env.js'
import type { StoreHomes } from '../kit/storeHomes.js'
import type { StoreSourceRule } from '../kit/storeSource.js'
@@ -47,3 +48,28 @@ export const HERMES_SOURCE: StoreSourceRule = {
interactive: ['', 'cli', 'tui'],
maxBuffer: 1 << 20,
}
+
+/** A profile needs its own command as soon as config exists, before its first history row (#191). */
+export const HERMES_CONFIG_HOMES = { directory: 'profiles', file: 'config.yaml', max: 64 } as const
+
+/** pre_llm_call registers resumed sessions too; on_session_start only fires for a new one. */
+export const HERMES_HOOK_SETTINGS = {
+ home: hookEnvironment.HERMES_HOME,
+ homes: HERMES_CONFIG_HOMES,
+ begin: '# machine-adapter: session discovery (managed block — safe to delete)',
+ end: '# machine-adapter: end',
+ events: ['on_session_start', 'pre_llm_call'],
+ timeout: 10,
+ allowlist: 'shell-hooks-allowlist.json',
+ ownership: ['notify.mjs', '--engine hermes'],
+ messages: {
+ missing: '[hooks] no Hermes config at {file} — skipping (run hermes once first)',
+ foreign: '[hooks] {file} has its own `hooks:` block — leaving it untouched.',
+ manual: '[hooks] add these entries under it manually to mirror Hermes sessions:',
+ current: '[hooks] Hermes session hooks already installed',
+ installed: '[hooks] installed Hermes session hooks → {file}',
+ collapsed: '[hooks] installed Hermes session hooks (collapsed {removed} stale blocks) → {file}',
+ after: '[hooks] (takes effect on the next hermes session start)',
+ failed: '[hooks] failed to write Hermes config.yaml:',
+ },
+} as const satisfies import('../kit/nativeHookYaml.js').NativeYamlHooks
diff --git a/cli/src/engines/hermes/home.ts b/cli/src/engines/hermes/home.ts
index b879ff294..2b36b854c 100644
--- a/cli/src/engines/hermes/home.ts
+++ b/cli/src/engines/hermes/home.ts
@@ -21,19 +21,18 @@
* home yet — it is a profile whose first session has not started.
*/
-import { readdirSync, realpathSync, statSync } from 'node:fs'
+import { realpathSync } from 'node:fs'
import { join } from 'node:path'
import { env } from '../../config/env.js'
-import { HERMES_HISTORY_ID_RE, HERMES_HOMES, HERMES_PROFILE, hermesDbPath } from './contract.js'
+import { HERMES_HISTORY_ID_RE, HERMES_HOMES, HERMES_PROFILE, HERMES_CONFIG_HOMES, hermesDbPath } from './contract.js'
import { forgetStoreHomes, listStoreHomes } from '../kit/storeHomes.js'
+import { nativeHookHomes } from '../kit/nativeHookHomes.js'
import { profileFromEnv } from '../kit/processFacts.js'
import { sqliteReadAll } from '../../lib/sqliteRead.js'
import type { AgentEngine } from '../types.js'
/** `YYYYMMDD_HHMMSS_<hex>`, or an editor's (ACP) uuid — the shapes `reader.ts` reads history for. */
const SESSION_ID_RE = HERMES_HISTORY_ID_RE
-/** A person with hundreds of profile folders has a different problem; this keeps the scan bounded. */
-const MAX_PROFILES = 64
export { hermesDbPath } from './contract.js'
@@ -65,16 +64,7 @@ export async function listHermesHomes(defaultHome = env.HERMES_HOME): Promise<st
* as it has a config, which is at creation. Synchronous because every hook installer is.
*/
export function hermesConfigHomes(defaultHome = env.HERMES_HOME): string[] {
- const homes = [defaultHome]
- let entries: string[] = []
- try { entries = readdirSync(join(defaultHome, 'profiles')) } catch { return homes }
- for (const name of entries.slice(0, MAX_PROFILES)) {
- const home = join(defaultHome, 'profiles', name)
- try {
- if (statSync(join(home, 'config.yaml')).isFile()) homes.push(home)
- } catch { /* not a profile folder, or no config yet */ }
- }
- return homes
+ return nativeHookHomes(HERMES_CONFIG_HOMES, defaultHome)
}
/** Forget the listing — for a test, and for an installer that has just made a profile. */
diff --git a/cli/src/engines/inProcess.ts b/cli/src/engines/inProcess.ts
index 1ba96273c..3d04aa6e9 100644
--- a/cli/src/engines/inProcess.ts
+++ b/cli/src/engines/inProcess.ts
@@ -27,7 +27,7 @@ const MODULES = {
/** Their pane and dialog readers, the twelve in one: lib/legacyScreen.ts with lib/legacyPane.ts,
* lib/questionPane.ts and the eight `askQuestion.ts`. A pane is read on every poll of one of their sessions. */
screens: () => import('../lib/legacyScreen.js'),
- /** Their hook installers, eleven in one file (lib/hooks.ts): run once, as the core starts. */
+ /** Legacy compatibility entry. Native installation is eager; core never requests this chunk. */
hooks: () => import('../lib/hooks.js'),
/** The database engines' conversations read whole (lib/databaseHistory.ts), for what the core hands on. */
databaseHistory: () => import('../lib/databaseHistory.js'),
diff --git a/cli/src/engines/kilo/contract.ts b/cli/src/engines/kilo/contract.ts
index c29ed8998..38841b6f6 100644
--- a/cli/src/engines/kilo/contract.ts
+++ b/cli/src/engines/kilo/contract.ts
@@ -1,3 +1,5 @@
+import { join as hookPath } from 'node:path'
+import { env as hookEnvironment } from '../../config/env.js'
/**
* What the core knows of Kilo without loading its code: declared data, read by the kit
* (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing.
@@ -7,3 +9,72 @@ export const contract = {
* walking Right from the first (askQuestion.ts), and `kit/questionPane.ts` `walkKeys` turns that into keys. */
questionWalk: 'right',
} as const
+
+/** Native source runs in the engine process; the daemon only renders and installs these bytes. */
+export const KILO_PLUGIN = {
+ file: hookPath(hookEnvironment.KILO_PLUGIN_DIR, 'launcher-register.js'),
+ template: [
+`// session-register — auto-installed by the machine adapter. Binds this `,
+"Kilo",
+` session to the
+// local machine daemon (127.0.0.1:`,
+{ argument: 'port' },
+`) so it can be mirrored to web/device. No-op if machine isn't running.
+import { readFileSync } from "node:fs"
+const hookToken = () => { try { return readFileSync(`,
+{ argument: 'credential' },
+`, "utf8").trim() } catch { return "" } }
+export const MachineRegister = async ({ directory, worktree, project, client }) => {
+ const seen = new Set()
+ const post = async (sessionID) => {
+ const pane = process.env.TMUX_PANE
+ const token = hookToken()
+ if (!pane || !token || !sessionID || seen.has(sessionID)) return
+ seen.add(sessionID)
+ try {
+ await fetch("http://127.0.0.1:`,
+{ argument: 'port' },
+`/api/hook/session-start", {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-harness-hook-token": token },
+ body: JSON.stringify({
+ engine: "`,
+"kilo",
+`",
+ pluginVersion: `,
+{ argument: 'version' },
+`,
+ sessionId: sessionID,
+ cwd: directory || worktree || (project && project.worktree) || null,
+ tmuxPane: pane,
+ callerPid: process.pid,
+ runtimeHints: [
+ ...(pane ? [{ backend: "tmux", paneId: pane }] : []),
+ ],
+ }),
+ })
+ } catch {}
+ }
+ return {
+ event: async ({ event }) => {
+ if (!event) return
+ if (event.type === "session.created" || event.type === "session.updated") {
+ const p = event.properties || {}
+ const info = p.info || {}
+ if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent
+ await post(info.id || p.sessionID || p.sessionId)
+ }
+ },
+ }
+}
+`
+],
+ messages: {
+ "current": "[hooks] Kilo discovery plugin already installed",
+ "installed": "[hooks] installed Kilo discovery plugin → {file}",
+ "after": [
+ "[hooks] (takes effect on the next kilo session start)"
+ ],
+ "failed": "[hooks] failed to write Kilo plugin:"
+},
+} as const satisfies import('../kit/nativePlugin.js').NativePlugin
diff --git a/cli/src/engines/kit/nativeHookHomes.ts b/cli/src/engines/kit/nativeHookHomes.ts
new file mode 100644
index 000000000..1c3355d44
--- /dev/null
+++ b/cli/src/engines/kit/nativeHookHomes.ts
@@ -0,0 +1,17 @@
+/** Configured profiles need hooks before their first session creates a history store. */
+import { readdirSync, statSync } from 'node:fs'
+import { join } from 'node:path'
+
+export interface NativeHookHomes { directory: string; file: string; max: number }
+export function nativeHookHomes(rule: NativeHookHomes, defaultHome: string): string[] {
+ const homes = [defaultHome]
+ let entries: string[] = []
+ try { entries = readdirSync(join(defaultHome, rule.directory)) } catch { return homes }
+ for (const name of entries.slice(0, rule.max)) {
+ const home = join(defaultHome, rule.directory, name)
+ try {
+ if (statSync(join(home, rule.file)).isFile()) homes.push(home)
+ } catch { /* not a profile folder, or no config yet */ }
+ }
+ return homes
+}
diff --git a/cli/src/engines/kit/nativeHookLiterals.spec.ts b/cli/src/engines/kit/nativeHookLiterals.spec.ts
new file mode 100644
index 000000000..e8edb3859
--- /dev/null
+++ b/cli/src/engines/kit/nativeHookLiterals.spec.ts
@@ -0,0 +1,29 @@
+/** A person's path is literal data, including replacement-string and template syntax. */
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import { installNativeHookSettings } from './nativeHookSettings.js'
+import { installNativePlugin } from './nativePlugin.js'
+
+let root = ''
+afterEach(() => { if (root) rmSync(root, { recursive: true, force: true }); root = ''; vi.restoreAllMocks() })
+it('reports a JSON settings destination verbatim', () => {
+ root = mkdtempSync(join(tmpdir(), 'native-hook-literals-'))
+ const file = join(root, '$&-${credential}.json')
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ installNativeHookSettings({ file, engine: 'copilot', schema: 'file', version: 1, eventFlag: '--copilot-event', events: ['sessionStart'],
+ messages: { current: 'current', installed: 'installed {file}', failed: 'failed' } }, 19473)
+ expect(JSON.parse(readFileSync(file, 'utf8')).hooks.sessionStart[0].command).toContain('--port 19473')
+ expect(log).toHaveBeenCalledWith(`installed ${file}`)
+})
+it('renders plugin argument contents once and reports its destination verbatim', () => {
+ root = mkdtempSync(join(tmpdir(), 'native-hook-literals-'))
+ const file = join(root, '$&-${version}.js')
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ installNativePlugin({ file, template: ['credential=', { argument: 'credential' }, ';version=', { argument: 'version' }],
+ messages: { current: 'current', installed: 'installed {file}', after: [], failed: 'failed' } },
+ { credential: '${version}$&', version: 'fixture', port: '19473' })
+ expect(readFileSync(file, 'utf8')).toBe('credential=${version}$&;version=fixture')
+ expect(log).toHaveBeenCalledWith(`installed ${file}`)
+})
diff --git a/cli/src/engines/kit/nativeHookSettings.ts b/cli/src/engines/kit/nativeHookSettings.ts
new file mode 100644
index 000000000..b410ae3be
--- /dev/null
+++ b/cli/src/engines/kit/nativeHookSettings.ts
@@ -0,0 +1,93 @@
+/** Eager mechanics for the native JSON hook schemas. Each engine declares its events and ownership rules. */
+import { existsSync, readFileSync } from 'node:fs'
+import { command, isOurs, writeJsonAtomic, type Settings, type HookBlock } from './notifyHooks.js'
+
+export interface NativeHookSettings {
+ file: string
+ engine: Parameters<typeof command>[1]
+ schema: 'nested' | 'entries' | 'named' | 'file'
+ events: readonly string[]
+ timeout?: number
+ eventFlag?: string
+ version?: number
+ block?: string
+ failClosed?: boolean
+ messages: { current: string; installed: string; after?: string; failed: string; malformed?: readonly string[] }
+}
+type Entry = { type?: string; command: string; timeout?: number; failClosed?: boolean }
+type EntrySettings = { version?: number; hooks?: Record<string, Entry[]> } & Record<string, unknown>
+type NamedSettings = Record<string, Record<string, Entry[]> | unknown>
+const UNREADABLE = Symbol('unreadable')
+
+function readSettings(rule: NativeHookSettings, file: string): unknown | typeof UNREADABLE {
+ if (!existsSync(file)) return {}
+ try { return JSON.parse(readFileSync(file, 'utf-8')) } catch {
+ for (const line of rule.messages.malformed ?? []) console.error(line.replace('{file}', () => file))
+ return UNREADABLE
+ }
+}
+function writeSettings(rule: NativeHookSettings, file: string, settings: unknown): void {
+ try {
+ writeJsonAtomic(file, settings)
+ console.log(rule.messages.installed.replace('{file}', () => file))
+ if (rule.messages.after) console.log(rule.messages.after)
+ } catch (err) { console.error(rule.messages.failed, err) }
+}
+
+export function installNativeHookSettings(rule: NativeHookSettings, port: number): void {
+ const file = rule.file
+ if (rule.schema === 'file') {
+ const cmd = command(port, rule.engine)
+ const settings = { version: rule.version!, hooks: Object.fromEntries(rule.events.map(event =>
+ [event, [{ type: 'command', command: `${cmd} ${rule.eventFlag} ${event}` }]])) }
+ let existing: unknown = null
+ if (existsSync(file)) { try { existing = JSON.parse(readFileSync(file, 'utf-8')) } catch { existing = null } }
+ if (JSON.stringify(existing) === JSON.stringify(settings)) { console.log(rule.messages.current); return }
+ writeSettings(rule, file, settings)
+ return
+ }
+ const parsed = readSettings(rule, file)
+ if (parsed === UNREADABLE) return
+ if (rule.schema === 'named') {
+ const settings: NamedSettings = !parsed || typeof parsed !== 'object' || Array.isArray(parsed) ? {} : parsed as NamedSettings
+ const cmd = command(port, rule.engine)
+ const block = Object.fromEntries(rule.events.map(event => [event,
+ [{ type: 'command', command: `${cmd} ${rule.eventFlag} ${event}`, timeout: rule.timeout }]]))
+ if (JSON.stringify(settings[rule.block!]) === JSON.stringify(block)) { console.log(rule.messages.current); return }
+ settings[rule.block!] = block
+ writeSettings(rule, file, settings)
+ return
+ }
+ if (rule.schema === 'entries') {
+ const settings = parsed as EntrySettings
+ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
+ if (typeof settings.version !== 'number') settings.version = rule.version
+ const cmd = command(port, rule.engine)
+ let changed = false
+ for (const event of rule.events) {
+ const entries = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []
+ const foreign = entries.filter(entry => !entry?.command?.includes('notify.mjs'))
+ const ours = entries.filter(entry => entry?.command?.includes('notify.mjs'))
+ const canonical: Entry = { command: cmd, failClosed: rule.failClosed }
+ if (ours.length !== 1 || ours[0]?.command !== cmd || ours[0]?.failClosed !== rule.failClosed) changed = true
+ settings.hooks[event] = [...foreign, canonical]
+ }
+ if (!changed) { console.log(rule.messages.current); return }
+ writeSettings(rule, file, settings)
+ return
+ }
+ const settings = parsed as Settings
+ if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
+ const cmd = command(port, rule.engine)
+ let changed = false
+ for (const event of rule.events) {
+ const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []
+ const foreign = blocks.filter(block => !isOurs(block))
+ const ours = blocks.filter(isOurs)
+ const canonical: HookBlock = { hooks: [{ type: 'command', command: cmd, timeout: rule.timeout }] }
+ if (ours.length !== 1 || ours[0]?.hooks?.[0]?.command !== cmd) changed = true
+ settings.hooks[event] = [...foreign, canonical]
+ }
+ if (!changed) { console.log(rule.messages.current); return }
+ writeSettings(rule, file, settings)
+}
diff --git a/cli/src/engines/kit/nativeHookYaml.ts b/cli/src/engines/kit/nativeHookYaml.ts
new file mode 100644
index 000000000..9ee9d9956
--- /dev/null
+++ b/cli/src/engines/kit/nativeHookYaml.ts
@@ -0,0 +1,141 @@
+/** A managed YAML hook block and exact-command approvals, applied from eager engine declarations. */
+import { readFileSync, writeFileSync } from 'node:fs'
+import { basename, join } from 'node:path'
+import { writeJsonAtomic } from './notifyHooks.js'
+import { nativeHookHomes, type NativeHookHomes } from './nativeHookHomes.js'
+
+export interface NativeYamlHooks {
+ home: string
+ homes: NativeHookHomes
+ begin: string
+ end: string
+ events: readonly string[]
+ timeout: number
+ allowlist: string
+ ownership: readonly string[]
+ messages: { missing: string; foreign: string; manual: string; current: string; installed: string; collapsed: string; after: string; failed: string }
+}
+function message(template: string, values: Record<string, string>): string {
+ return template.replace(/\{(file|removed)\}/g, (_, key: string) => values[key])
+}
+
+function allowlistHook(rule: NativeYamlHooks, cmd: string, home: string): void {
+ const allowlistPath = join(home, rule.allowlist)
+ let data: { approvals?: Array<{ event?: string; command?: string }> } = { approvals: [] }
+ try {
+ const parsed = JSON.parse(readFileSync(allowlistPath, 'utf-8')) as typeof data
+ if (parsed && Array.isArray(parsed.approvals)) data = parsed
+ } catch { /* absent or unreadable → start from an empty skeleton */ }
+ const previous = data.approvals ?? []
+ // Drop OUR stale approvals before adding the current one. Each command change — a new port, a moved
+ // install, a new Node runtime — otherwise leaves five dead entries here forever, and the entry is
+ // dead the moment the command string it approves is no longer the one we install. Foreign approvals
+ // are somebody else's business and are copied through untouched.
+ const isOurStaleApproval = (a: { command?: string }) =>
+ typeof a?.command === 'string' &&
+ rule.ownership.every(fragment => a.command!.includes(fragment)) &&
+ a.command !== cmd
+ const approvals = previous.filter((a) => !isOurStaleApproval(a))
+ let changed = approvals.length !== previous.length
+ for (const event of rule.events) {
+ // Approvals match exact (event, command) string equality.
+ if (approvals.some((a) => a?.event === event && a?.command === cmd)) continue
+ approvals.push({ event, command: cmd })
+ changed = true
+ }
+ if (!changed) return
+ writeJsonAtomic(allowlistPath, { ...data, approvals })
+}
+
+function hooksBlock(rule: NativeYamlHooks, cmd: string): string {
+ const entries = rule.events
+ .map((event) => ` ${event}:\n - command: ${JSON.stringify(cmd)}\n timeout: ${rule.timeout}`)
+ .join('\n')
+ return `\n${rule.begin}\nhooks:\n${entries}\n${rule.end}\n`
+}
+
+/** True for a top-level `hooks:` mapping that is ours (every command runs our notify.mjs for this engine). */
+function isOwnedHooksBody(rule: NativeYamlHooks, body: string[]): boolean {
+ const commands = body.filter((line) => /^\s*- command:/.test(line))
+ return commands.length > 0 && commands.every((line) => rule.ownership.every(fragment => line.includes(fragment)))
+}
+
+/**
+ * Strip every block this installer owns: the delimited BEGIN…END form AND any bare `hooks:` mapping
+ * left behind by the earlier buggy rewrite (identified by its notify.mjs commands). Returns the cleaned
+ * document plus whether a FOREIGN `hooks:` key survives — the caller must not touch the file then.
+ */
+function stripOwnedBlocks(rule: NativeYamlHooks, config: string): { cleaned: string; foreignHooks: boolean; removed: number } {
+ const lines = config.split('\n')
+ const out: string[] = []
+ let removed = 0
+ let foreignHooks = false
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]
+ if (line.trim() === rule.begin) {
+ // Skip through the END marker (or, for a truncated block, to the end of the mapping).
+ let j = i + 1
+ while (j < lines.length && lines[j].trim() !== rule.end) j++
+ i = j < lines.length ? j : lines.length - 1
+ removed++
+ continue
+ }
+ if (/^hooks:\s*$/.test(line)) {
+ let j = i + 1
+ while (j < lines.length && (lines[j].startsWith(' ') || lines[j].startsWith('\t') || lines[j].trim() === '')) j++
+ const body = lines.slice(i + 1, j)
+ if (isOwnedHooksBody(rule, body)) { removed++; i = j - 1; continue }
+ foreignHooks = true
+ out.push(line)
+ continue
+ }
+ out.push(line)
+ }
+ return { cleaned: out.join('\n').replace(/\n{3,}$/, '\n'), foreignHooks, removed }
+}
+
+/** Installs only homes with a config, each with its own command and allowlist. */
+export function installNativeYamlHooks(rule: NativeYamlHooks, commandForHome: (home: string) => string): void {
+ for (const home of nativeHookHomes(rule.homes, rule.home)) installIn(rule, commandForHome(home), home)
+}
+
+function installIn(rule: NativeYamlHooks, cmd: string, home: string): void {
+ const configPath = join(home, rule.homes.file)
+ let config = ''
+ try {
+ config = readFileSync(configPath, 'utf-8')
+ } catch {
+ if (home === rule.home) console.log(message(rule.messages.missing, { file: configPath }))
+ return
+ }
+
+ const { cleaned, foreignHooks, removed } = stripOwnedBlocks(rule, config)
+ if (foreignHooks) {
+ console.error(message(rule.messages.foreign, { file: configPath }))
+ console.error(rule.messages.manual)
+ for (const event of rule.events) console.error(`[hooks] ${event}: [{ command: ${JSON.stringify(cmd)}, timeout: ${rule.timeout} }]`)
+ return
+ }
+
+ const next = `${cleaned.replace(/\s*$/, '')}\n${hooksBlock(rule, cmd)}`
+ if (next === config) {
+ allowlistHook(rule, cmd, home) // keep the allowlist in sync even when the block is current
+ console.log(rule.messages.current + (home === rule.home ? '' : ` (${basename(home)})`))
+ return
+ }
+
+ try {
+ writeFileSync(configPath, next)
+ allowlistHook(rule, cmd, home)
+ console.log(
+ removed > 1
+ ? message(rule.messages.collapsed, { removed: String(removed), file: configPath })
+ : message(rule.messages.installed, { file: configPath }),
+ )
+ console.log(rule.messages.after)
+ } catch (err) {
+ console.error(rule.messages.failed, err)
+ }
+}
+
diff --git a/cli/src/engines/kit/nativePlugin.ts b/cli/src/engines/kit/nativePlugin.ts
new file mode 100644
index 000000000..21cf1d2fd
--- /dev/null
+++ b/cli/src/engines/kit/nativePlugin.ts
@@ -0,0 +1,56 @@
+/** Native plugin bytes are engine declarations. Installing them never loads an interpreter. */
+import { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, unlinkSync } from 'node:fs'
+import { dirname } from 'node:path'
+
+export interface NativePlugin {
+ file: string
+ template: readonly (string | { argument: 'port' | 'credential' | 'version' })[]
+ directories?: readonly { path: string; mode?: number }[]
+ messages: { current: string; installed: string; after: readonly string[]; failed: string }
+}
+export interface NativePluginValues { port: string; credential: string; version: string }
+
+/** Joining parts once keeps a path's contents literal, even when it resembles a template argument. */
+export function nativePluginSource(rule: NativePlugin, values: NativePluginValues): string {
+ return rule.template.map(part => typeof part === 'string' ? part : values[part.argument]).join('')
+}
+
+export function installNativePlugin(rule: NativePlugin, values: NativePluginValues): void {
+ const source = nativePluginSource(rule, values)
+ const file = rule.file
+ try {
+ if (existsSync(file) && readFileSync(file, 'utf-8') === source) {
+ console.log(rule.messages.current)
+ return
+ }
+ } catch { /* unreadable — rewrite it */ }
+ try {
+ mkdirSync(dirname(file), { recursive: true })
+ for (const directory of rule.directories ?? []) mkdirSync(directory.path, { recursive: true, mode: directory.mode })
+ const tmp = `${file}.${process.pid}.tmp`
+ writeFileSync(tmp, source)
+ renameSync(tmp, file)
+ console.log(rule.messages.installed.replace('{file}', () => file))
+ for (const line of rule.messages.after) console.log(line)
+ } catch (err) { console.error(rule.messages.failed, err) }
+}
+
+export interface NativePluginRemoval {
+ file: string
+ prefix: string
+ contains: string
+ removed: string
+ failed: string
+}
+/** The engine may still discover an older plugin with an incompatible API. Remove only our artifact. */
+export function removeNativePlugin(rule: NativePluginRemoval): void {
+ try {
+ const source = readFileSync(rule.file, 'utf8')
+ if (source.startsWith(rule.prefix) && source.includes(rule.contains)) {
+ unlinkSync(rule.file)
+ console.log(rule.removed)
+ }
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') console.error(rule.failed, err)
+ }
+}
diff --git a/cli/src/engines/nativeHooks.eager.spec.ts b/cli/src/engines/nativeHooks.eager.spec.ts
new file mode 100644
index 000000000..541f90368
--- /dev/null
+++ b/cli/src/engines/nativeHooks.eager.spec.ts
@@ -0,0 +1,19 @@
+import { expect, it, vi } from 'vitest'
+import { mkdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
+import { opencodeBin } from '../lib/engineBin.js'
+import { loadEngine } from './inProcess.js'
+
+vi.mock('node:fs', async real => ({ ...await real<object>(),
+ mkdirSync: vi.fn(() => { throw new Error('directory created while importing native hooks') }),
+ renameSync: vi.fn(() => { throw new Error('file replaced while importing native hooks') }),
+ unlinkSync: vi.fn(() => { throw new Error('file removed while importing native hooks') }),
+ writeFileSync: vi.fn(() => { throw new Error('file written while importing native hooks') }),
+}))
+vi.mock('../lib/engineBin.js', () => ({ opencodeBin: vi.fn(() => { throw new Error('native executable resolved during import') }) }))
+vi.mock('./inProcess.js', () => ({ loadEngine: vi.fn(() => { throw new Error('optional code requested during import') }) }))
+
+it('composes hook declarations without probing, installing or requesting optional code', async () => {
+ const hooks = await import('./nativeHooks.js')
+ expect(Object.keys(hooks)).toHaveLength(11)
+ for (const operation of [opencodeBin, loadEngine, mkdirSync, renameSync, unlinkSync, writeFileSync]) expect(operation).not.toHaveBeenCalled()
+})
diff --git a/cli/src/engines/nativeHooks.ts b/cli/src/engines/nativeHooks.ts
new file mode 100644
index 000000000..30cbdace4
--- /dev/null
+++ b/cli/src/engines/nativeHooks.ts
@@ -0,0 +1,44 @@
+/** Native hook installation is eager. Optional transcript and screen readers own no hook files. */
+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 { KILO_PLUGIN } from './kilo/contract.js'
+import { PI_EXTENSION } from './pi/contract.js'
+import { AMP_PLUGIN } from './amp/contract.js'
+import { HERMES_HOOK_SETTINGS } from './hermes/contract.js'
+import { opencodeMajorVersion } from './launchControl.js'
+import { installNativePlugin, removeNativePlugin } from './kit/nativePlugin.js'
+import { installNativeYamlHooks } from './kit/nativeHookYaml.js'
+import { command } from './kit/notifyHooks.js'
+import { GROK_HOOK_SETTINGS } from './grok/contract.js'
+import { AGY_HOOK_SETTINGS } from './agy/contract.js'
+import { COPILOT_HOOK_SETTINGS } from './copilot/contract.js'
+import { CURSOR_HOOK_SETTINGS } from './cursor/contract.js'
+import { COMMANDCODE_HOOK_SETTINGS } from './commandcode/contract.js'
+import { DEVIN_HOOK_SETTINGS } from './devin/contract.js'
+import { installNativeHookSettings } from './kit/nativeHookSettings.js'
+
+export const installGrokHooks = (port: number): void => installNativeHookSettings(GROK_HOOK_SETTINGS, port)
+export const installAgyHooks = (port: number): void => installNativeHookSettings(AGY_HOOK_SETTINGS, port)
+export const installCopilotHooks = (port: number): void => installNativeHookSettings(COPILOT_HOOK_SETTINGS, port)
+export const installCursorHooks = (port: number): void => installNativeHookSettings(CURSOR_HOOK_SETTINGS, port)
+export const installCommandCodeHooks = (port: number): void => installNativeHookSettings(COMMANDCODE_HOOK_SETTINGS, port)
+export const installDevinHooks = (port: number): void => installNativeHookSettings(DEVIN_HOOK_SETTINGS, port)
+
+const pluginValues = (port: number) => ({
+ port: String(port), credential: JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential')), version: JSON.stringify(VERSION),
+})
+export const installKiloPlugin = (port: number): void => installNativePlugin(KILO_PLUGIN, pluginValues(port))
+export const installPiExtension = (port: number): void => installNativePlugin(PI_EXTENSION, pluginValues(port))
+export const installAmpPlugin = (port: number): void => installNativePlugin(AMP_PLUGIN, pluginValues(port))
+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)
+}
diff --git a/cli/src/engines/opencode/contract.ts b/cli/src/engines/opencode/contract.ts
index cab33b3ff..3c81648e3 100644
--- a/cli/src/engines/opencode/contract.ts
+++ b/cli/src/engines/opencode/contract.ts
@@ -1,3 +1,5 @@
+import { join as hookPath, dirname as hookParent } from 'node:path'
+import { env as hookEnvironment } from '../../config/env.js'
/**
* What the core knows of OpenCode without loading its code: declared data, read in line where a launch is built
* (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of OpenCode's code.
@@ -35,3 +37,151 @@ export const OPENCODE_SESSION_MODEL = {
fields: { data: 'data', model: 'model', id: 'id', alternativeId: 'modelID', provider: 'providerID', variant: 'variant' },
},
} as const
+
+/** Native source runs in the engine process; the daemon only renders and installs these bytes. */
+export const OPENCODE_LEGACY_PLUGIN = {
+ file: hookPath(hookEnvironment.OPENCODE_PLUGIN_DIR, 'launcher-register.js'),
+ template: [
+`// session-register — auto-installed by the machine adapter. Binds this `,
+"OpenCode",
+` session to the
+// local machine daemon (127.0.0.1:`,
+{ argument: 'port' },
+`) so it can be mirrored to web/device. No-op if machine isn't running.
+import { readFileSync } from "node:fs"
+const hookToken = () => { try { return readFileSync(`,
+{ argument: 'credential' },
+`, "utf8").trim() } catch { return "" } }
+export const MachineRegister = async ({ directory, worktree, project, client }) => {
+ const seen = new Set()
+ const post = async (sessionID) => {
+ const pane = process.env.TMUX_PANE
+ const token = hookToken()
+ if (!pane || !token || !sessionID || seen.has(sessionID)) return
+ seen.add(sessionID)
+ try {
+ await fetch("http://127.0.0.1:`,
+{ argument: 'port' },
+`/api/hook/session-start", {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-harness-hook-token": token },
+ body: JSON.stringify({
+ engine: "`,
+"opencode",
+`",
+ pluginVersion: `,
+{ argument: 'version' },
+`,
+ sessionId: sessionID,
+ cwd: directory || worktree || (project && project.worktree) || null,
+ tmuxPane: pane,
+ callerPid: process.pid,
+ runtimeHints: [
+ ...(pane ? [{ backend: "tmux", paneId: pane }] : []),
+ ],
+ }),
+ })
+ } catch {}
+ }
+ return {
+ event: async ({ event }) => {
+ if (!event) return
+ if (event.type === "session.created" || event.type === "session.updated") {
+ const p = event.properties || {}
+ const info = p.info || {}
+ if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent
+ await post(info.id || p.sessionID || p.sessionId)
+ }
+ },
+ }
+}
+`
+],
+ messages: {
+ "current": "[hooks] OpenCode discovery plugin already installed",
+ "installed": "[hooks] installed OpenCode discovery plugin → {file}",
+ "after": [
+ "[hooks] (takes effect on the next opencode session start)"
+ ],
+ "failed": "[hooks] failed to write OpenCode plugin:"
+},
+} as const satisfies import('../kit/nativePlugin.js').NativePlugin
+
+/** Native source runs in the engine process; the daemon only renders and installs these bytes. */
+export const OPENCODE_TUI_PLUGIN = {
+ file: hookPath(hookParent(hookEnvironment.OPENCODE_PLUGIN_DIR), 'plugins', 'launcher-register', 'tui.js'),
+ template: [
+`// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine
+// daemon (127.0.0.1:`,
+{ argument: 'port' },
+`) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.
+import { readFileSync } from "node:fs"
+const hookToken = () => { try { return readFileSync(`,
+{ argument: 'credential' },
+`, "utf8").trim() } catch { return "" } }
+export default {
+ id: "harness-session-register",
+ setup(ctx) {
+ const pane = process.env.TMUX_PANE
+ const router = ctx && ctx.ui && ctx.ui.router
+ if (!pane || !router || typeof router.current !== "function") return
+ const posted = new Set()
+ let busy = false
+ const post = async (sessionID) => {
+ const token = hookToken()
+ if (!token || !sessionID || posted.has(sessionID) || busy) return
+ busy = true
+ try {
+ let info
+ try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}
+ if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card
+ const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()
+ const res = await fetch("http://127.0.0.1:`,
+{ argument: 'port' },
+`/api/hook/session-start", {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-harness-hook-token": token },
+ body: JSON.stringify({
+ engine: "opencode",
+ pluginVersion: `,
+{ argument: 'version' },
+`,
+ sessionId: sessionID,
+ cwd,
+ tmuxPane: pane,
+ callerPid: process.pid,
+ runtimeHints: [{ backend: "tmux", paneId: pane }],
+ }),
+ })
+ if (res && res.ok) posted.add(sessionID)
+ } catch {} finally { busy = false }
+ }
+ const check = () => {
+ try { const at = router.current(); if (at && at.type === "session" && at.sessionID) post(at.sessionID) } catch {}
+ }
+ check()
+ const timer = setInterval(check, 1000)
+ if (timer && typeof timer.unref === "function") timer.unref()
+ return () => clearInterval(timer)
+ },
+}
+`
+],
+ messages: {
+ "current": "[hooks] OpenCode 2 TUI discovery plugin already installed",
+ "installed": "[hooks] installed OpenCode 2 TUI discovery plugin → {file}",
+ "after": [
+ "[hooks] (takes effect on the next opencode session start)"
+ ],
+ "failed": "[hooks] failed to write OpenCode 2 TUI plugin:"
+},
+} as const satisfies import('../kit/nativePlugin.js').NativePlugin
+
+/** V2 also discovers the legacy directory but rejects its API. A foreign plugin is never ours to remove. */
+export const OPENCODE_LEGACY_REMOVAL = {
+ file: OPENCODE_LEGACY_PLUGIN.file,
+ prefix: '// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n',
+ contains: 'export const MachineRegister =',
+ removed: '[hooks] removed incompatible OpenCode 1 discovery plugin',
+ failed: '[hooks] failed to remove OpenCode 1 plugin:',
+} as const
diff --git a/cli/src/engines/pi/contract.ts b/cli/src/engines/pi/contract.ts
index 3e9866c89..bf3245827 100644
--- a/cli/src/engines/pi/contract.ts
+++ b/cli/src/engines/pi/contract.ts
@@ -1,3 +1,5 @@
+import { join as hookPath } from 'node:path'
+import { env as hookEnvironment } from '../../config/env.js'
/** Pi's folder is lossy. Only its complete first entry establishes the session id and cwd. */
import type { SessionFolder, SessionHeader } from '../kit/sessionIdentity.js'
@@ -10,3 +12,77 @@ export const PI_HEADER: SessionHeader = {
export const PI_FOLDER: SessionFolder = {
prefix: '--', suffix: '--', trim: /^[/\\]/, mangle: /[/\\:]/g, replacement: '-',
}
+
+/** Native source runs in the engine process; the daemon only renders and installs these bytes. */
+export const PI_EXTENSION = {
+ file: hookPath(hookEnvironment.PI_HOME, 'agent', 'extensions', 'launcher-register.ts'),
+ template: [
+`// session-register — auto-installed by the machine adapter. Binds this Pi session to the local
+// machine daemon (127.0.0.1:`,
+{ argument: 'port' },
+`) so it can be mirrored to web/device. No-op if machine isn't running.
+import { existsSync, readFileSync } from "node:fs";
+import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
+
+export default function (pi: ExtensionAPI) {
+ let announced = false; // posted at least once (the transcript may not exist yet)
+ let registered = false; // posted with a real, on-disk transcript — nothing left to do
+
+ const register = async (ctx: any) => {
+ const pane = process.env.TMUX_PANE;
+ let token = "";
+ try { token = readFileSync(`,
+{ argument: 'credential' },
+`, "utf8").trim(); } catch {}
+ if (!pane || !token) return;
+ // Pi knows the session file path immediately but only WRITES it once the first assistant message
+ // lands. Sending a path that isn't on disk yet is rejected by the daemon (it validates the file),
+ // so announce without one first and attach the real path on a later turn.
+ const file = ctx?.sessionManager?.getSessionFile?.() ?? null;
+ const ready = !!file && existsSync(file);
+ if (registered || (announced && !ready)) return;
+ const sessionId = ctx?.sessionManager?.getSessionId?.();
+ if (!sessionId) return;
+ try {
+ const res = await fetch("http://127.0.0.1:`,
+{ argument: 'port' },
+`/api/hook/session-start", {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-harness-hook-token": token },
+ body: JSON.stringify({
+ engine: "pi",
+ pluginVersion: `,
+{ argument: 'version' },
+`,
+ sessionId,
+ transcriptPath: ready ? file : undefined,
+ cwd: ctx?.cwd ?? undefined,
+ tmuxPane: pane,
+ callerPid: process.pid,
+ runtimeHints: [
+ ...(pane ? [{ backend: "tmux", paneId: pane }] : []),
+ ],
+ }),
+ });
+ if (!res.ok) return; // daemon refused (e.g. transcript not readable yet) — retry on the next turn
+ announced = true;
+ if (ready) registered = true;
+ } catch {}
+ };
+
+ // session_start fires before the transcript exists; the turn hooks catch it once it does.
+ pi.on("session_start", async (_event, ctx) => { await register(ctx); });
+ pi.on("turn_start", async (_event, ctx) => { await register(ctx); });
+ pi.on("turn_end", async (_event, ctx) => { await register(ctx); });
+}
+`
+],
+ messages: {
+ "current": "[hooks] Pi discovery extension already installed",
+ "installed": "[hooks] installed Pi discovery extension → {file}",
+ "after": [
+ "[hooks] (takes effect on the next pi session start)"
+ ],
+ "failed": "[hooks] failed to write Pi extension:"
+},
+} as const satisfies import('../kit/nativePlugin.js').NativePlugin
diff --git a/cli/src/leanEntry.spec.ts b/cli/src/leanEntry.spec.ts
index 9ad3ccb7a..29ea42c6c 100644
--- a/cli/src/leanEntry.spec.ts
+++ b/cli/src/leanEntry.spec.ts
@@ -88,13 +88,11 @@ describe('the lean bundle a release carries', () => {
})
it.each([
- // Each a string its module alone holds: lib/questionPane.ts's, lib/hooks.ts's (its Amp plugin's), Amp's thread
- // export's (engines/amp/threadExport.ts), and the name the bundle keeps for Cursor's sub-agents' reader
+ // Each a string its module alone holds: lib/questionPane.ts's, Amp's thread export's (engines/amp/threadExport.ts), and the name the bundle keeps for Cursor's sub-agents' reader
// (engines/cursor/subagent.ts), Devin's switch reader (engines/devin/runtimeProfile.ts), the compatibility
// wrappers for agy's lock lookup and Cursor discovery, and Hermes's optional adoption reader. Core
// identity and discovery use eager declarations/kit mechanics instead of those optional wrappers.
['pane readers', 'Native screen reader must be injected'],
- ['hook installers', 'Mirrors this Amp thread to the machine adapter'],
['own code: Amp\'s', 'AMP_DISABLE_PLUGINS'],
['own code: Cursor\'s', '"loadCursorReplayTaskLinks"'],
['runtime profiles: Devin\'s', '"devinModelCommandResult"'],
@@ -108,6 +106,16 @@ describe('the lean bundle a release carries', () => {
expect([...loads('core')].filter((name) => files.get(name)!.includes(marker))).toEqual([])
})
+ it('loads native hook declarations eagerly without importing the optional compatibility entry', () => {
+ const core = loads('core')
+ // This is native source data written into Amp's plugin file, not Amp's optional transcript reader.
+ // Readiness and launch must not depend on an import() before the core can install that file.
+ const declaration = 'Mirrors this Amp thread to the machine adapter'
+ expect([...core].filter(name => files.get(name)!.includes(declaration))).toHaveLength(1)
+ expect([...core].some(name => name.startsWith('core-hooks-'))).toBe(false)
+ expect([...files.keys()].some(name => name.startsWith('core-hooks-'))).toBe(true)
+ })
+
it('gives the core its own code and none of the CLI\'s commands, which parsing cli.js cost it', () => {
const core = loads('core')
const text = [...core].map((name) => files.get(name)!).join('\n')
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index 59a7d20dd..3a929a2bd 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -1,1003 +1,4 @@
-/** Hook installers for engines still awaiting migration to their hooks facet. */
-
-import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync } from 'fs'
-import { basename, join, dirname } from 'path'
-import { cursorConfigDir, cursorDataDir } from '../engines/cursor/home.js'
-import { env } from '../config/env.js'
-import { VERSION } from '../version.js'
-import { hermesConfigHomes } from '../engines/hermes/home.js'
-import { opencodeMajorVersion } from '../engines/launchControl.js'
-import { command, isOurs, writeJsonAtomic, type HookBlock, type Settings } from '../engines/kit/notifyHooks.js'
-
-const GROK_HOOKS_PATH = join(env.GROK_HOME, 'hooks', 'harness.json')
-const CURSOR_HOOKS_PATH = join(cursorConfigDir(), 'hooks.json')
-// agy reads hooks from its SHARED customization root (~/.gemini/config), not from its own state dir —
-// the CLI's changelog records the move, "ensuring hooks remain synchronized between the TUI and the
-// backend". Verified live: a hooks.json placed there fires for `agy` in a pane.
-const AGY_HOOKS_PATH = join(env.AGY_CONFIG_DIR, 'hooks.json')
-// Copilot reads every *.json in this directory, so Harness gets its own file and never edits the
-// user's. Measured: a file dropped here fires without any further opt-in.
-const COPILOT_HOOKS_PATH = join(env.COPILOT_HOME, 'hooks', 'harness.json')
-
-/** Merge the adapter's Grok lifecycle hooks into a dedicated global hook file. Grok loads every JSON
- * file in ~/.grok/hooks, so using our own file avoids touching the user's other hook packages. Normal
- * Stop is intentionally omitted because its record precedes Grok's final assistant chunk on disk. */
-export function installGrokHooks(port: number): void {
- let settings: Settings = {}
- if (existsSync(GROK_HOOKS_PATH)) {
- try {
- settings = JSON.parse(readFileSync(GROK_HOOKS_PATH, 'utf-8')) as Settings
- } catch {
- console.error(`[hooks] Grok hooks file is invalid JSON; leaving it unchanged: ${GROK_HOOKS_PATH}`)
- console.error('[hooks] fix the file, then restart harness login')
- return
- }
- }
- if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
-
- const cmd = command(port, 'grok')
- const required = ['SessionStart', 'SessionEnd', 'UserPromptSubmit', 'StopFailure'] as const
- let changed = false
- for (const event of required) {
- const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []
- const foreign = blocks.filter((b) => !isOurs(b))
- const ours = blocks.filter(isOurs)
- const canonical: HookBlock = { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }
- if (ours.length !== 1 || ours[0]?.hooks?.[0]?.command !== cmd) changed = true
- settings.hooks[event] = [...foreign, canonical]
- }
-
- if (!changed) {
- console.log('[hooks] Grok lifecycle/StopFailure hooks already installed')
- return
- }
- try {
- writeJsonAtomic(GROK_HOOKS_PATH, settings)
- console.log(`[hooks] installed Grok lifecycle/StopFailure hooks → ${GROK_HOOKS_PATH}`)
- console.log('[hooks] (takes effect on the next Grok session start)')
- } catch (err) {
- console.error('[hooks] failed to write Grok hook file:', err)
- }
-}
-
-/**
- * agy's hook file is a map of NAMED blocks, each holding per-event handler lists — a different shape
- * from every other engine here, so it gets its own writer rather than reusing `Settings`.
- *
- * Only two events are installed, and the omissions are the point:
- *
- * - `PreToolUse` and `PostToolUse` are DELIBERATELY absent. `PreToolUse`'s contract makes `decision`
- * REQUIRED, and a handler that prints anything else — including the `{}` every other hook here
- * returns — is read as a denial: measured on a real pane as "Tool call denied by pre-tool hook" on
- * every call of the turn. Tool events come off the transcript anyway, so there is nothing to gain
- * and a working agent to lose.
- * - `PostInvocation` fires per model round-trip, not per turn, so it would add noise without adding a
- * boundary. `PreInvocation` is installed only for its FIRST firing, which announces the session.
- *
- * `Stop` is the turn boundary. Its output is safe: `{"decision":"continue"}` would BLOCK the stop, and
- * notify.mjs never prints that.
- */
-type AgyHookHandler = { type?: string; command: string; timeout?: number }
-type AgyHookFile = Record<string, { enabled?: boolean } & Record<string, unknown>>
-
-export function installAgyHooks(port: number): void {
- let file: AgyHookFile = {}
- if (existsSync(AGY_HOOKS_PATH)) {
- try {
- file = JSON.parse(readFileSync(AGY_HOOKS_PATH, 'utf-8')) as AgyHookFile
- } catch {
- console.error(`[hooks] agy hooks file is invalid JSON; leaving it unchanged: ${AGY_HOOKS_PATH}`)
- console.error('[hooks] fix the file, then restart harness login')
- return
- }
- }
- if (!file || typeof file !== 'object' || Array.isArray(file)) file = {}
-
- const cmd = command(port, 'agy')
- const handler = (event: string): AgyHookHandler => ({ type: 'command', command: `${cmd} --agy-event ${event}`, timeout: 10 })
- const block = { PreInvocation: [handler('PreInvocation')], Stop: [handler('Stop')] }
-
- const existing = file['harness'] as Record<string, AgyHookHandler[]> | undefined
- const same = JSON.stringify(existing) === JSON.stringify(block)
- if (same) {
- console.log('[hooks] agy lifecycle hooks already installed')
- return
- }
- // Every other named block belongs to the user; only ours is replaced.
- file['harness'] = block
- try {
- writeJsonAtomic(AGY_HOOKS_PATH, file)
- console.log(`[hooks] installed agy lifecycle hooks → ${AGY_HOOKS_PATH}`)
- console.log('[hooks] (takes effect on the next agy session start)')
- } catch (err) {
- console.error('[hooks] failed to write agy hook file:', err)
- }
-}
-
-/**
- * Copilot's user-level hooks: a directory of JSON files, each `{version, hooks: {<event>: [handler]}}`.
- *
- * Four events, and the omissions are deliberate:
- *
- * - `preToolUse` is NOT installed. Its exit-code contract is fail-CLOSED — the docs are explicit that
- * a non-zero exit denies the tool, while every other event fails open. A crashing hook would stop
- * the user's agent from running anything. Tool cards come off the transcript instead, which costs
- * nothing.
- * - `postToolUse` is not installed either: the same rows are already in `events.jsonl`, so posting
- * them would only duplicate work on every tool call.
- *
- * `agentStop` is the turn boundary and the one event that names the transcript
- * (`transcriptPath: <COPILOT_HOME>/session-state/<id>/events.jsonl`).
- */
-type CopilotHookFile = { version: number; hooks: Record<string, Array<{ type: string; command: string }>> }
-
-export function installCopilotHooks(port: number): void {
- const cmd = command(port, 'copilot')
- const handler = (event: string): { type: string; command: string } => ({ type: 'command', command: `${cmd} --copilot-event ${event}` })
- const file: CopilotHookFile = {
- version: 1,
- hooks: {
- sessionStart: [handler('sessionStart')],
- userPromptSubmitted: [handler('userPromptSubmitted')],
- agentStop: [handler('agentStop')],
- sessionEnd: [handler('sessionEnd')],
- },
- }
-
- let existing: unknown = null
- if (existsSync(COPILOT_HOOKS_PATH)) {
- try { existing = JSON.parse(readFileSync(COPILOT_HOOKS_PATH, 'utf-8')) } catch { existing = null }
- }
- if (JSON.stringify(existing) === JSON.stringify(file)) {
- console.log('[hooks] Copilot lifecycle hooks already installed')
- return
- }
- try {
- writeJsonAtomic(COPILOT_HOOKS_PATH, file)
- console.log(`[hooks] installed Copilot lifecycle hooks → ${COPILOT_HOOKS_PATH}`)
- console.log('[hooks] (takes effect on the next copilot session start)')
- } catch (err) {
- console.error('[hooks] failed to write Copilot hook file:', err)
- }
-}
-
-interface CursorHook {
- command: string
- failClosed?: boolean
-}
-
-type CursorSettings = {
- version?: number
- hooks?: Record<string, CursorHook[]>
-} & Record<string, unknown>
-
-/** Merge Cursor's simpler user-hook schema. Cursor local CLI uses lower-camel event names and invokes
- * command entries directly, unlike Claude/Codex's nested matcher/hooks blocks. */
-export function installCursorHooks(port: number): void {
- let settings: CursorSettings = {}
- if (existsSync(CURSOR_HOOKS_PATH)) {
- try {
- settings = JSON.parse(readFileSync(CURSOR_HOOKS_PATH, 'utf-8')) as CursorSettings
- } catch {
- console.error(`[hooks] Cursor hooks file is invalid JSON; leaving it unchanged: ${CURSOR_HOOKS_PATH}`)
- return
- }
- }
- if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
- if (typeof settings.version !== 'number') settings.version = 1
-
- const cmd = command(port, 'cursor')
- const events = ['sessionStart', 'beforeSubmitPrompt', 'preToolUse', 'stop', 'sessionEnd'] as const
- let changed = false
- for (const event of events) {
- const entries = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []
- const foreign = entries.filter((entry) => !entry?.command?.includes('notify.mjs'))
- const ours = entries.filter((entry) => entry?.command?.includes('notify.mjs'))
- const canonical: CursorHook = { command: cmd, failClosed: false }
- if (ours.length !== 1 || ours[0]?.command !== cmd || ours[0]?.failClosed !== false) changed = true
- settings.hooks[event] = [...foreign, canonical]
- }
- if (!changed) {
- console.log('[hooks] Cursor lifecycle/task hooks already installed')
- return
- }
- try {
- writeJsonAtomic(CURSOR_HOOKS_PATH, settings)
- console.log(`[hooks] installed Cursor lifecycle/task hooks → ${CURSOR_HOOKS_PATH}`)
- } catch (err) {
- console.error('[hooks] failed to write Cursor hooks.json:', err)
- }
-}
-
-const OPENCODE_PLUGIN_PATH = join(env.OPENCODE_PLUGIN_DIR, 'launcher-register.js')
-// OpenCode 2.0's TUI plugins: `<config>/plugins/<dir>/tui.js` (plural, a directory) — beside the 1.x
-// `plugin/` file, which 1.x keeps reading as it always did.
-const OPENCODE_TUI_PLUGIN_PATH = join(dirname(env.OPENCODE_PLUGIN_DIR), 'plugins', 'launcher-register', 'tui.js')
-const KILO_PLUGIN_PATH = join(env.KILO_PLUGIN_DIR, 'launcher-register.js')
-
-/**
- * Discovery plugin for the opencode-family engines — opencode itself and `kilo`, which is its fork.
- *
- * Neither has shell hooks; discovery is a global plugin that POSTs each session to the daemon. The plugin
- * runs INSIDE every interactive process (so it sees `$TMUX_PANE` + the cwd) and fires on
- * session.created/updated. The recap workers run with `--pure`, which skips external plugins, so an
- * ephemeral summary session never self-registers.
- *
- * ONE template, two installers: the engine name is the only difference in the emitted source, and the two
- * install to different directories with their own log lines. The engine modules are deliberately
- * duplicated so the forks can drift apart, but this template holds no engine behaviour to drift — if
- * kilo's plugin API ever diverges from opencode's, that is the moment to split this, not before.
- */
-function forkPluginSource(engine: 'opencode' | 'kilo', port: number): string {
- const product = engine === 'kilo' ? 'Kilo' : 'OpenCode'
- return `// session-register — auto-installed by the machine adapter. Binds this ${product} session to the
-// local machine daemon (127.0.0.1:${port}) so it can be mirrored to web/device. No-op if machine isn't running.
-import { readFileSync } from "node:fs"
-const hookToken = () => { try { return readFileSync(${JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential'))}, "utf8").trim() } catch { return "" } }
-export const MachineRegister = async ({ directory, worktree, project, client }) => {
- const seen = new Set()
- const post = async (sessionID) => {
- const pane = process.env.TMUX_PANE
- const token = hookToken()
- if (!pane || !token || !sessionID || seen.has(sessionID)) return
- seen.add(sessionID)
- try {
- await fetch("http://127.0.0.1:${port}/api/hook/session-start", {
- method: "POST",
- headers: { "content-type": "application/json", "x-harness-hook-token": token },
- body: JSON.stringify({
- engine: "${engine}",
- pluginVersion: ${JSON.stringify(VERSION)},
- sessionId: sessionID,
- cwd: directory || worktree || (project && project.worktree) || null,
- tmuxPane: pane,
- callerPid: process.pid,
- runtimeHints: [
- ...(pane ? [{ backend: "tmux", paneId: pane }] : []),
- ],
- }),
- })
- } catch {}
- }
- return {
- event: async ({ event }) => {
- if (!event) return
- if (event.type === "session.created" || event.type === "session.updated") {
- const p = event.properties || {}
- const info = p.info || {}
- if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent
- await post(info.id || p.sessionID || p.sessionId)
- }
- },
- }
-}
-`
-}
-
-/**
- * OpenCode 2.0's discovery plugin: the same session-start the 1.x plugin posts, from where 2.0 still
- * knows the pane.
- *
- * Measured on 2.0.18 (upstream v2.0.18 source): a plugin must `export default { id, setup }` — the 1.x
- * named export fails to load ("Plugin must export a default definition"); server plugins run in ONE
- * background service shared by every TUI, whose environment has no `TMUX_PANE`, and whose events carry
- * no client — so no server plugin can say which pane a session is in. A TUI plugin runs in the pane's
- * own process: `process.env.TMUX_PANE` is the pane, and `ui.router.current()` is the session it shows.
- * It posts that session — and the next one, when the pane switches (`/sessions`, a tab) — skipping a
- * sub-agent's (it has a parent), each once. Polled: the router is a store, and a missed event costs a
- * second, not a binding. Without a pane, a token or the router (another 2.x), it does nothing.
- */
-function opencodeTuiPluginSource(port: number): string {
- return `// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine
-// daemon (127.0.0.1:${port}) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.
-import { readFileSync } from "node:fs"
-const hookToken = () => { try { return readFileSync(${JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential'))}, "utf8").trim() } catch { return "" } }
-export default {
- id: "harness-session-register",
- setup(ctx) {
- const pane = process.env.TMUX_PANE
- const router = ctx && ctx.ui && ctx.ui.router
- if (!pane || !router || typeof router.current !== "function") return
- const posted = new Set()
- let busy = false
- const post = async (sessionID) => {
- const token = hookToken()
- if (!token || !sessionID || posted.has(sessionID) || busy) return
- busy = true
- try {
- let info
- try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}
- if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card
- const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()
- const res = await fetch("http://127.0.0.1:${port}/api/hook/session-start", {
- method: "POST",
- headers: { "content-type": "application/json", "x-harness-hook-token": token },
- body: JSON.stringify({
- engine: "opencode",
- pluginVersion: ${JSON.stringify(VERSION)},
- sessionId: sessionID,
- cwd,
- tmuxPane: pane,
- callerPid: process.pid,
- runtimeHints: [{ backend: "tmux", paneId: pane }],
- }),
- })
- if (res && res.ok) posted.add(sessionID)
- } catch {} finally { busy = false }
- }
- const check = () => {
- try { const at = router.current(); if (at && at.type === "session" && at.sessionID) post(at.sessionID) } catch {}
- }
- check()
- const timer = setInterval(check, 1000)
- if (timer && typeof timer.unref === "function") timer.unref()
- return () => clearInterval(timer)
- },
-}
-`
-}
-
-const COMMANDCODE_SETTINGS_PATH = join(env.COMMANDCODE_HOME, 'settings.json')
-// Command Code exposes only SessionStart / PreToolUse / PostToolUse / Stop — there is NO
-// UserPromptSubmit (so no catch-hook re-register) and no SessionEnd (the tmux reaper covers that).
-// Stop is the authoritative turn close, same as claude's.
-//
-// PreToolUse is here as the TURN-OPEN signal, and it is the only one this engine has. Command Code
-// writes its transcript in one flush when the turn finishes — the user line and the assistant line carry
-// the same millisecond — so tailing the JSONL cannot open a turn either. With only SessionStart/Stop the
-// adapter first heard about a turn when it was already over and emitted turn_started+turn_ended in the
-// same millisecond, so the device never showed "working": the tile went straight from idle to the recap.
-const COMMANDCODE_EVENTS = ['SessionStart', 'PreToolUse', 'Stop'] as const
-
-/**
- * Command Code's hook file is `~/.commandcode/settings.json` with the SAME nested `matcher`/`hooks`
- * schema as `~/.claude/settings.json`, so this mirrors Claude Code's hook settings
- * (engines/claude/hookContract.ts) — including its dedup discipline: every "ours" block (any command
- * mentioning notify.mjs, whatever its old path/port) is collapsed into exactly one canonical entry, and
- * foreign blocks are preserved untouched.
- */
-export function installCommandCodeHooks(port: number): void {
- let settings: Settings = {}
- if (existsSync(COMMANDCODE_SETTINGS_PATH)) {
- try {
- settings = JSON.parse(readFileSync(COMMANDCODE_SETTINGS_PATH, 'utf-8')) as Settings
- } catch {
- console.error(`[hooks] Command Code settings file is invalid JSON; leaving it unchanged: ${COMMANDCODE_SETTINGS_PATH}`)
- return
- }
- }
- if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
-
- const cmd = command(port, 'commandcode')
- let changed = false
- for (const event of COMMANDCODE_EVENTS) {
- const blocks = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : []
- const foreign = blocks.filter((b) => !isOurs(b))
- const ours = blocks.filter(isOurs)
- if (ours.length !== 1 || ours[0]?.hooks?.[0]?.command !== cmd) changed = true
- settings.hooks[event] = [...foreign, { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]
- }
-
- if (!changed) {
- console.log('[hooks] Command Code session hooks already installed')
- return
- }
- try {
- writeJsonAtomic(COMMANDCODE_SETTINGS_PATH, settings)
- console.log(`[hooks] installed Command Code SessionStart/Stop hooks → ${COMMANDCODE_SETTINGS_PATH}`)
- console.log('[hooks] (takes effect on the next commandcode session start)')
- } catch (err) {
- console.error('[hooks] failed to write Command Code settings.json:', err)
- }
-}
-
-// Devin reads Claude's hook schema verbatim (its binary parses `ClaudeHookConfig`/`ClaudeHookMatcherConfig`),
-// so the only differences from Claude Code's hook settings (engines/claude/hookContract.ts) are the file and
-// that hooks nest under a "hooks" key of the user's general config — which also holds `devin.org_id`,
-// `theme_mode`, etc, so this MERGES and never rewrites the file wholesale. Verified live:
-// SessionStart/UserPromptSubmit/Stop all fire with `$TMUX_PANE` intact; the payload carries
-// {hook_event_name, session_id, prompt_id, prompt, source} but NO transcript_path and NO cwd (notify.mjs
-// derives cwd from its own process).
-const DEVIN_EVENTS = ['SessionStart', 'UserPromptSubmit', 'Stop', 'SessionEnd'] as const
-
-export function installDevinHooks(port: number): void {
- let config: Settings & Record<string, unknown> = {}
- if (existsSync(env.DEVIN_CONFIG_PATH)) {
- try {
- config = JSON.parse(readFileSync(env.DEVIN_CONFIG_PATH, 'utf-8')) as Settings & Record<string, unknown>
- } catch {
- console.error(`[hooks] Devin config file is invalid JSON; leaving it unchanged: ${env.DEVIN_CONFIG_PATH}`)
- return
- }
- }
- if (!config.hooks || typeof config.hooks !== 'object') config.hooks = {}
-
- const cmd = command(port, 'devin')
- let changed = false
- for (const event of DEVIN_EVENTS) {
- const blocks = Array.isArray(config.hooks[event]) ? config.hooks[event] : []
- const foreign = blocks.filter((b) => !isOurs(b))
- const ours = blocks.filter(isOurs)
- if (ours.length !== 1 || ours[0]?.hooks?.[0]?.command !== cmd) changed = true
- config.hooks[event] = [...foreign, { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]
- }
-
- if (!changed) {
- console.log('[hooks] Devin session hooks already installed')
- return
- }
- try {
- writeJsonAtomic(env.DEVIN_CONFIG_PATH, config)
- console.log(`[hooks] installed Devin SessionStart/UserPromptSubmit/Stop/SessionEnd hooks → ${env.DEVIN_CONFIG_PATH}`)
- console.log('[hooks] (takes effect on the next devin session start)')
- } catch (err) {
- console.error('[hooks] failed to write Devin config.json:', err)
- }
-}
-
-const HERMES_CONFIG_PATH = join(env.HERMES_HOME, 'config.yaml')
-// The managed block is delimited by BEGIN/END so it can be replaced unambiguously. (An earlier version
-// used a single marker line and a lookahead regex, which only replaced the comment and orphaned the old
-// `hooks:` mapping — YAML then took the LAST duplicate key, so a stale block silently won.)
-const HERMES_BLOCK_BEGIN = '# machine-adapter: session discovery (managed block — safe to delete)'
-const HERMES_BLOCK_END = '# machine-adapter: end'
-// `on_session_start` fires ONLY for brand-new sessions, so `pre_llm_call` (once per turn, in every
-// session incl. `hermes -c`/`--resume`) is the real beacon. Registration is idempotent.
-const HERMES_HOOK_EVENTS = ['on_session_start', 'pre_llm_call'] as const
-
-/** Hermes gates every (event, command) pair behind ~/.hermes/shell-hooks-allowlist.json; an unapproved
- * hook is SILENTLY skipped in non-TTY runs. Record ours so it fires without an interactive prompt. */
-function allowlistHermesHook(cmd: string, home: string): void {
- const allowlistPath = join(home, 'shell-hooks-allowlist.json')
- let data: { approvals?: Array<{ event?: string; command?: string }> } = { approvals: [] }
- try {
- const parsed = JSON.parse(readFileSync(allowlistPath, 'utf-8')) as typeof data
- if (parsed && Array.isArray(parsed.approvals)) data = parsed
- } catch { /* absent or unreadable → start from an empty skeleton */ }
- const previous = data.approvals ?? []
- // Drop OUR stale approvals before adding the current one. Each command change — a new port, a moved
- // install, a new Node runtime — otherwise leaves five dead entries here forever, and the entry is
- // dead the moment the command string it approves is no longer the one we install. Foreign approvals
- // are somebody else's business and are copied through untouched.
- const isOurStaleApproval = (a: { command?: string }) =>
- typeof a?.command === 'string' &&
- a.command.includes('notify.mjs') &&
- a.command.includes('--engine hermes') &&
- a.command !== cmd
- const approvals = previous.filter((a) => !isOurStaleApproval(a))
- let changed = approvals.length !== previous.length
- for (const event of HERMES_HOOK_EVENTS) {
- // Hermes matches on EXACT (event, command) string equality.
- if (approvals.some((a) => a?.event === event && a?.command === cmd)) continue
- approvals.push({ event, command: cmd })
- changed = true
- }
- if (!changed) return
- writeJsonAtomic(allowlistPath, { ...data, approvals })
-}
-
-function hermesHooksBlock(cmd: string): string {
- const entries = HERMES_HOOK_EVENTS
- .map((event) => ` ${event}:\n - command: ${JSON.stringify(cmd)}\n timeout: 10`)
- .join('\n')
- return `\n${HERMES_BLOCK_BEGIN}\nhooks:\n${entries}\n${HERMES_BLOCK_END}\n`
-}
-
-/** True for a top-level `hooks:` mapping that is ours (every command runs our notify.mjs for hermes). */
-function isMachineHooksBody(body: string[]): boolean {
- const commands = body.filter((line) => /^\s*- command:/.test(line))
- return commands.length > 0 && commands.every((line) => line.includes('notify.mjs') && line.includes('--engine hermes'))
-}
-
-/**
- * Strip every block this installer owns: the delimited BEGIN…END form AND any bare `hooks:` mapping
- * left behind by the earlier buggy rewrite (identified by its notify.mjs commands). Returns the cleaned
- * document plus whether a FOREIGN `hooks:` key survives — the caller must not touch the file then.
- */
-function stripMachineHermesBlocks(config: string): { cleaned: string; foreignHooks: boolean; removed: number } {
- const lines = config.split('\n')
- const out: string[] = []
- let removed = 0
- let foreignHooks = false
-
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i]
- if (line.trim() === HERMES_BLOCK_BEGIN) {
- // Skip through the END marker (or, for a truncated block, to the end of the mapping).
- let j = i + 1
- while (j < lines.length && lines[j].trim() !== HERMES_BLOCK_END) j++
- i = j < lines.length ? j : lines.length - 1
- removed++
- continue
- }
- if (/^hooks:\s*$/.test(line)) {
- let j = i + 1
- while (j < lines.length && (lines[j].startsWith(' ') || lines[j].startsWith('\t') || lines[j].trim() === '')) j++
- const body = lines.slice(i + 1, j)
- if (isMachineHooksBody(body)) { removed++; i = j - 1; continue }
- foreignHooks = true
- out.push(line)
- continue
- }
- out.push(line)
- }
- return { cleaned: out.join('\n').replace(/\n{3,}$/, '\n'), foreignHooks, removed }
-}
-
-/**
- * Install the Hermes shell hooks. Unlike the other engines Hermes has no dedicated hooks file — they
- * live in the user's main `~/.hermes/config.yaml`. We therefore own exactly one delimited block: every
- * previous machine block is stripped first and a single fresh one appended, so a port/path change can
- * never leave a duplicate `hooks:` key behind (YAML resolves duplicates to the LAST one, which silently
- * pinned sessions to a stale block). A `hooks:` key that is NOT ours means the user manages their own —
- * leave the file untouched and print what to add.
- */
-export function installHermesHooks(port: number): void {
- // EVERY home, each with its OWN path baked into its block.
- //
- // ⚠️ A PROFILE'S CONFIG IS A COPY, AND NOTHING WAS MAINTAINING IT. `hermes profile create` copies
- // `~/.hermes/config.yaml`, managed block and all — so a profile made after an install carried a
- // frozen command (an older node path, an older port) that no installer ever revisited, and the
- // `--hermes-home` in it named the DEFAULT home rather than the profile's own. The hook then looked
- // its session up in a store the session was not in (openharness#191). Walking the profiles fixes
- // both: the drift, and the home.
- for (const home of hermesConfigHomes()) installHermesHooksIn(port, home)
-}
-
-function installHermesHooksIn(port: number, home: string): void {
- const configPath = join(home, 'config.yaml')
- const cmd = command(port, 'hermes', env.CODEX_HOME, home)
- let config = ''
- try {
- config = readFileSync(configPath, 'utf-8')
- } catch {
- if (home === env.HERMES_HOME) console.log(`[hooks] no Hermes config at ${configPath} — skipping (run hermes once first)`)
- return
- }
-
- const { cleaned, foreignHooks, removed } = stripMachineHermesBlocks(config)
- if (foreignHooks) {
- console.error(`[hooks] ${configPath} has its own \`hooks:\` block — leaving it untouched.`)
- console.error('[hooks] add these entries under it manually to mirror Hermes sessions:')
- for (const event of HERMES_HOOK_EVENTS) console.error(`[hooks] ${event}: [{ command: ${JSON.stringify(cmd)}, timeout: 10 }]`)
- return
- }
-
- const next = `${cleaned.replace(/\s*$/, '')}\n${hermesHooksBlock(cmd)}`
- if (next === config) {
- allowlistHermesHook(cmd, home) // keep the allowlist in sync even when the block is current
- console.log(`[hooks] Hermes session hooks already installed${home === env.HERMES_HOME ? '' : ` (${basename(home)})`}`)
- return
- }
-
- try {
- writeFileSync(configPath, next)
- allowlistHermesHook(cmd, home)
- console.log(
- removed > 1
- ? `[hooks] installed Hermes session hooks (collapsed ${removed} stale blocks) → ${configPath}`
- : `[hooks] installed Hermes session hooks → ${configPath}`,
- )
- console.log('[hooks] (takes effect on the next hermes session start)')
- } catch (err) {
- console.error('[hooks] failed to write Hermes config.yaml:', err)
- }
-}
-
-const PI_EXTENSION_PATH = join(env.PI_HOME, 'agent', 'extensions', 'launcher-register.ts')
-
-/** Pi has no shell hooks either — discovery is a global TypeScript extension. It runs INSIDE every
- * interactive `pi` process (so it sees `$TMUX_PANE` and the session's own file path) and registers the
- * session with the local daemon. Pi buffers the transcript until the first assistant message, so the
- * session file may not exist yet at `session_start`; the extension re-registers on the first turn, once
- * `getSessionFile()` points at a real file. The recap worker runs with `--no-extensions`, so it never
- * registers itself. Global extensions load before the project-trust prompt, so this always fires. */
-function piExtensionSource(port: number): string {
- return `// session-register — auto-installed by the machine adapter. Binds this Pi session to the local
-// machine daemon (127.0.0.1:${port}) so it can be mirrored to web/device. No-op if machine isn't running.
-import { existsSync, readFileSync } from "node:fs";
-import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
-
-export default function (pi: ExtensionAPI) {
- let announced = false; // posted at least once (the transcript may not exist yet)
- let registered = false; // posted with a real, on-disk transcript — nothing left to do
-
- const register = async (ctx: any) => {
- const pane = process.env.TMUX_PANE;
- let token = "";
- try { token = readFileSync(${JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential'))}, "utf8").trim(); } catch {}
- if (!pane || !token) return;
- // Pi knows the session file path immediately but only WRITES it once the first assistant message
- // lands. Sending a path that isn't on disk yet is rejected by the daemon (it validates the file),
- // so announce without one first and attach the real path on a later turn.
- const file = ctx?.sessionManager?.getSessionFile?.() ?? null;
- const ready = !!file && existsSync(file);
- if (registered || (announced && !ready)) return;
- const sessionId = ctx?.sessionManager?.getSessionId?.();
- if (!sessionId) return;
- try {
- const res = await fetch("http://127.0.0.1:${port}/api/hook/session-start", {
- method: "POST",
- headers: { "content-type": "application/json", "x-harness-hook-token": token },
- body: JSON.stringify({
- engine: "pi",
- pluginVersion: ${JSON.stringify(VERSION)},
- sessionId,
- transcriptPath: ready ? file : undefined,
- cwd: ctx?.cwd ?? undefined,
- tmuxPane: pane,
- callerPid: process.pid,
- runtimeHints: [
- ...(pane ? [{ backend: "tmux", paneId: pane }] : []),
- ],
- }),
- });
- if (!res.ok) return; // daemon refused (e.g. transcript not readable yet) — retry on the next turn
- announced = true;
- if (ready) registered = true;
- } catch {}
- };
-
- // session_start fires before the transcript exists; the turn hooks catch it once it does.
- pi.on("session_start", async (_event, ctx) => { await register(ctx); });
- pi.on("turn_start", async (_event, ctx) => { await register(ctx); });
- pi.on("turn_end", async (_event, ctx) => { await register(ctx); });
-}
-`
-}
-
-/** Idempotently drop the Pi discovery extension into <PI_HOME>/agent/extensions/. */
-export function installPiExtension(port: number): void {
- const source = piExtensionSource(port)
- try {
- if (existsSync(PI_EXTENSION_PATH) && readFileSync(PI_EXTENSION_PATH, 'utf-8') === source) {
- console.log('[hooks] Pi discovery extension already installed')
- return
- }
- } catch { /* unreadable — rewrite it */ }
- try {
- mkdirSync(dirname(PI_EXTENSION_PATH), { recursive: true })
- const tmp = `${PI_EXTENSION_PATH}.${process.pid}.tmp`
- writeFileSync(tmp, source)
- renameSync(tmp, PI_EXTENSION_PATH)
- console.log(`[hooks] installed Pi discovery extension → ${PI_EXTENSION_PATH}`)
- console.log('[hooks] (takes effect on the next pi session start)')
- } catch (err) {
- console.error('[hooks] failed to write Pi extension:', err)
- }
-}
-
-const AMP_PLUGIN_PATH = join(env.AMP_PLUGIN_DIR, 'launcher-register.ts')
-
-/**
- * Amp's plugin does more than discovery — it WRITES the transcript, because Amp keeps none.
- *
- * Every other engine here leaves a conversation on disk and the adapter tails it. Amp does not: threads
- * live on its server, and the only local artefacts are `session.json` and a debug log that records
- * `blockCount`/`frameLength` and no message text whatsoever (measured across two real sessions).
- * `amp threads export` can fetch the content, but it is a ~1.5s network round trip that never shows a
- * message before it is complete — useless for a live tail.
- *
- * The plugin API is the way in. Four events fire (measured in the TUI by registering for sixteen
- * candidate names on 0.0.1786681855 and logging what arrived, not read off a doc): `session.start`,
- * `tool.call`, `tool.result`, `agent.end`. So this plugin writes the JSONL the watcher tails, and from
- * there Amp is an ordinary file-backed engine.
- *
- * `agent.start` used to be a fifth, and was how a turn opened. It no longer fires, and `agent.end` — the
- * only event that still carries the prompt — arrives at the END of the turn, far too late to open one.
- * The prompt is therefore read from the thread instead (see `drain`). The handler for `agent.start` is
- * kept anyway: it costs nothing on a version that never emits it, and an older Amp still works.
- *
- * Three details are load-bearing:
- *
- * - **Text comes from `ctx.thread.messages()`, not from the events.** No event carries assistant text.
- * But the thread handle reads the client's own local state, and at `tool.call` it ALREADY contains
- * the in-flight assistant message (measured) — so snapshotting on each event emits a message's text
- * BEFORE the tool it called, which is the order a transcript has to be in. Nothing is fetched.
- * - **Blocks are emitted once, keyed `<messageId>#<index>`.** Each snapshot re-reads the same recent
- * messages, so without that key every event would re-emit the whole tail of the conversation.
- * - **The turn opens from the user's own text block**, not from an event — the only place the prompt
- * is available while the turn is still running.
- *
- * Being a SYSTEM plugin it loads in every `amp` the user runs, including ones this adapter knows nothing
- * about. The `TMUX_PANE` guard keeps standalone sessions inert; the daemon additionally proves that the
- * pane contains the matching top-level Amp process before accepting a binding.
- */
-function ampPluginSource(port: number, sessionsDir: string): string {
- return `// session-register — auto-installed by the machine adapter. Binds this Amp thread to the local
-// machine daemon (127.0.0.1:${port}) and writes the transcript the daemon tails, because Amp keeps none
-// on disk. No-op outside tmux.
-import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
-import { join } from 'node:path'
-
-export const description = 'Mirrors this Amp thread to the machine adapter (web + device)'
-
-const SESSIONS_DIR = ${JSON.stringify(sessionsDir)}
-
-export default function (amp: any) {
- const pane = process.env.TMUX_PANE
- if (!pane) return
-
- // NOT \`process.cwd()\`: Bun runs a plugin with the PLUGIN's directory as its cwd, so that reports
- // \`<project>/.amp/plugins\` (measured). \`PWD\` is inherited from the shell that launched plain Amp.
- const workdir = process.env.PWD || process.cwd()
-
- const emitted = new Set()
- // Turn ids already opened/closed. Amp re-dispatches a message it could not deliver, firing agent.start
- // a SECOND time for the same message id (measured: two identical turn_start records 61s apart, then a
- // turn_end 'done' and a turn_end 'error' for the one turn). Written straight through, that is two turns
- // on web and device and two user bubbles in history.
- const turnsStarted = new Set()
- const turnsEnded = new Set()
- // Tool ids already written, so a tool seen BOTH as an event and as a message block is written once.
- const toolCalls = new Set()
- const toolResults = new Set()
- let registered = false
- let file = ''
- let seeded = false
-
- const line = (record: any) => {
- try {
- mkdirSync(SESSIONS_DIR, { recursive: true, mode: 0o700 })
- appendFileSync(file, JSON.stringify(record) + '\\n')
- } catch {}
- }
-
- const open = (threadId: string) => {
- if (file) return
- file = join(SESSIONS_DIR, threadId + '.jsonl')
- // \`cwd\` on the first line is what lets the daemon re-find this session by directory after a restart,
- // the same way it reads claude's and pi's transcripts. It must be a top-level string field.
- line({ t: 'session', threadId, cwd: workdir, at: Date.now() })
- }
-
- const register = async (threadId: string) => {
- open(threadId)
- if (registered || !existsSync(file)) return
- try {
- const token = readFileSync(${JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential'))}, 'utf8').trim()
- if (!token) return
- const res = await fetch('http://127.0.0.1:${port}/api/hook/session-start', {
- method: 'POST',
- headers: { 'content-type': 'application/json', 'x-harness-hook-token': token },
- body: JSON.stringify({
- engine: 'amp',
- pluginVersion: ${JSON.stringify(VERSION)},
- sessionId: threadId,
- transcriptPath: file,
- cwd: workdir,
- tmuxPane: pane,
- callerPid: process.pid,
- runtimeHints: [
- ...(pane ? [{ backend: 'tmux', paneId: pane }] : []),
- ],
- }),
- })
- if (res.ok) registered = true
- } catch {}
- }
-
- const resultId = (block: any) => String(block.toolUseID || block.tool_use_id || '')
-
- /**
- * Write everything in the thread that has not been written yet.
- *
- * This reads message BLOCKS rather than events, because the events do not cover the thread:
- *
- * - no event carries assistant text at all, and
- * - \`tool.call\`/\`tool.result\` only fire for tools the CLIENT executes. MEASURED: a \`web_search\`
- * turn produced no tool event and no tool lease in Amp's own log, yet the message plainly held a
- * \`tool_use\` block — Amp runs that tool on its server. Skipping blocks meant a search rendered as
- * nothing at all on web and device while the pane showed "Explored 1 search".
- *
- * \`seed\` marks what already exists WITHOUT writing it, for a thread that is being resumed: those
- * messages belong to earlier turns, and replaying them made a fresh turn open with an old answer in it.
- */
- const drain = async (ctx: any) => {
- let messages: any[] = []
- try { messages = await ctx.thread.messages({ from: 'end', limit: 20 }) } catch { return }
- // The FIRST drain of this plugin instance only claims what it finds; it writes nothing. That covers
- // both ways a plugin meets a thread that already has messages: a resumed thread, and a plugin reload
- // (Amp loads a plugin ONCE per process, so reload is how a running pane picks up a new build). Without
- // it, the next prompt replayed the whole recent history as if it had just happened.
- const seed = !seeded
- seeded = true
- // The seed pass would swallow the very prompt the turn needs to open on. Measured: \`session.start\`
- // does NOT fire when Amp launches — it fires on the first submit, and by then the thread already
- // holds one \`user\` message. So the seed has to tell history from the live prompt, and the test is
- // whether anything answered it: the LAST user text block with no assistant message after it is
- // waiting, not past. On a resumed thread the last message is an assistant one, so nothing opens.
- let liveUserId = ''
- for (const message of messages) {
- if (message.role === 'assistant') { liveUserId = ''; continue }
- const parts = Array.isArray(message.content) ? message.content : []
- const hasText = parts.some((b: any) => b && b.type === 'text' && typeof b.text === 'string' && b.text)
- if (hasText) liveUserId = String(message.id)
- }
- for (const message of messages) {
- const blocks = Array.isArray(message.content) ? message.content : []
- for (let i = 0; i < blocks.length; i++) {
- const block = blocks[i]
- if (!block) continue
- if (block.type === 'text' || block.type === 'thinking') {
- const key = String(message.id) + '#' + i
- if (emitted.has(key)) continue
- const text = typeof block.text === 'string' ? block.text : block.thinking
- if (typeof text !== 'string' || !text) continue
- emitted.add(key)
- // A user TEXT block opens the turn.
- //
- // Amp used to announce that with an \`agent.start\` event, and the handler below wrote
- // \`turn_start\` from it. That event no longer fires — probed with a plugin that registered for
- // sixteen candidate names on amp 0.0.1786681855 and saw only \`session.start\`, \`tool.call\`,
- // \`tool.result\` and \`agent.end\`. The prompt now reaches a plugin no earlier than
- // \`agent.end\`, which is the END of the turn, far too late to open one.
- //
- // So it is taken from the thread instead, where drain was already reading it and dropping it:
- // measured at the first \`tool.call\` of a turn, \`messages()\` already returns the prompt, oldest
- // first. Without this the turn opens with an empty question on web and device, and the recap
- // loses what was asked.
- //
- // Only a TEXT block qualifies: a tool_result is also carried on a \`user\` message, so matching
- // the role alone would open a turn on every tool that returned.
- if (message.role !== 'assistant') {
- const turnId = String(message.id)
- if (turnsStarted.has(turnId)) continue
- turnsStarted.add(turnId)
- if (!seed || turnId === liveUserId) line({ t: 'turn_start', id: turnId, message: text, at: Date.now() })
- continue
- }
- if (!seed) line({ t: block.type, id: message.id, i, text })
- } else if (block.type === 'tool_use') {
- const id = String(block.id || '')
- if (!id || toolCalls.has(id)) continue
- toolCalls.add(id)
- if (!seed) line({ t: 'tool_call', id, tool: block.name, input: block.input })
- } else if (block.type === 'tool_result') {
- const id = resultId(block)
- if (!id || toolResults.has(id)) continue
- toolResults.add(id)
- // A server-run tool puts its payload under \`run\`; a client-run one under \`content\`/\`output\`.
- if (!seed) line({ t: 'tool_result', id, status: 'done', output: block.run ?? block.content ?? block.output })
- }
- }
- }
- }
-
- amp.on('session.start', async (event: any, ctx: any) => {
- await register(event.thread.id)
- await drain(ctx)
- })
-
- amp.on('agent.start', async (event: any, ctx: any) => {
- await register(event.thread.id)
- const id = String(event.id)
- if (!turnsStarted.has(id)) {
- turnsStarted.add(id)
- line({ t: 'turn_start', id: event.id, message: event.message, at: Date.now() })
- }
- await drain(ctx)
- })
-
- amp.on('tool.call', async (event: any, ctx: any) => {
- await register(event.thread.id)
- // CLAIM THE ID FIRST. \`drain\` runs before this card so a message's prose lands ahead of the tool it
- // called — but by then the tool_use block for THIS tool is already in the thread, so draining without
- // claiming wrote the card twice (measured: one Task turn produced two identical \`skill\` cards).
- toolCalls.add(String(event.toolUseID))
- await drain(ctx)
- line({ t: 'tool_call', id: event.toolUseID, tool: event.tool, input: event.input })
- })
-
- amp.on('tool.result', async (event: any, ctx: any) => {
- // Same rule as tool.call: claim before draining.
- toolResults.add(String(event.toolUseID))
- line({
- t: 'tool_result',
- id: event.toolUseID,
- tool: event.tool,
- status: event.status,
- output: event.output,
- })
- await drain(ctx)
- })
-
- amp.on('agent.end', async (event: any, ctx: any) => {
- await drain(ctx)
- // \`message\` is the prompt that STARTED this turn, and agent.end carries it even when
- // agent.start never fired (a prompt queued while Amp was connecting). Recording it here is what
- // lets history still show what was asked — see the replay branch in the normalizer.
- const id = String(event.id)
- if (turnsEnded.has(id)) return
- turnsEnded.add(id)
- line({ t: 'turn_end', id: event.id, status: event.status, message: event.message, at: Date.now() })
- })
-}
-`
-}
-
-/** Idempotently drop the Amp plugin into ~/.config/amp/plugins/. */
-export function installAmpPlugin(port: number): void {
- const source = ampPluginSource(port, env.AMP_SESSIONS_DIR)
- try {
- if (existsSync(AMP_PLUGIN_PATH) && readFileSync(AMP_PLUGIN_PATH, 'utf-8') === source) {
- console.log('[hooks] Amp plugin already installed')
- return
- }
- } catch { /* unreadable — rewrite it */ }
- try {
- mkdirSync(dirname(AMP_PLUGIN_PATH), { recursive: true })
- mkdirSync(env.AMP_SESSIONS_DIR, { recursive: true, mode: 0o700 })
- const tmp = `${AMP_PLUGIN_PATH}.${process.pid}.tmp`
- writeFileSync(tmp, source)
- renameSync(tmp, AMP_PLUGIN_PATH)
- console.log(`[hooks] installed Amp plugin → ${AMP_PLUGIN_PATH}`)
- // Amp loads a plugin ONCE per process, so a pane that is already open keeps running the old one —
- // measured the hard way: an amp started at 11:49 went on writing tool-less transcripts for hours
- // after the fix landed on disk. Say what to do about it rather than leaving it to be discovered.
- console.log('[hooks] a NEW amp session picks this up automatically; for one already open, run')
- console.log("[hooks] ctrl+o → 'plugins: reload' (or restart that pane)")
- } catch (err) {
- console.error('[hooks] failed to write Amp plugin:', err)
- }
-}
-
-/**
- * OpenCode 2 still discovers the legacy plugin directory, but rejects its 1.x API. Keep the legacy
- * file only for a confirmed 1.x binary. Remove only our generated file during migration, preserving
- * unrelated plugins and user configuration. With no binary yet, prepare the TUI plugin without
- * planting a legacy file that would fail when the pane installs current OpenCode.
- */
-export function installOpencodePlugin(port: number): void {
- if (opencodeMajorVersion() === 1) {
- installForkPlugin('opencode', OPENCODE_PLUGIN_PATH, 'OpenCode', port)
- } else {
- try {
- const source = readFileSync(OPENCODE_PLUGIN_PATH, 'utf8')
- if (source.startsWith('// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n')
- && source.includes('export const MachineRegister =')) {
- unlinkSync(OPENCODE_PLUGIN_PATH)
- console.log('[hooks] removed incompatible OpenCode 1 discovery plugin')
- }
- } catch (err) {
- if ((err as NodeJS.ErrnoException).code !== 'ENOENT') console.error('[hooks] failed to remove OpenCode 1 plugin:', err)
- }
- }
- installPluginSource('opencode', OPENCODE_TUI_PLUGIN_PATH, 'OpenCode 2 TUI', opencodeTuiPluginSource(port))
-}
-
-/**
- * Idempotently drop the Kilo discovery plugin into ~/.config/kilo/plugin/.
- *
- * Measured: kilo resolves its config root from XDG_CONFIG_HOME (`kilo debug paths` reports
- * `~/.config/kilo`), and that directory is already scaffolded with the same `package.json` +
- * `node_modules` layout opencode's has — the plugin dir itself is simply absent until something creates
- * it, which `mkdirSync` below does.
- */
-export function installKiloPlugin(port: number): void {
- installForkPlugin('kilo', KILO_PLUGIN_PATH, 'Kilo', port)
-}
-
-function installForkPlugin(engine: 'opencode' | 'kilo', path: string, product: string, port: number): void {
- installPluginSource(engine, path, product, forkPluginSource(engine, port))
-}
-
-/** Write [source] to [path] unless it is there already, atomically. */
-function installPluginSource(engine: 'opencode' | 'kilo', path: string, product: string, source: string): void {
- try {
- if (existsSync(path) && readFileSync(path, 'utf-8') === source) {
- console.log(`[hooks] ${product} discovery plugin already installed`)
- return
- }
- } catch { /* unreadable — rewrite it */ }
- try {
- mkdirSync(dirname(path), { recursive: true })
- const tmp = `${path}.${process.pid}.tmp`
- writeFileSync(tmp, source)
- renameSync(tmp, path)
- console.log(`[hooks] installed ${product} discovery plugin → ${path}`)
- console.log(`[hooks] (takes effect on the next ${engine} session start)`)
- } catch (err) {
- console.error(`[hooks] failed to write ${product} plugin:`, err)
- }
-}
+/** Compatibility entry for callers outside core. Native installation is eagerly composed. */
+export { installGrokHooks, installAgyHooks, installCopilotHooks, installCursorHooks,
+ installCommandCodeHooks, installDevinHooks, installHermesHooks, installOpencodePlugin,
+ installKiloPlugin, installPiExtension, installAmpPlugin } from '../engines/nativeHooks.js'
diff --git a/docs/research/2026-10-09-daemon-separation-progress.md b/docs/research/2026-10-09-daemon-separation-progress.md
index f338f3376..ac1308680 100644
--- a/docs/research/2026-10-09-daemon-separation-progress.md
+++ b/docs/research/2026-10-09-daemon-separation-progress.md
@@ -181,3 +181,26 @@ existing engine/timestamp prefix, avoiding same-clock collisions across calls,
daemon processes and restarts. Discovery still accepts both old and new names;
existing panes are neither renamed nor removed. All native fixtures use private
homes, shell history and sockets. Final validation and review are pending.
+
+
+## Later follow-ups and remaining safety work
+
+The same-millisecond label fix landed in [#1091](https://github.com/autonomous-ai/openharness/pull/1091).
+The capture authority fence landed in [#1093](https://github.com/autonomous-ai/openharness/pull/1093).
+Kilo and Hermes adoption/control boundaries landed in [#1095](https://github.com/autonomous-ai/openharness/pull/1095)
+and [#1097](https://github.com/autonomous-ai/openharness/pull/1097).
+Eager native identity and Muse/Pi repair landed in [#1104](https://github.com/autonomous-ai/openharness/pull/1104)
+and [#1106](https://github.com/autonomous-ai/openharness/pull/1106).
+OpenCode's version/model control extraction landed in [#1110](https://github.com/autonomous-ai/openharness/pull/1110)
+as `ee33093971d27e9dcda7f2ae8c35f54b61cec0bb` at 11:30:10 UTC, with all automatic checks and independent review.
+Their detailed evidence is in the dated identity, repair, capture, Kilo and OpenCode notes beside this one.
+No release has occurred.
+
+The six original phases have landed. The architectural bar is not complete. Native hook installation now
+has its own [golden-first extraction and fault evidence](2026-10-09-native-hook-installation.md).
+The required next work is bounded asynchronous executable/version preparation, explicit held preparation
+and durable launch intent, retarget authority across native writes, unreadable/unconfirmed native mutation
+handling, and the OpenCode v2 Close checkpoint audit. The precise gaps are recorded in
+[OpenCode control](2026-10-09-opencode-control.md). Remaining shared-control work includes bounded identity
+scans, Cursor pending-task persistence, agy turn backstop/control facts, input verification declarations,
+and the final unavailable-service/readiness audit. Line counts do not establish any of those properties.
diff --git a/docs/research/2026-10-09-native-hook-cost.json b/docs/research/2026-10-09-native-hook-cost.json
new file mode 100644
index 000000000..9b32cc290
--- /dev/null
+++ b/docs/research/2026-10-09-native-hook-cost.json
@@ -0,0 +1,101 @@
+{
+ "nativeHooks": true,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "tmux": "tmux 3.5a",
+ "samples": [
+ {
+ "bundle": "baseline",
+ "readyMs": 2017.0236180000002,
+ "atReady": {
+ "cpuMs": 310,
+ "rssMiB": 76.2890625
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 252.12965399999985,
+ "coreCpuMs": 30,
+ "rssMiB": 77.859375
+ },
+ {
+ "phase": "warm",
+ "requestMs": 129.017922,
+ "coreCpuMs": 10,
+ "rssMiB": 78.234375
+ }
+ ]
+ },
+ {
+ "bundle": "candidate",
+ "readyMs": 1583.9035439999998,
+ "atReady": {
+ "cpuMs": 300,
+ "rssMiB": 78.76171875
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 229.55663000000004,
+ "coreCpuMs": 30,
+ "rssMiB": 79.578125
+ },
+ {
+ "phase": "warm",
+ "requestMs": 134.9243489999999,
+ "coreCpuMs": 10,
+ "rssMiB": 80.7421875
+ }
+ ]
+ },
+ {
+ "bundle": "candidate",
+ "readyMs": 1632.7975390000001,
+ "atReady": {
+ "cpuMs": 300,
+ "rssMiB": 76.97265625
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 231.3424210000003,
+ "coreCpuMs": 30,
+ "rssMiB": 77.72265625
+ },
+ {
+ "phase": "warm",
+ "requestMs": 143.41917400000057,
+ "coreCpuMs": 20,
+ "rssMiB": 79.23046875
+ }
+ ]
+ },
+ {
+ "bundle": "baseline",
+ "readyMs": 1499.192669,
+ "atReady": {
+ "cpuMs": 300,
+ "rssMiB": 79.05859375
+ },
+ "launches": [
+ {
+ "phase": "cold",
+ "requestMs": 182.13429099999848,
+ "coreCpuMs": 30,
+ "rssMiB": 80.53515625
+ },
+ {
+ "phase": "warm",
+ "requestMs": 91.47403399999894,
+ "coreCpuMs": 10,
+ "rssMiB": 80.7734375
+ }
+ ]
+ }
+ ],
+ "baseline": "ee33093971d27e9dcda7f2ae8c35f54b61cec0bb (same production tree as reviewed 2b5e0b057574e7a9ffe0f191992e672d55229ffc)",
+ "bundleSha256": {
+ "baseline": "75d1c875df5a17dede8f99eef620cafb83eb2f6bfc1033596c5b5ebd84f1d63c",
+ "candidate": "a5f3452c8634ea92bbe80c59f5c74da05969266c970dcaf58cb8d9261ecf28b3"
+ }
+}
diff --git a/docs/research/2026-10-09-native-hook-installation.md b/docs/research/2026-10-09-native-hook-installation.md
new file mode 100644
index 000000000..209ab490b
--- /dev/null
+++ b/docs/research/2026-10-09-native-hook-installation.md
@@ -0,0 +1,22 @@
+# Native hook installation stays with session control
+
+Before this change, the shared optional `hooks` module was awaited by daemon startup and OpenCode preflight. Removing or stalling it can block readiness or a launch. Hook installation supplies session discovery and turn boundaries, so those mechanics must be eager too.
+
+Before moving production code, the existing `otherHooks.golden.spec.ts` was re-recorded from main `f6f1eef1ab3823effa1646ebce960cc1b007a574` on 2026-10-09, then verified with recording disabled. All 340 cases pass. The recorded artifact is byte-for-byte identical to the existing fixture, SHA-256 `05013b28d8e42eec73598ac21d139130e4b5c65e2207aadbb1626bd5ee591197`. This commit records that baseline before implementation. Linux is pinned, the environment uses UTC and `/tmp`, every home is disposable, and Node paths are placeholders.
+
+The extraction declares vendor settings, plugin source, paths and migration facts beside each engine, with shared mechanics in `engines/kit` and eager composition. Existing JSON merging, YAML preservation, generated plugin bytes, permissions, symlinks, migration ownership checks and log output remain covered by that unchanged golden. Deliberate wiring and declaration mutations must fail assertions. The real bundle becomes ready with all thirteen installers selected, verifies each private native artifact, launches OpenCode and retains a sibling Claude Code/Codex Stop/resume while the obsolete shared hooks chunk is missing or stalled. The compatibility alias remains available for old imports, but core never requests it. The architecture guard rejects restoring that lazy dependency.
+
+Compatibility is only the first step. The OpenCode control review separately identified swallowed plugin write/removal errors, the synchronous version probe, inconsistent preparation across dispatch paths and unavailable-service results lost by callers. Those require explicit held outcomes and shared preparation before any process or configuration mutation; an eager import alone does not establish that they are safe. See [OpenCode control](2026-10-09-opencode-control.md).
+
+
+Validation plan: typecheck; architecture; unchanged native hook, Claude/Codex hook and admission goldens; installer and Hermes profile specs; eager-import guard; full core/services and master coverage; private-bundle shared-hook and OpenCode-reader fault cases; core, hook-client and crash/resume e2e lanes. Scope receipts include all CLI/Store sources, configs, fixtures and lockfiles plus Node, Vitest and tmux versions. CI covers the complete Linux unit suite. Runtime comparison uses frozen baseline/candidate bundles with the same thirteen-install startup and two OpenCode launches; measurements run separately from heavy validation.
+
+Initial complete gates pass: 530 focused tests, 1,897 core/services tests and 265 master tests (one intentional skip), with every covered core/services/master file at 100% statements, branches, functions and lines. Seven bundle acceptance cases pass. The first wrong-generation mutant caused the golden's fixture-building step to fail before assertions; it was rejected as evidence and changed to keep v1 installation while wrongly installing the v1 plugin for v2. The golden fixture and spec are unchanged.
+
+
+Final focused verification adds two literal-data cases: a `$&` in a path must appear verbatim in a log, and a plugin argument resembling template syntax must not be interpolated again. All 532 focused tests and typecheck pass. Twelve declaration/wiring mutants fail assertions: JSON event/failure policy/foreign preservation, port routing, version selection, legacy plugin ownership, YAML foreign preservation, profile discovery, approvals, installer routing, pre-spawn preparation and the lazy startup dependency. No setup failure is counted.
+
+[Runtime samples](2026-10-09-native-hook-cost.json) use Node 22.23.2 and tmux 3.5a on the same machine, all thirteen installers, and two native launches per fresh daemon. The two baseline readiness samples are 1,499–2,017 ms versus 1,584–1,633 ms for the candidate; core CPU at readiness is 300–310 ms versus 300 ms, and RSS 76.3–79.1 MiB versus 77.0–78.8 MiB. Launch latency varies across both samples. These four observations support no speed claim or numerical gate. Reproduce with frozen bundles at `OPENCODE_COST_ROOT/{baseline,candidate}/cli.js` and `OPENCODE_COST_NATIVE_HOOKS=1` passed in the test process environment. The validation runner does not forward an `env` field in an individual check; the first opt-in invocation skipped and is not measurement evidence. The actual workload passed in 9.5 seconds.
+
+
+The final bundled core/hook-client/crash-resume lane passes all 27 cases (342.5 seconds). The first ready-head Linux run found an obsolete lean-bundle assertion requiring native hook source to stay lazy. The replacement explicitly requires the native declaration in the core's static bundle while keeping the optional compatibility entry and native readers out. This is a test correction to the intended boundary; no production code changed after the passing local acceptance.