The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: use managed Node runtime for generated hook command lines and CLI execution
0xken154fe2795ad8a8
diff --git a/cli/scripts/install-cli.sh b/cli/scripts/install-cli.shindex 556f9fee8..9cb5e0c65 100755--- a/cli/scripts/install-cli.sh+++ b/cli/scripts/install-cli.sh@@ -58,9 +58,24 @@ for arg in "$@"; doesacdone-command -v node >/dev/null 2>&1 || { echo "error: node not found — the CLI is plain JS run by your Node (>= 20)" >&2; exit 1; }-NODE_MAJOR="$(node -e 'process.stdout.write(String(process.versions.node.split(".")[0]))')"-[ "$NODE_MAJOR" -ge 20 ] || { echo "error: Node >= 20 required (found $(node -v))" >&2; exit 1; }+# The Node the launcher will be PINNED to, as an absolute path. Two reasons it is resolved here+# rather than left as a bare `node` in the launcher: a Finder-launched app inherits launchd's+# PATH (/usr/bin:/bin:/usr/sbin:/sbin — no Homebrew, no nvm) and would find no `node` at all; and+# the public installer pins an absolute path, which this script's header promises to match.+# The managed runtime wins when it is present, so a dev install drives the same cli.js on the same+# Node the desktop app uses instead of quietly forking onto whatever PATH resolves.+HARNESS_RUNTIME_NODE="${HARNESS_RUNTIME_NODE:-$HOME/.harness/runtime/current-node}"+NODE_BIN=""+if [ -r "$HARNESS_RUNTIME_NODE" ]; then+ CANDIDATE="$(cat "$HARNESS_RUNTIME_NODE" 2>/dev/null || true)"+ if [ -n "$CANDIDATE" ] && [ -x "$CANDIDATE" ]; then NODE_BIN="$CANDIDATE"; fi+fi+if [ -z "$NODE_BIN" ]; then+ NODE_BIN="$(command -v node 2>/dev/null || true)"+fi+[ -n "$NODE_BIN" ] || { echo "error: node not found — the CLI is plain JS run by your Node (>= 20)" >&2; exit 1; }+NODE_MAJOR="$("$NODE_BIN" -e 'process.stdout.write(String(process.versions.node.split(".")[0]))')"+[ "$NODE_MAJOR" -ge 20 ] || { echo "error: Node >= 20 required (found $("$NODE_BIN" -v))" >&2; exit 1; }if [ "$DO_BUILD" -eq 1 ]; thencommand -v npm >/dev/null 2>&1 || { echo "error: npm not found (needed for the bundle step; use --no-build to skip)" >&2; exit 1; }fi@@ -86,7 +101,7 @@ head -1 "$SRC_CLI" | grep -q '^#!' || { echo "error: dist/cli.js lost its sheban# replace a working install (the same gate the self-updater applies). Everything below reports# `node dist/cli.js version` rather than the label above, so `--no-build` — where dist/ may hold a# bundle some other command produced — can never announce a version it isn't installing.-VER="$(node "$SRC_CLI" version 2>/dev/null || true)"+VER="$("$NODE_BIN" "$SRC_CLI" version 2>/dev/null || true)"[ -n "$VER" ] || { echo "error: 'node dist/cli.js version' failed — refusing to install a broken bundle" >&2; exit 1; }if [ "$DO_BUILD" -eq 1 ] && [ "$VER" != "$LABEL" ]; thenecho "error: bundle reports '$VER', expected '$LABEL' (ADAPTER_VERSION not injected)" >&2; exit 1@@ -108,7 +123,7 @@ if [ -n "$RUNNING_PID" ] && kill -0 "$RUNNING_PID" 2>/dev/null; thenecho ">> stopping the running adapter (pid $RUNNING_PID)…"# Prefer the CLI's own stop (graceful WS close → releases the machine-owner claim, clears the pid# file); fall back to signals if the currently-installed bundle is broken or missing.- node "$CLI_DIR/cli.js" stop >/dev/null 2>&1 || kill -TERM "$RUNNING_PID" 2>/dev/null || true+ "$NODE_BIN" "$CLI_DIR/cli.js" stop >/dev/null 2>&1 || kill -TERM "$RUNNING_PID" 2>/dev/null || truefor _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$RUNNING_PID" 2>/dev/null || break; sleep 0.3; doneif kill -0 "$RUNNING_PID" 2>/dev/null; then kill -KILL "$RUNNING_PID" 2>/dev/null || true; sleep 0.5; firm -f "$PID_FILE"@@ -135,7 +150,7 @@ rm -f "$CLI_DIR/cli.js.prev" "$CLI_DIR/notify.mjs.prev"if [ "$KEEP_UPDATES" -eq 1 ]; thencat > "$LAUNCHER.tmp" <<EOF#!/bin/sh-exec node "$CLI_DIR/cli.js" "\$@"+exec "$NODE_BIN" "$CLI_DIR/cli.js" "\$@"EOFelsecat > "$LAUNCHER.tmp" <<EOF@@ -145,7 +160,7 @@ else# Re-run install-cli.sh without --no-updates (or the public installer) to rejoin the release train.ADAPTER_UPDATE_DISABLE=trueexport ADAPTER_UPDATE_DISABLE-exec node "$CLI_DIR/cli.js" "\$@"+exec "$NODE_BIN" "$CLI_DIR/cli.js" "\$@"EOFfichmod 755 "$LAUNCHER.tmp"diff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex 9f0d0a7e4..c79d626fa 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -11,6 +11,9 @@ import { adoptComputerId } from '../lib/computerIdentity.js'const adapterRootDir = join(homedir(), '.harness')const adapterCliDir = join(adapterRootDir, 'cli')const adapterDataDir = join(adapterCliDir, 'data')+// The private, checksum-verified Node the installers and Desktop Harness provision. `current-node`+// inside it names the binary in use; both writers rewrite that file whenever they lay down a runtime.+const adapterRuntimeDir = join(adapterRootDir, 'runtime')// The computer id lives at the PRODUCT root, one level ABOVE `cli/`, and deliberately not in the data// dir: `harness reset` wipes that dir, the ~/.machine adoption below force-replaces entries in it, and// a custom ADAPTER_DATA_DIR moves it. A computer's identity must outlive all three — the backend binds@@ -365,6 +368,10 @@ const envSchema = z.object({ADAPTER_UPDATE_DISABLE: z.string().default('false').transform((v) => v === 'true'),// Install dir holding the packaged cli.js + notify.mjs that the self-updater swaps in place.ADAPTER_CLI_DIR: z.string().default(adapterCliDir),+ // Where the managed Node runtime lives. Read (never written) by this process: the hook command+ // lines have to name an interpreter by absolute path, because a hook fires in a shell whose PATH+ // we do not control — see managedNodePath() in lib/nodeRuntime.ts.+ ADAPTER_RUNTIME_DIR: z.string().default(adapterRuntimeDir),// ── the dial on the USB cable ──────────────────────────────────────────────────────────────────// Set 'true' to leave the serial port alone entirely. The port is exclusive, so this is what adiff --git a/cli/src/engines/cursor/localE2e.spec.ts b/cli/src/engines/cursor/localE2e.spec.tsindex 29feca0c1..4c7048ef2 100644--- a/cli/src/engines/cursor/localE2e.spec.ts+++ b/cli/src/engines/cursor/localE2e.spec.ts@@ -10,6 +10,7 @@ import { WebSocket, WebSocketServer } from 'ws'import { describe, expect, it } from 'vitest'import { cursorMessagesToEvents } from './normalizer.js'import { loadCursorReplayTaskLinks } from './subagent.js'+import { managedNodePath } from '../../lib/nodeRuntime.js'const runCursorE2e = process.env.RUN_CURSOR_E2E === '1'const execFileAsync = promisify(execFile)@@ -91,7 +92,9 @@ async function installTemporaryCursorHooks(port: number, dataDir: string): Promi? settings.hooks as Record<string, unknown>: {}const command = [- 'node',+ // Mirrors lib/hooks.ts: an absolute interpreter, never the bare word, so this fixture keeps+ // matching what the installer really writes.+ shellQuote(managedNodePath()),shellQuote(hookScript),'--port', String(port),'--data-dir', shellQuote(dataDir),diff --git a/cli/src/lib/hooks.spec.ts b/cli/src/lib/hooks.spec.tsindex fdc4933e7..dc859da53 100644--- a/cli/src/lib/hooks.spec.ts+++ b/cli/src/lib/hooks.spec.ts@@ -351,3 +351,152 @@ describe('Hermes hook installation', () => {expect(existsSync(join(hermesHome, 'shell-hooks-allowlist.json'))).toBe(false)})})++/**+ * A hook command is executed later, by the ENGINE, in a shell whose PATH we do not control — an app+ * started from Finder inherits launchd's bare `/usr/bin:/bin:/usr/sbin:/sbin`. Since the product ships+ * its own Node under ~/.harness/runtime, a computer with no `node` on PATH is the normal case, and a+ * command line beginning with the bare word `node` fails there with "node: command not found".+ */+describe('the Node interpreter baked into hook commands', () => {+ let runtimeDir = ''++ beforeEach(() => {+ codexHome = mkdtempSync(join(tmpdir(), 'adapter-codex-node-'))+ hermesHome = mkdtempSync(join(tmpdir(), 'adapter-hermes-node-'))+ runtimeDir = mkdtempSync(join(tmpdir(), 'adapter-runtime-'))+ })++ afterEach(() => {+ for (const dir of [codexHome, hermesHome, runtimeDir]) rmSync(dir, { recursive: true, force: true })+ delete process.env.CODEX_HOME+ delete process.env.HERMES_HOME+ delete process.env.ADAPTER_RUNTIME_DIR+ })++ /** The first shell word of the emitted command, unquoted. */+ function interpreterOf(command: string): string {+ const [, quoted] = /^'((?:[^']|'\\'')*)'/.exec(command) ?? []+ return quoted ?? command.split(' ')[0]+ }++ it('names an absolute, runnable interpreter and never the bare word node', async () => {+ const file = join(codexHome, 'hooks.json')+ const { installCodexHooks } = await loadHooks()+ installCodexHooks(18473)++ const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }+ const command = out.hooks.SessionStart[0].hooks[0].command+ const interpreter = interpreterOf(command)++ expect(interpreter).not.toBe('node')+ expect(interpreter.startsWith('/')).toBe(true)+ expect(existsSync(interpreter)).toBe(true)+ })++ it('prefers the managed runtime over the interpreter this process runs on', async () => {+ // Stand in for a runtime provisioned AFTER this daemon started: the hooks must follow+ // current-node, not process.execPath, or a Node upgrade would never reach them.+ const upgraded = join(runtimeDir, 'node-v99', 'bin', 'node')+ mkdirSync(join(runtimeDir, 'node-v99', 'bin'), { recursive: true })+ writeFileSync(upgraded, '#!/bin/sh\nexit 0\n', { mode: 0o755 })+ writeFileSync(join(runtimeDir, 'current-node'), `${upgraded}\n`)+ process.env.ADAPTER_RUNTIME_DIR = runtimeDir++ const file = join(codexHome, 'hooks.json')+ const { installCodexHooks } = await loadHooks()+ installCodexHooks(18473)++ const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }+ expect(interpreterOf(out.hooks.SessionStart[0].hooks[0].command)).toBe(upgraded)+ })++ it('falls back to this process when current-node names something unrunnable', async () => {+ writeFileSync(join(runtimeDir, 'current-node'), `${join(runtimeDir, 'node-gone', 'bin', 'node')}\n`)+ process.env.ADAPTER_RUNTIME_DIR = runtimeDir++ const file = join(codexHome, 'hooks.json')+ const { installCodexHooks } = await loadHooks()+ installCodexHooks(18473)++ const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }+ // A hook naming an interpreter that cannot run is strictly worse than one naming the interpreter+ // we are demonstrably running on.+ expect(interpreterOf(out.hooks.SessionStart[0].hooks[0].command)).toBe(process.execPath)+ })++ it('refuses a current-node pointing outside the runtime directory', async () => {+ writeFileSync(join(runtimeDir, 'current-node'), '/bin/sh\n')+ process.env.ADAPTER_RUNTIME_DIR = runtimeDir++ const file = join(codexHome, 'hooks.json')+ const { installCodexHooks } = await loadHooks()+ installCodexHooks(18473)++ const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }+ expect(interpreterOf(out.hooks.SessionStart[0].hooks[0].command)).toBe(process.execPath)+ })++ // The repair path for every machine already carrying the broken form. It works because each+ // installer recognises its own entries by the notify.mjs substring and rewrites on ANY command+ // drift — a changed interpreter is the same kind of drift as a changed path or port.+ it('replaces an already-installed hook that still runs a bare node', async () => {+ const file = join(codexHome, 'hooks.json')+ writeFileSync(file, JSON.stringify({+ hooks: {+ SessionStart: [{ hooks: [{ type: 'command', command: "node '/Users/someone/.harness/cli/notify.mjs' --port 18473 --engine codex" }] }],+ },+ }))++ const { installCodexHooks } = await loadHooks()+ installCodexHooks(18473)++ const out = JSON.parse(readFileSync(file, 'utf8')) as { hooks: Record<string, Array<{ hooks: Array<{ command: string }> }>> }+ const commands = out.hooks.SessionStart.flatMap((block) => block.hooks.map((h) => h.command))+ expect(commands).toHaveLength(1)+ expect(commands[0].startsWith('node ')).toBe(false)+ expect(interpreterOf(commands[0]).startsWith('/')).toBe(true)+ })+})++/**+ * Hermes silently skips any hook whose exact (event, command) pair is not approved, so the installer+ * records its own. Every command change mints five new pairs; without pruning, the approvals file+ * grows by five entries for every port change, moved install and Node upgrade, forever.+ */+describe('Hermes hook allowlist', () => {+ beforeEach(() => {+ hermesHome = mkdtempSync(join(tmpdir(), 'adapter-hermes-allow-'))+ writeFileSync(join(hermesHome, 'config.yaml'), 'model: test\n')+ })++ afterEach(() => {+ rmSync(hermesHome, { recursive: true, force: true })+ delete process.env.HERMES_HOME+ })++ it('drops its own stale approvals and keeps foreign ones', async () => {+ const allowlist = join(hermesHome, 'shell-hooks-allowlist.json')+ writeFileSync(allowlist, JSON.stringify({+ approvals: [+ { event: 'on_session_start', command: "node '/old/notify.mjs' --port 19918 --engine hermes" },+ { event: 'pre_llm_call', command: "node '/old/notify.mjs' --port 19918 --engine hermes" },+ { event: 'on_session_start', command: '/usr/local/bin/somebody-elses-hook.sh' },+ ],+ }))++ const { installHermesHooks } = await loadHooks()+ installHermesHooks(18473)++ const out = JSON.parse(readFileSync(allowlist, 'utf8')) as { approvals: Array<{ event: string; command: string }> }+ expect(out.approvals.some((a) => a.command.includes('/old/notify.mjs'))).toBe(false)+ expect(out.approvals.some((a) => a.command === '/usr/local/bin/somebody-elses-hook.sh')).toBe(true)+ // Exactly one approval per event, and it is the command actually written into config.yaml.+ const installed = /- command: "(.*?)"/.exec(readFileSync(join(hermesHome, 'config.yaml'), 'utf8'))![1]+ .replace(/\\(.)/g, '$1')+ const ours = out.approvals.filter((a) => a.command.includes('notify.mjs'))+ expect(ours.every((a) => a.command === installed)).toBe(true)+ expect(new Set(ours.map((a) => a.event)).size).toBe(ours.length)+ })+})+diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex 72e7a5269..97e5439b5 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -11,6 +11,7 @@ import { homedir } from 'os'import { fileURLToPath } from 'url'import { env } from '../config/env.js'import { VERSION } from '../version.js'+import { managedNodePath } from './nodeRuntime.js'const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')const CODEX_HOOKS_PATH = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'hooks.json')@@ -58,7 +59,11 @@ function shellQuote(value: string): string {function command(port: number, engine: 'claude' | 'codex' | 'cursor' | 'hermes' | 'commandcode' | 'devin' | 'grok' | 'agy' | 'copilot'): string {return [- 'node',+ // Absolute, never the bare word `node`. This string is executed later by the ENGINE, in a shell+ // whose PATH is none of our business — and since the product ships its own Node, a computer with+ // no `node` on PATH is normal. See managedNodePath(); a changed interpreter is picked up by the+ // same drift comparison each installer already does for a changed path or port.+ shellQuote(managedNodePath()),shellQuote(HOOK_SCRIPT),'--port', String(port),'--data-dir', shellQuote(env.ADAPTER_DATA_DIR),@@ -553,8 +558,18 @@ function allowlistHermesHook(cmd: string): void {const parsed = JSON.parse(readFileSync(HERMES_ALLOWLIST_PATH, 'utf-8')) as typeof dataif (parsed && Array.isArray(parsed.approvals)) data = parsed} catch { /* absent or unreadable → start from an empty skeleton */ }- const approvals = data.approvals ?? []- let changed = false+ 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.lengthfor (const event of HERMES_HOOK_EVENTS) {// Hermes matches on EXACT (event, command) string equality.if (approvals.some((a) => a?.event === event && a?.command === cmd)) continuediff --git a/cli/src/lib/nodeRuntime.ts b/cli/src/lib/nodeRuntime.tsnew file mode 100644index 000000000..ab99fc02b--- /dev/null+++ b/cli/src/lib/nodeRuntime.ts@@ -0,0 +1,37 @@+import { accessSync, constants, readFileSync } from 'node:fs'+import { join, sep } from 'node:path'++import { env } from '../config/env.js'++/**+ * The Node interpreter to bake into anything that runs LATER, in a process we do not launch — engine+ * hook command lines above all. Such a command cannot say `node`: a hook fires in a shell whose PATH+ * belongs to the engine (an app started from Finder inherits launchd's bare+ * `/usr/bin:/bin:/usr/sbin:/sbin`), and since the product moved to a private runtime, a machine with+ * no `node` on PATH at all is the normal case rather than the broken one.+ *+ * The managed runtime is preferred over [process.execPath], and the ordering is the whole point:+ * `execPath` is whatever interpreter THIS daemon happened to be launched with, which goes stale the+ * moment a new runtime is provisioned under a long-running daemon, whereas `current-node` is rewritten+ * by both installers and by Desktop Harness every time they lay one down. Reading it here means the+ * next `harness start` emits hooks pointing at the CURRENT runtime even while this process is still+ * running on the previous one — so a Node upgrade repairs the hooks by itself, not just a CLI upgrade.+ *+ * `execPath` remains the answer for a dev checkout or any machine with no managed runtime, and for a+ * `current-node` that has gone bad: a hook naming an interpreter that cannot run is strictly worse+ * than one naming the interpreter we are demonstrably running on.+ */+export function managedNodePath(): string {+ try {+ const recorded = readFileSync(join(env.ADAPTER_RUNTIME_DIR, 'current-node'), 'utf-8').trim()+ // Only ever trust a path inside the runtime directory we own — the same containment check the+ // desktop app applies to this file before executing what it names.+ if (recorded && recorded.startsWith(env.ADAPTER_RUNTIME_DIR + sep)) {+ accessSync(recorded, constants.X_OK)+ return recorded+ }+ } catch {+ // absent, unreadable, or not executable → fall through+ }+ return process.execPath+}