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.

feat: inject npmRuntimePrelude to ensure managed Node/npm are available to engines when missing from PATH

0xken15b972983d4cd8
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index ee4c19bf5..8a9fbb8d9 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -205,8 +205,8 @@ describe('buildEngineLaunchArgv with installIfMissing', () => {
command: string,
executable: EngineInstallRecipe['executable'] = { names: ['harness-no-such-engine'] },
): EngineInstallRecipe => ({ command, source: 'test fixture', executable })
- const script = (install: EngineInstallRecipe): string =>
- buildEngineLaunchArgv('opencode', { installIfMissing: install }, '/bin/zsh')[2]
+ const script = (install: EngineInstallRecipe, runtimeNode?: string): string =>
+ buildEngineLaunchArgv('opencode', { installIfMissing: install }, '/bin/zsh', runtimeNode)[2]
it('execs an installed engine without running the installer', async () => {
await expect(runPaneScript(script(recipe('false')))).resolves.toMatchObject({ code: 0, ranEngine: true })
@@ -239,12 +239,48 @@ describe('buildEngineLaunchArgv with installIfMissing', () => {
expect(result).toMatchObject({ code: 1, ranEngine: false })
expect(result.stdout).toContain('install completed, but its executable could not be found')
})
+
+ it('enables npm from the managed Node runtime when the pane PATH has no npm', async () => {
+ const runtimeBin = mkdtempSync(join(tmpdir(), 'harness-managed-node-bin-'))
+ const emptyPath = mkdtempSync(join(tmpdir(), 'harness-empty-path-'))
+ dirs.push(runtimeBin, emptyPath)
+ const runtimeNode = executable(runtimeBin, 'node')
+ const engineSource = join(runtimeBin, 'engine-source')
+ writeFileSync(engineSource, '#!/bin/sh\n/usr/bin/printf "HARNESS-TEST-ENGINE-RAN\\n"\n')
+ chmodSync(engineSource, 0o700)
+ const installed = join(runtimeBin, 'installed-engine')
+ const npm = join(runtimeBin, 'npm')
+ writeFileSync(npm, `#!/bin/sh
+if [ "$1" = prefix ]; then exit 0; fi
+/bin/cp ${JSON.stringify(engineSource)} ${JSON.stringify(installed)}
+/bin/chmod 700 ${JSON.stringify(installed)}
+`)
+ chmodSync(npm, 0o700)
+
+ const result = await runPaneScript(
+ script(recipe('npm install -g fixture', {
+ names: ['harness-no-such-engine'],
+ absolutePaths: [installed],
+ npmGlobal: true,
+ }), runtimeNode),
+ 'harness-no-such-engine',
+ { PATH: emptyPath },
+ )
+
+ expect(result).toMatchObject({ code: 0, ranEngine: true })
+ expect(result.stdout).toContain('enabling Harness managed Node.js/npm')
+ })
+
+ it('does not add the npm bootstrap to non-npm installers', () => {
+ expect(script(recipe('true'))).not.toContain('managed Node.js/npm')
+ })
})
/** Run one generated pane script under /bin/sh and report what it did. */
async function runPaneScript(
paneScript: string,
command = '/usr/bin/printf',
+ env: NodeJS.ProcessEnv = process.env,
): Promise<{ code: number; stdout: string; ranEngine: boolean }> {
const { execFile } = await import('node:child_process')
const marker = 'HARNESS-TEST-ENGINE-RAN'
@@ -252,7 +288,7 @@ async function runPaneScript(
execFile(
'/bin/sh',
['-c', paneScript, 'harness-engine', command, `${marker}\n`],
- { timeout: 10_000 },
+ { timeout: 10_000, env },
(error, stdout) => {
const code = error && typeof (error as { code?: unknown }).code === 'number'
? (error as unknown as { code: number }).code
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 8c0abec1b..b5e20542f 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -1,10 +1,11 @@
import { execFile } from 'node:child_process'
import { homedir, userInfo } from 'node:os'
-import { isAbsolute, basename, join } from 'node:path'
+import { isAbsolute, basename, dirname, join } from 'node:path'
import type { AgentEngine } from '../engines/types.js'
import { binaryOnPath } from './binaryOnPath.js'
import { engineBin } from './engineBin.js'
import type { EngineInstallRecipe } from './engineInstall.js'
+import { managedNodePath } from './nodeRuntime.js'
/**
* Best-effort "skip permission prompts" flag per engine, confirmed against each vendor's own docs.
@@ -176,6 +177,7 @@ export function buildEngineLaunchArgv(
engine: AgentEngine,
opts: LaunchCommandOptions = {},
shell: string | undefined = undefined,
+ runtimeNode: string = managedNodePath(),
): string[] {
const command = buildEngineCommandArgv(engine, opts)
const interactive = interactiveEngineShell(shell)
@@ -186,7 +188,7 @@ export function buildEngineLaunchArgv(
// of this launch is that the agent's environment is the one the user asked for.
const prelude = clearEnvPrelude(opts.clearEnv)
const body = opts.installIfMissing
- ? installIfMissingThenExecScript(opts.installIfMissing)
+ ? installIfMissingThenExecScript(opts.installIfMissing, runtimeNode)
: opts.installFirst
? installThenExecScript(opts.installFirst)
: 'exec "$@"'
@@ -244,6 +246,43 @@ function installedPathCandidates(recipe: EngineInstallRecipe): string[] {
]
}
+/**
+ * Make npm recipes work on machines where Harness owns Node instead of installing it system-wide.
+ *
+ * The verified Node archive provisioned by `harness start` includes npm, but the daemon deliberately
+ * does not mutate the user's PATH. A tmux login shell can therefore have neither `node` nor `npm`
+ * even though the runtime executing Harness has both. Prefer any npm the user already configured;
+ * otherwise prepend the managed runtime's bin directory for this pane only. This is portable across
+ * macOS and Linux and avoids an interactive/root package-manager install in an agent launch.
+ */
+function npmRuntimePrelude(recipe: EngineInstallRecipe, runtimeNode: string, required: boolean): string {
+ if (!recipe.executable.npmGlobal) return ''
+ const bins = [...new Set([dirname(runtimeNode), dirname(process.execPath)])]
+ .map(shellSingleQuote)
+ .join(' ')
+ return [
+ 'if ! command -v npm >/dev/null 2>&1; then',
+ ` for harness_node_bin in ${bins}; do`,
+ ' if [ -x "$harness_node_bin/node" ] && [ -x "$harness_node_bin/npm" ]; then',
+ ' PATH="$harness_node_bin${PATH:+:$PATH}"',
+ ' export PATH',
+ ' hash -r 2>/dev/null || true',
+ ...(required ? [
+ ` printf '%s\\n' 'harness: npm is missing from PATH — enabling Harness managed Node.js/npm'`,
+ ] : []),
+ ' break',
+ ' fi',
+ ' done',
+ 'fi',
+ ...(required ? [
+ 'if ! command -v npm >/dev/null 2>&1; then',
+ ` printf '%s\\n' 'harness: npm is unavailable and the managed Node.js/npm runtime could not be used.'`,
+ ' exit 1',
+ 'fi',
+ ] : []),
+ ].join('\n')
+}
+
/**
* Install-if-missing has to resolve twice: before installing, and again after it returns.
*
@@ -253,7 +292,7 @@ function installedPathCandidates(recipe: EngineInstallRecipe): string[] {
* source-owned candidate paths below bridge that one-shell gap without sourcing arbitrary profile
* files a second time. npm installs also get their active global prefix as a fallback.
*/
-function installIfMissingThenExecScript(recipe: EngineInstallRecipe): string {
+function installIfMissingThenExecScript(recipe: EngineInstallRecipe, runtimeNode: string): string {
const install = recipe.command
const names = recipe.executable.names.map(shellSingleQuote).join(' ')
const paths = installedPathCandidates(recipe).map(shellSingleQuote).join(' ')
@@ -286,6 +325,7 @@ function installIfMissingThenExecScript(recipe: EngineInstallRecipe): string {
'}',
'try_engine "$1" "$@" || true',
tryCandidates,
+ npmRuntimePrelude(recipe, runtimeNode, true),
tryNpmGlobal,
`printf '%s\\n' 'harness: engine is missing — installing it in this terminal' 'harness: $ ${install.replace(/'/g, "'\\''")}' ''`,
`if eval ${JSON.stringify(install)}; then`,
@@ -306,6 +346,7 @@ function availabilityScript(recipe: EngineInstallRecipe | undefined): string {
const paths = recipe ? installedPathCandidates(recipe).map(shellSingleQuote).join(' ') : ''
const candidates = [names, paths].filter(Boolean).join(' ')
return [
+ ...(recipe ? [npmRuntimePrelude(recipe, managedNodePath(), false)] : []),
`for candidate in "$@" ${candidates}; do`,
' case "$candidate" in',
' */*) resolved="$candidate" ;;',