Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

fix(runtime): bundled node on the agent PATH; stop offering an installer that cannot run

Chaitanya Giri60ecca0eaf60
diff --git a/package.json b/package.json
index 37b0dd56..a5b3703f 100644
--- a/package.json
+++ b/package.json
@@ -19,7 +19,7 @@
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
- "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs",
+ "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs",
"dist": "npm run build && electron-builder",
"dist:mac": "npm run build && electron-builder --mac",
"dist:win": "npm run build && electron-builder --win",
diff --git a/src/main/cliInstall.ts b/src/main/cliInstall.ts
new file mode 100644
index 00000000..e280e66e
--- /dev/null
+++ b/src/main/cliInstall.ts
@@ -0,0 +1,154 @@
+/**
+ * The missing-engine-CLI install ladder.
+ *
+ * Split out of index.ts deliberately: it imports NOTHING from electron, so the
+ * decision ("which installer can actually succeed on this machine?") and the
+ * script it emits are both testable without booting an app.
+ */
+import type { AgentProvider, ProviderInstallInfo } from '../shared/agentProvider';
+import { installInfoForProvider } from '../shared/agentProvider';
+
+/** Pick which rung of the install ladder to run, given what this machine has.
+ *
+ * Every provider's `installCommand` is `npm install -g …`, which needs npm,
+ * which needs node. On a machine with no node the banner used to print that
+ * command anyway and run it — so the user watched `npm: command not found`
+ * scroll past and concluded the app was broken. Classify first:
+ *
+ * npm present → npm install (unchanged; the common case)
+ * npm absent, native installer → the vendor's self-contained installer
+ * npm absent, no native → manual only. Do NOT run a doomed command.
+ *
+ * We never auto-install a system Node, touch nvm, or edit the user's shell rc —
+ * a missing runtime is the user's to resolve, and the manual rung says so. */
+export function chooseInstallRung(
+ info: ProviderInstallInfo,
+ npmAvailable: boolean
+): { command?: string; kind: 'npm' | 'native' | 'manual'; nodeMissing: boolean } {
+ if (info.command && npmAvailable) return { command: info.command, kind: 'npm', nodeMissing: false };
+ if (info.nativeCommand) return { command: info.nativeCommand, kind: 'native', nodeMissing: !npmAvailable };
+ return { kind: 'manual', nodeMissing: !npmAvailable };
+}
+
+/** Build the shell script the missing-CLI auto-install path runs IN PLACE of a
+ * missing engine CLI. When a rung of the ladder above is runnable it prints a
+ * banner then RUNS it visibly (so the user can watch + finish any sign-in);
+ * otherwise it prints a manual instruction only and runs nothing. The script is
+ * emitted in the target platform's shell syntax ($SHELL on unix, cmd.exe on
+ * Windows) — `platform` is a parameter only so the Windows branch is reachable
+ * from a test on macOS. The only user-derived value (the missing binary name) is
+ * sanitized to a safe identifier; the install commands are trusted constants. */
+export function buildMissingCliScript(
+ bin: string,
+ provider: AgentProvider,
+ npmAvailable: boolean,
+ platform: string = process.platform
+): string {
+ const info: ProviderInstallInfo = installInfoForProvider(provider, platform);
+ const safeBin = (bin || provider).replace(/[^A-Za-z0-9._-]/g, '') || provider;
+ const rung = chooseInstallRung(info, npmAvailable);
+ const cmd = rung.command; // trusted constant, or undefined → manual hint only
+ const label = info.label;
+ const docs = info.docsUrl;
+ const rule = '------------------------------------------------------------';
+
+ if (platform === 'win32') {
+ // ONE cmd.exe line: `&` chains steps, `^&` prints a literal ampersand, and the
+ // script carries NO double-quotes (it is wrapped verbatim in `/d /s /c "..."`).
+ // We avoid `if errorlevel` branching (untestable here) — a combined success/
+ // failure hint after the install is robust and satisfies the manual-fallback DoD.
+ const parts: string[] = ['echo.', `echo ${rule}`, `echo Engine CLI not found: ${safeBin}`, 'echo.'];
+ if (rung.nodeMissing) {
+ parts.push('echo Node.js is not installed on this machine, so the usual', 'echo npm installer cannot run here.', 'echo.');
+ }
+ if (cmd) {
+ if (rung.kind === 'native') parts.push(`echo Using the self-contained ${label} installer instead ^(no Node needed^):`);
+ else parts.push(`echo Installing the ${label} CLI now so you can watch:`);
+ parts.push(
+ 'echo.',
+ `echo ${cmd}`,
+ `echo ${rule}`,
+ 'echo.',
+ cmd,
+ 'echo.',
+ 'echo [done] If it succeeded, the agent launches automatically.',
+ 'echo If it failed, run the command above manually, then restart the agent.'
+ );
+ } else {
+ if (rung.nodeMissing) {
+ parts.push(
+ `echo Install Node.js ^(nodejs.org^), then the ${label} CLI:`,
+ `echo ${info.command ?? ''}`,
+ 'echo …or install the CLI by whatever method its docs recommend.'
+ );
+ } else {
+ parts.push(
+ `echo No bundled installer for the ${label} provider.`,
+ 'echo Install it manually, then restart the agent to launch it.'
+ );
+ }
+ if (docs) parts.push(`echo Docs: ${docs}`);
+ parts.push(`echo ${rule}`);
+ }
+ return parts.join(' & ');
+ }
+
+ // unix ($SHELL -lc <script>): one statement per line, single-quoted echo text so
+ // no shell metacharacter expands. We avoid `!` so any shell with history
+ // expansion never fires. npm is found via the interactive PATH spawn() injects.
+ const lines: string[] = [
+ `echo ''`,
+ `echo '${rule}'`,
+ `echo ' Engine CLI not found: ${safeBin}'`,
+ `echo ''`
+ ];
+ if (rung.nodeMissing) {
+ lines.push(
+ `echo ' Node.js is not installed on this machine, so the usual npm'`,
+ `echo ' installer cannot run here.'`,
+ `echo ''`
+ );
+ }
+ if (cmd) {
+ lines.push(
+ ...(rung.kind === 'native'
+ ? [`echo ' Using the self-contained ${label} installer instead (no Node needed) —'`,
+ `echo ' finish any sign-in it prompts for, then come back to this terminal.'`]
+ : [`echo ' Installing the ${label} CLI now so you can watch — finish any'`,
+ `echo ' sign-in it prompts for, then come back to this terminal.'`]),
+ `echo ''`,
+ `echo ' ${cmd}'`,
+ `echo '${rule}'`,
+ `echo ''`,
+ cmd,
+ `__clirc=$?`,
+ `echo ''`,
+ `if [ $__clirc -eq 0 ]; then`,
+ ` echo ' [done] Installed — launching the agent…'`,
+ `else`,
+ ` echo " [x] Install exited with code $__clirc — finish it manually:"`,
+ ` echo ' ${cmd}'`,
+ ...(docs ? [` echo ' Docs: ${docs}'`] : []),
+ ` echo ' Then restart the agent to launch it.'`,
+ `fi`
+ );
+ } else if (rung.nodeMissing) {
+ // The honest dead end: no node, and this vendor ships no node-free installer.
+ // Say what is actually missing instead of running a command that cannot work.
+ lines.push(
+ `echo ' Install Node.js (nodejs.org), then the ${label} CLI:'`,
+ ...(info.command ? [`echo ' ${info.command}'`] : []),
+ `echo ' …or install the CLI by whatever method its docs recommend.'`,
+ ...(docs ? [`echo ' Docs: ${docs}'`] : []),
+ `echo '${rule}'`
+ );
+ } else {
+ lines.push(
+ `echo ' No bundled installer for the ${label} provider.'`,
+ `echo ' Install it manually, then restart the agent to launch it.'`,
+ ...(docs ? [`echo ' Docs: ${docs}'`] : []),
+ `echo '${rule}'`
+ );
+ }
+ return lines.join(String.fromCharCode(10));
+}
diff --git a/src/main/hive.ts b/src/main/hive.ts
index 6f5636fb..dd1c9d9c 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -375,6 +375,54 @@ export class HiveManager {
return p && existsSync(p) ? p : null;
}
+ /**
+ * `<root>/bin/runtime` — the same bundled-node trick as `hive-node`, but the
+ * wrapper is NAMED `node`, so anything that resolves `node` off PATH finds one.
+ *
+ * `hive-node` only covers commands WE generate. It does nothing for node that
+ * the agent's own work needs at runtime: an MCP server declared as
+ * `node ./server.js`, a provider CLI that shells out to node, a `.cjs` helper an
+ * agent wrote itself. On a machine with no system node those all die with 127
+ * exactly like the hooks did.
+ *
+ * This dir is APPENDED to the agent's PATH (see pty.spawn), never prepended: a
+ * user who has their own node keeps their own version — we are strictly the
+ * fallback. Prepending would silently swap every agent's node for Electron's
+ * (the v22 line at time of writing) underneath the user's own projects.
+ *
+ * NOTE: `node` only — deliberately no `npm`/`npx`. Electron bundles the Node
+ * RUNTIME, not the npm CLI (which is ~12MB of JS we do not ship), so an `npm`
+ * wrapper here could only be a stub that fails confusingly. A missing `npm` is
+ * the honest signal; see the missing-CLI ladder in index.ts, which detects it.
+ */
+ runtimeBinDir(): string | null {
+ const root = this.root();
+ return root ? join(root, 'bin', 'runtime') : null;
+ }
+
+ /** Write the `node` shim described above. Best-effort: on failure the dir is
+ * simply absent from PATH and behavior is exactly as before. */
+ private writeRuntimeShims(): void {
+ const dir = this.runtimeBinDir();
+ if (!dir) return;
+ try {
+ mkdirSync(dir, { recursive: true });
+ if (process.platform === 'win32') {
+ writeFileSync(
+ join(dir, 'node.cmd'),
+ `@echo off\r\nset ELECTRON_RUN_AS_NODE=1\r\n"${process.execPath}" %*\r\n`,
+ 'utf8'
+ );
+ } else {
+ const p = join(dir, 'node');
+ writeFileSync(p, `#!/bin/sh\nELECTRON_RUN_AS_NODE=1 exec "${process.execPath}" "$@"\n`, 'utf8');
+ chmodSync(p, 0o755);
+ }
+ } catch (e) {
+ console.error('[hive] writeRuntimeShims failed:', e);
+ }
+ }
+
/** Build a hook command string that runs `script` under the guaranteed node,
* DOUBLE-QUOTED (safe for paths with spaces). */
private nodeRun(script: string, ...args: string[]): string {
@@ -441,6 +489,8 @@ export class HiveManager {
// The bundled-node launcher every shim above is invoked through — MUST be
// written before any hook installer runs (they probe for it).
this.writeNodeLauncher();
+ // …and the PATH-visible `node` fallback for the agent's OWN subprocesses.
+ this.writeRuntimeShims();
if (!existsSync(join(root, '.git'))) {
this.git(['init', '-q'], root);
diff --git a/src/main/index.ts b/src/main/index.ts
index 2ed8036e..4074e384 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -54,9 +54,9 @@ import {
nonInteractiveEnvForProvider,
providerPreset,
installInfoForProvider,
- type AgentProvider,
- type ProviderInstallInfo
+ type AgentProvider
} from '../shared/agentProvider';
+import { buildMissingCliScript, chooseInstallRung } from './cliInstall';
import {
CODEX_REMOTE_SOCKET_RELATIVE,
codexRemoteAliasPath,
@@ -1848,89 +1848,6 @@ function installAppMenu(): void {
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
-/** Build the shell script the missing-CLI auto-install path runs IN PLACE of a
- * missing engine CLI. When the provider has a known installer it prints a banner
- * then RUNS the install visibly (so the user can watch + finish any sign-in);
- * otherwise it prints a manual instruction only and runs nothing. The script is
- * emitted in the current platform shell's syntax ($SHELL on unix, cmd.exe on
- * Windows). The only user-derived value (the missing binary name) is sanitized to
- * a safe identifier; the install command itself is a trusted hardcoded constant. */
-function buildMissingCliScript(bin: string, provider: AgentProvider): string {
- const info: ProviderInstallInfo = installInfoForProvider(provider);
- const safeBin = (bin || provider).replace(/[^A-Za-z0-9._-]/g, '') || provider;
- const cmd = info.command; // trusted constant, or undefined → manual hint only
- const label = info.label;
- const docs = info.docsUrl;
- const rule = '------------------------------------------------------------';
-
- if (process.platform === 'win32') {
- // ONE cmd.exe line: `&` chains steps, `^&` prints a literal ampersand, and the
- // script carries NO double-quotes (it is wrapped verbatim in `/d /s /c "..."`).
- // We avoid `if errorlevel` branching (untestable here) — a combined success/
- // failure hint after the install is robust and satisfies the manual-fallback DoD.
- const parts: string[] = ['echo.', `echo ${rule}`, `echo Engine CLI not found: ${safeBin}`, 'echo.'];
- if (cmd) {
- parts.push(
- `echo Installing the ${label} CLI now so you can watch:`,
- 'echo.',
- `echo ${cmd}`,
- `echo ${rule}`,
- 'echo.',
- cmd,
- 'echo.',
- 'echo [done] If it succeeded, the agent launches automatically.',
- 'echo If it failed, run the command above manually, then restart the agent.'
- );
- } else {
- parts.push(
- `echo No bundled installer for the ${label} provider.`,
- 'echo Install it manually, then restart the agent to launch it.'
- );
- if (docs) parts.push(`echo Docs: ${docs}`);
- parts.push(`echo ${rule}`);
- }
- return parts.join(' & ');
- }
-
- // unix ($SHELL -lc <script>): one statement per line, single-quoted echo text so
- // no shell metacharacter expands. We avoid `!` so any shell with history
- // expansion never fires. npm is found via the interactive PATH spawn() injects.
- const lines: string[] = [
- `echo ''`,
- `echo '${rule}'`,
- `echo ' Engine CLI not found: ${safeBin}'`,
- `echo ''`
- ];
- if (cmd) {
- lines.push(
- `echo ' Installing the ${label} CLI now so you can watch — finish any'`,
- `echo ' sign-in it prompts for, then come back to this terminal.'`,
- `echo ''`,
- `echo ' ${cmd}'`,
- `echo '${rule}'`,
- `echo ''`,
- cmd,
- `__clirc=$?`,
- `echo ''`,
- `if [ $__clirc -eq 0 ]; then`,
- ` echo ' [done] Installed — launching the agent…'`,
- `else`,
- ` echo " [x] Install exited with code $__clirc — finish it manually:"`,
- ` echo ' ${cmd}'`,
- ...(docs ? [` echo ' Docs: ${docs}'`] : []),
- ` echo ' Then restart the agent to launch it.'`,
- `fi`
- );
- } else {
- lines.push(
- `echo ' No bundled installer for the ${label} provider.'`,
- `echo ' Install it manually, then restart the agent to launch it.'`,
- ...(docs ? [`echo ' Docs: ${docs}'`] : []),
- `echo '${rule}'`
- );
- }
- return lines.join(String.fromCharCode(10));
-}
// ─── IPC: pty lifecycle ─────────────────────────────────────────────────────
/** Codex stores its rollout transcripts under a PER-AGENT CODEX_HOME
@@ -2049,6 +1966,11 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten
{
const bin = opts.command.trim().split(/\s+/)[0] || opts.command;
if (bin && !opts.noAutoInstall && !ptyManager.isCommandAvailable(bin)) {
+ // The installer commands are `npm install -g …`. Probe for npm the same way
+ // we probe for the engine CLI, so a no-Node machine gets the node-free rung
+ // (or an honest manual hint) instead of watching `npm: not found` scroll by.
+ const npmAvailable = ptyManager.isCommandAvailable('npm');
+ const rung = chooseInstallRung(installInfoForProvider(provider), npmAvailable);
const res = ptyManager.spawn(
{
id: opts.id,
@@ -2056,7 +1978,7 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten
command: bin,
cols: opts.cols,
rows: opts.rows,
- shellScript: buildMissingCliScript(bin, provider)
+ shellScript: buildMissingCliScript(bin, provider, npmAvailable)
},
owner
);
@@ -2065,7 +1987,11 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten
// (no user click). Only when an installer actually RAN (a provider with no
// bundled installer just prints a manual hint and exits 0 — relaunching there
// would spawn the still-missing binary and die) and the PTY actually started.
- if (res.ok && installInfoForProvider(provider).command) {
+ // …keyed on the RUNG, not on `installCommand`: the manual rung prints a hint
+ // and exits 0, and relaunching there would just respawn the still-missing
+ // binary and die with the bare "process exited (code 1)" this whole path exists
+ // to replace.
+ if (res.ok && rung.command) {
pendingInstallRelaunch.set(opts.id, { opts, owner, bin });
}
syncKeepAwake();
diff --git a/src/main/pty.ts b/src/main/pty.ts
index efc759d1..7683f0a8 100644
--- a/src/main/pty.ts
+++ b/src/main/pty.ts
@@ -1,11 +1,33 @@
import * as pty from 'node-pty';
import type { WebContents } from 'electron';
import { existsSync } from 'node:fs';
+import { delimiter, join } from 'node:path';
import { spawnSync } from 'node:child_process';
import { ensureKilled } from './procKill';
import { expandTilde } from './fs';
import { captureFromLoginShell, userShellPath } from './shellEnv';
+/** APPEND the hive's bundled-node dir (`<HIVE_ROOT>/bin/runtime`, which holds a
+ * shim literally named `node`) to a child's PATH.
+ *
+ * Layer 1 routed the commands WE generate through `hive-node`. This covers the
+ * ones we don't: an MCP server declared as `node ./server.js`, a provider CLI
+ * that shells out to node, a helper script the agent wrote itself. With no
+ * system node those all die with 127 — the same bug, one level down.
+ *
+ * APPENDED, never prepended: a user who has their own node keeps it, and we are
+ * only the fallback. Prepending would silently swap the node version under the
+ * user's own projects for Electron's, which is a different (and wrong) product
+ * decision. No-ops when there is no hive root or the dir was never written. */
+export function withHiveRuntimeFallback(path: string, hiveRoot?: string): string {
+ if (!hiveRoot) return path;
+ const dir = join(hiveRoot, 'bin', 'runtime');
+ if (!existsSync(dir)) return path;
+ const entries = path.split(delimiter).filter(Boolean);
+ if (entries.includes(dir)) return path; // re-spawn of a live agent
+ return [...entries, dir].join(delimiter);
+}
+
interface PtySession {
id: string;
proc: pty.IPty;
@@ -248,9 +270,10 @@ export class PtyManager {
// for the session (shellEnv.userShellPath, fenced against rc-file noise) —
// the interactive-shell launch it replaces cost ~1s of main-thread freeze
// on EVERY spawn.
- const userPath = process.platform === 'win32'
- ? (process.env.PATH || '')
- : userShellPath();
+ const userPath = withHiveRuntimeFallback(
+ process.platform === 'win32' ? (process.env.PATH || '') : userShellPath(),
+ opts.env?.HIVE_ROOT
+ );
// On Windows, .cmd/.bat files (and extensionless shims) cannot be executed
// directly by CreateProcess — only .exe/.com can. Route them through cmd.exe.
diff --git a/src/shared/agentProvider.ts b/src/shared/agentProvider.ts
index 75d7816d..aa41c58f 100644
--- a/src/shared/agentProvider.ts
+++ b/src/shared/agentProvider.ts
@@ -146,6 +146,17 @@ export interface AgentProviderPreset {
* when undefined, the user is shown a manual instruction only and nothing is
* auto-run. MUST be a trusted, hardcoded constant — never user/manifest input. */
installCommand?: string;
+ /** A SELF-CONTAINED installer that needs no Node/npm at all, per platform.
+ *
+ * `installCommand` is `npm install -g …` for every provider, which silently
+ * assumes npm — i.e. node — is already on the machine. When it isn't, the
+ * missing-CLI banner prints a command that CANNOT succeed, so the user watches
+ * an installer fail instead of an app work. Where the vendor ships a native
+ * installer we run that instead (see buildMissingCliScript's ladder).
+ *
+ * Trusted, hardcoded constants — never user/manifest input. MUST contain no
+ * double-quotes: the Windows form is wrapped verbatim in `cmd /d /s /c "…"`. */
+ nativeInstallCommand?: { posix: string; win32: string };
/** Optional docs URL surfaced as a manual-setup hint in the missing-CLI banner. */
docsUrl?: string;
resumeSubcommand?: string; // CLIs that resume via a subcommand instead of a flag (Codex: `codex resume [OPTIONS] [SESSION_ID]`)
@@ -169,6 +180,12 @@ export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [
resumeFlag: '--resume',
// Official Claude Code install (npm global). Used by the missing-CLI auto-install.
installCommand: 'npm install -g @anthropic-ai/claude-code',
+ // Anthropic's official native installer — a standalone binary, no node/npm.
+ // The only rung of the ladder that works on a machine with no Node at all.
+ nativeInstallCommand: {
+ posix: 'curl -fsSL https://claude.ai/install.sh | bash',
+ win32: 'powershell -c irm https://claude.ai/install.ps1 ^| iex'
+ },
docsUrl: 'https://docs.claude.com/en/docs/claude-code'
},
{
@@ -566,11 +583,22 @@ export function commandGroupsForProvider(provider: AgentProvider): CmdGroup[] {
* is the friendly CLI name; `docsUrl` is an optional manual-setup link. */
export interface ProviderInstallInfo {
command?: string;
+ /** A node-free installer for this platform, when the vendor ships one. */
+ nativeCommand?: string;
label: string;
docsUrl?: string;
}
-export function installInfoForProvider(provider: AgentProvider): ProviderInstallInfo {
+export function installInfoForProvider(
+ provider: AgentProvider,
+ platform: string = process.platform
+): ProviderInstallInfo {
const p = providerPreset(provider);
- return { command: p.installCommand, label: p.label, docsUrl: p.docsUrl };
+ const native = p.nativeInstallCommand;
+ return {
+ command: p.installCommand,
+ nativeCommand: native ? (platform === 'win32' ? native.win32 : native.posix) : undefined,
+ label: p.label,
+ docsUrl: p.docsUrl
+ };
}
diff --git a/test/cli-install-ladder.test.cjs b/test/cli-install-ladder.test.cjs
new file mode 100644
index 00000000..d319e2a5
--- /dev/null
+++ b/test/cli-install-ladder.test.cjs
@@ -0,0 +1,90 @@
+'use strict';
+
+/**
+ * Every provider's `installCommand` is `npm install -g …`. On a machine with no
+ * Node, the missing-CLI banner used to print that command and RUN it — so a fresh
+ * user watched `npm: command not found` scroll past and concluded the app was
+ * broken. The ladder classifies first and only ever runs something that can work.
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const { chooseInstallRung, buildMissingCliScript } = loadTs('src/main/cliInstall.ts');
+const { installInfoForProvider } = loadTs('src/shared/agentProvider.ts');
+
+const script = (provider, npmAvailable, platform) =>
+ buildMissingCliScript(provider, provider, npmAvailable, platform);
+
+test('with npm present the ladder is unchanged — npm install, for every provider', () => {
+ for (const provider of ['claude', 'codex', 'opencode', 'crush', 'copilot']) {
+ const info = installInfoForProvider(provider);
+ const rung = chooseInstallRung(info, true);
+ assert.equal(rung.kind, 'npm', provider);
+ assert.equal(rung.command, info.command, provider);
+ assert.equal(rung.nodeMissing, false, provider);
+ }
+});
+
+test('with npm absent, a provider shipping a native installer uses it', () => {
+ const rung = chooseInstallRung(installInfoForProvider('claude'), false);
+ assert.equal(rung.kind, 'native');
+ assert.equal(rung.nodeMissing, true);
+ assert.doesNotMatch(rung.command, /\bnpm\b/, 'the whole point is that npm is not there');
+});
+
+test('with npm absent and no native installer, NOTHING is run', () => {
+ const info = installInfoForProvider('codex');
+ assert.equal(info.nativeCommand, undefined, 'fixture assumes codex has no native installer');
+ const rung = chooseInstallRung(info, false);
+ assert.equal(rung.kind, 'manual');
+ assert.equal(rung.command, undefined, 'a command here would be the doomed `npm install -g`');
+});
+
+test('the no-node script explains the real problem instead of failing at it', () => {
+ const out = script('codex', false);
+ assert.match(out, /Node\.js is not installed/);
+ assert.match(out, /nodejs\.org/, 'tell the user where to get it');
+ assert.match(out, /Docs: https/, 'and keep the provider docs link');
+
+ // The npm command may still be SHOWN (as the follow-up step) but must never be
+ // an executed line: every executable line here is an `echo`.
+ const executable = out.split('\n').filter((l) => l.trim() && !/^\s*echo\b/.test(l.trim()));
+ assert.deepEqual(executable, [], `these would run on a machine with no node: ${executable}`);
+});
+
+test('the native rung actually runs, and says why it differs', () => {
+ const out = script('claude', false);
+ assert.match(out, /no Node needed/);
+ const native = installInfoForProvider('claude').nativeCommand;
+ assert.ok(out.split('\n').includes(native), 'the installer must be an executed line, not only echoed');
+});
+
+test('with npm present nothing mentions a missing Node', () => {
+ const out = script('claude', true);
+ assert.doesNotMatch(out, /Node\.js is not installed/);
+ assert.ok(out.split('\n').includes('npm install -g @anthropic-ai/claude-code'));
+});
+
+test('the Windows script stays a single quote-free cmd.exe line', () => {
+ // It is wrapped verbatim in `cmd /d /s /c "<script>"` — one embedded double
+ // quote ends the command line early and the rest executes as garbage.
+ for (const provider of ['claude', 'codex']) {
+ for (const npm of [true, false]) {
+ const out = buildMissingCliScript(provider, provider, npm, 'win32');
+ assert.ok(!out.includes('"'), `${provider}/${npm}: embedded quote`);
+ assert.ok(!out.includes('\n'), `${provider}/${npm}: must be one line`);
+ }
+ }
+ assert.match(buildMissingCliScript('claude', 'claude', false, 'win32'), /powershell/,
+ 'the native rung must be the PowerShell form on Windows, not the curl one');
+});
+
+test('a hostile binary name cannot inject a command into the banner', () => {
+ const out = script('claude', true).split('\n');
+ const evil = buildMissingCliScript("x'; rm -rf /; echo '", 'claude', true).split('\n');
+ assert.equal(evil.length, out.length, 'no extra statements');
+ assert.ok(evil.some((l) => l.includes('xrm-rf')), 'sanitized to a bare identifier');
+ assert.ok(!evil.some((l) => /rm -rf \//.test(l)));
+});
diff --git a/test/hive-runtime-path.test.cjs b/test/hive-runtime-path.test.cjs
new file mode 100644
index 00000000..26ad75b2
--- /dev/null
+++ b/test/hive-runtime-path.test.cjs
@@ -0,0 +1,101 @@
+'use strict';
+
+/**
+ * Layer 1 fixed the commands WE generate (every hook shim runs through
+ * `hive-node`). It did nothing for node the agent's own work needs: an MCP server
+ * declared as `node ./server.js`, a provider CLI that shells out to node, a helper
+ * an agent wrote itself. With no system node those die with 127 — same bug, one
+ * level down.
+ *
+ * `<hive>/bin/runtime/` holds a shim literally NAMED `node`, APPENDED to the
+ * agent's PATH. Appended, not prepended: a user with their own node keeps their
+ * own version, and we are strictly the fallback.
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+const loadTs = require('./load-ts.cjs');
+
+const { HiveManager } = loadTs('src/main/hive.ts');
+const { withHiveRuntimeFallback } = loadTs('src/main/pty.ts');
+
+const POSIX = process.platform !== 'win32';
+const STRIPPED_PATH = '/usr/bin:/bin:/usr/sbin:/sbin';
+const SEP = path.delimiter;
+
+async function hiveIn(t) {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'md-runtime-'));
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+ await hive.ensureAgent({ id: 'a1', name: 'A', provider: 'claude', cwd: home });
+ return { home, hive, root: path.join(home, 'hive') };
+}
+
+test('bootstrap materializes a PATH-visible `node`', async (t) => {
+ const { hive, root } = await hiveIn(t);
+
+ const dir = hive.runtimeBinDir();
+ assert.equal(dir, path.join(root, 'bin', 'runtime'));
+ const shim = path.join(dir, POSIX ? 'node' : 'node.cmd');
+ assert.equal(fs.existsSync(shim), true, 'nothing resolves `node` here without it');
+
+ const body = fs.readFileSync(shim, 'utf8');
+ assert.match(body, /ELECTRON_RUN_AS_NODE=1/, 'without this the binary opens a second app window');
+ assert.ok(body.includes(process.execPath), 'execPath is re-baked each bootstrap so an app move/update heals');
+ if (POSIX) assert.ok(fs.statSync(shim).mode & 0o111, 'must be executable');
+});
+
+test('npm and npx are deliberately NOT shimmed', async (t) => {
+ const { hive } = await hiveIn(t);
+ // Electron bundles the Node runtime, not the npm CLI. A stub named `npm` would
+ // make `npm install` fail confusingly instead of being honestly absent — which
+ // is what the missing-CLI ladder (cli-install-ladder.test.cjs) detects.
+ const present = fs.readdirSync(hive.runtimeBinDir());
+ assert.deepEqual(present.filter((f) => /^(npm|npx)(\.cmd)?$/.test(f)), []);
+});
+
+test('the runtime dir is APPENDED — the user\'s own node still wins', async (t) => {
+ const { root } = await hiveIn(t);
+ const dir = path.join(root, 'bin', 'runtime');
+
+ const out = withHiveRuntimeFallback(`/usr/local/bin${SEP}/usr/bin`, root);
+ assert.equal(out, `/usr/local/bin${SEP}/usr/bin${SEP}${dir}`);
+ assert.ok(out.indexOf('/usr/local/bin') < out.indexOf(dir),
+ 'prepending would silently swap the node version under the user\'s own projects');
+
+ assert.equal(withHiveRuntimeFallback(out, root), out, 'a respawn must not keep appending');
+});
+
+test('no hive root, or no runtime dir, leaves PATH exactly as it was', async (t) => {
+ const original = `/usr/local/bin${SEP}/usr/bin`;
+ assert.equal(withHiveRuntimeFallback(original, undefined), original, 'plain terminals are untouched');
+
+ const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'md-runtime-none-'));
+ t.after(() => fs.rmSync(empty, { recursive: true, force: true }));
+ assert.equal(withHiveRuntimeFallback(original, empty), original,
+ 'a pre-fix hive that never wrote the dir must degrade, not point PATH at nothing');
+});
+
+test('`node` resolves and RUNS with no node on PATH — the whole point', { skip: !POSIX }, async (t) => {
+ const { root } = await hiveIn(t);
+
+ const bare = { PATH: STRIPPED_PATH };
+ const probe = spawnSync('/bin/sh', ['-c', 'command -v node'], { env: bare, encoding: 'utf8' });
+ if (probe.status === 0) {
+ // An image with /usr/bin/node — the control is meaningless, but the fallback
+ // assertion below still must hold.
+ t.diagnostic(`node already on the stripped PATH at ${probe.stdout.trim()}`);
+ } else {
+ const before = spawnSync('/bin/sh', ['-c', 'node -e "process.exit(0)"'], { env: bare, encoding: 'utf8' });
+ assert.equal(before.status, 127, 'the bug: an agent-spawned `node` is not resolvable');
+ }
+
+ const env = { PATH: withHiveRuntimeFallback(STRIPPED_PATH, root) };
+ const after = spawnSync('/bin/sh', ['-c', 'node -p "1+1"'], { env, encoding: 'utf8' });
+ assert.equal(after.status, 0, `node still unresolvable: ${after.stderr}`);
+ assert.equal(after.stdout.trim(), '2', 'it must be a real Node, not just an executable file');
+});