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.

Install missing coding engines for the current OS user (#510)

Deea1b19bcda199
diff --git a/cli/src/lib/engineBin.ts b/cli/src/lib/engineBin.ts
index 2f1cc432e..4032f09d8 100644
--- a/cli/src/lib/engineBin.ts
+++ b/cli/src/lib/engineBin.ts
@@ -11,6 +11,7 @@ import { homedir } from 'node:os'
import { basename, delimiter, isAbsolute, join, normalize, sep } from 'node:path'
import { env } from '../config/env.js'
import { ENGINES, PROCESS_ENGINES, type AgentEngine } from '../engines/types.js'
+import { engineInstallPaths, engineInstallRecipe } from './engineInstall.js'
// Keep this historical import surface for callers, but never duplicate the
// catalog here. `engines/types.ts` is the one iterable source of truth.
@@ -182,21 +183,12 @@ function addAll(target: Set<string>, identities: readonly ExecutableFileIdentity
}
function vendorFallbackCommands(engine: AgentEngine): string[] {
- const home = homedir()
+ const recipe = engineInstallRecipe(engine)
+ const paths = recipe ? engineInstallPaths(recipe) : []
switch (engine) {
- case 'claude': return [join(home, '.local', 'bin', 'claude')]
- case 'codex': return [join(home, '.local', 'bin', 'codex')]
- case 'cursor': return [join(home, '.local', 'bin', 'cursor-agent'), join(home, '.local', 'bin', 'agent')]
- case 'opencode': return [join(home, '.opencode', 'bin', 'opencode')]
- case 'hermes': return [join(home, '.local', 'bin', 'hermes')]
- case 'devin': return [join(home, '.local', 'bin', 'devin')]
- case 'muse': return [join(home, '.local', 'bin', 'muse')]
- case 'amp': return [join(home, '.amp', 'bin', 'amp'), join(home, '.local', 'bin', 'amp')]
- case 'kilo': return [join(home, '.kilo', 'bin', 'kilo'), join(home, '.local', 'bin', 'kilo')]
- case 'grok': return [join(env.GROK_HOME, 'bin', 'grok'), join(home, '.local', 'bin', 'grok')]
- case 'agy': return [join(home, '.local', 'bin', 'agy')]
- case 'copilot': return [join(home, '.local', 'bin', 'copilot')]
- default: return []
+ case 'cursor': return [...paths, join(homedir(), '.local', 'bin', 'agent')]
+ case 'grok': return [join(env.GROK_HOME, 'bin', 'grok'), ...paths]
+ default: return paths
}
}
diff --git a/cli/src/lib/engineInstall.ts b/cli/src/lib/engineInstall.ts
index 42ca5f046..8b13c72ed 100644
--- a/cli/src/lib/engineInstall.ts
+++ b/cli/src/lib/engineInstall.ts
@@ -6,6 +6,8 @@
* installs successfully but does not provide the expected executable is worse than no recipe.
*/
+import { homedir } from 'node:os'
+import { join } from 'node:path'
import { isTerminalEngine, type AgentEngine, type ProcessEngine } from '../engines/types.js'
/** How to find the executable after the installer returns. */
@@ -123,6 +125,22 @@ export function engineInstallRecipe(engine: AgentEngine): EngineInstallRecipe |
return isTerminalEngine(engine) ? undefined : ENGINE_INSTALL[engine]
}
+/** Stable across managed Node upgrades and writable by this OS user, unlike shared Homebrew. */
+export function npmEnginePrefix(): string {
+ return join(homedir(), '.local')
+}
+
+/** The same candidates are used by launch, availability checks, and process discovery. */
+export function engineInstallPaths(recipe: EngineInstallRecipe): string[] {
+ return [...new Set([
+ ...(recipe.executable.homeRelativePaths ?? []).map((path) => join(homedir(), path)),
+ ...(recipe.executable.absolutePaths ?? []),
+ ...(recipe.executable.npmGlobal
+ ? recipe.executable.names.map((name) => join(npmEnginePrefix(), 'bin', name))
+ : []),
+ ])]
+}
+
export const INSTALLABLE_ENGINES: ReadonlySet<AgentEngine> = new Set(
Object.keys(ENGINE_INSTALL) as AgentEngine[],
)
diff --git a/cli/src/lib/engineInstall.user.spec.ts b/cli/src/lib/engineInstall.user.spec.ts
new file mode 100644
index 000000000..42285500c
--- /dev/null
+++ b/cli/src/lib/engineInstall.user.spec.ts
@@ -0,0 +1,107 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { execFileSync, spawnSync } from 'node:child_process'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { resolveBinaryOnPath } from './binaryOnPath.js'
+import { buildEngineLaunchArgv, commandAvailableInInteractiveShell, shellSingleQuote } from './engineLaunch.js'
+import type { EngineInstallRecipe } from './engineInstall.js'
+
+// Use real npm against a local package, with networking and lifecycle scripts disabled.
+// Fake npm missed the fresh-account EACCES failure in a shared Homebrew prefix.
+const npm = resolveBinaryOnPath('npm')!
+const roots: string[] = []
+const locked: string[] = []
+afterEach(() => {
+ vi.unstubAllEnvs()
+ for (const dir of locked.splice(0)) chmodSync(dir, 0o755)
+ for (const dir of roots.splice(0)) rmSync(dir, { recursive: true, force: true })
+})
+
+function fixture() {
+ const root = mkdtempSync(join(tmpdir(), 'harness-user-engine-'))
+ roots.push(root)
+ const home = join(root, "home with 'quotes")
+ mkdirSync(home)
+ vi.stubEnv('HOME', home)
+ const shared = join(root, 'shared-prefix')
+ mkdirSync(shared, { mode: 0o555 })
+ locked.push(shared)
+ const pkg = join(root, 'package')
+ mkdirSync(pkg)
+ const name = 'harness-user-engine-fixture'
+ writeFileSync(join(pkg, 'package.json'), JSON.stringify({ name, version: '1.0.0', bin: { [name]: 'engine.js' } }))
+ writeFileSync(join(pkg, 'engine.js'), '#!/usr/bin/env node\nconsole.log("ENGINE_READY:" + JSON.stringify(process.argv.slice(2)))\n')
+ const runtime = (name: string) => {
+ const bin = join(root, name, 'bin')
+ mkdirSync(bin, { recursive: true })
+ symlinkSync(process.execPath, join(bin, 'node'))
+ symlinkSync(npm, join(bin, 'npm'))
+ return join(bin, 'node')
+ }
+ const recipe: EngineInstallRecipe = {
+ command: `npm install -g --offline --ignore-scripts --no-audit --no-fund ${shellSingleQuote(pkg)}`,
+ source: 'local fixture',
+ executable: { names: [name], npmGlobal: true },
+ }
+ const env = {
+ HOME: home, PATH: '/usr/bin:/bin',
+ // Both npm spellings must be overridden for the install without rewriting this user's config.
+ npm_config_prefix: shared, NPM_CONFIG_PREFIX: shared,
+ }
+ writeFileSync(join(home, '.npmrc'), `prefix=${shared}\n`)
+ const run = (node: string, install = recipe, shell = '/bin/sh') => {
+ const script = buildEngineLaunchArgv('codex', { installIfMissing: install }, shell, node, 'grid', null)[2]
+ return spawnSync(shell, ['-c', script, 'harness-engine', name, 'argument with spaces'], {
+ env, encoding: 'utf8', timeout: 20_000,
+ })
+ }
+ return { home, shared, name, recipe, env, runtime, run }
+}
+
+describe('engine installation for a fresh OS user', () => {
+ for (const shell of ['/bin/sh', '/bin/zsh'].filter(existsSync)) {
+ it(`installs with ${shell} into the user home when the npm global prefix is not writable`, () => {
+ const f = fixture()
+ const result = f.run(f.runtime('node-one'), f.recipe, shell)
+ expect(result.status, result.stdout + result.stderr).toBe(0)
+ expect(result.stdout).toContain('ENGINE_READY:["argument with spaces"]')
+ expect(existsSync(join(f.home, '.local/bin', f.name))).toBe(true)
+ expect(readdirSync(f.shared)).toEqual([])
+ expect(readFileSync(join(f.home, '.npmrc'), 'utf8')).toBe(`prefix=${f.shared}\n`)
+ })
+ }
+
+ it('reuses the user install after a managed Node upgrade, even with no node or npm on PATH', async () => {
+ const f = fixture()
+ const first = f.run(f.runtime('node-one'))
+ expect(first.status, first.stdout + first.stderr).toBe(0)
+ rmSync(join(f.home, '..', 'node-one'), { recursive: true })
+ const upgradedNode = f.runtime('node-two')
+ const second = f.run(upgradedNode, { ...f.recipe, command: 'exit 93' })
+ expect(second.status, second.stdout + second.stderr).toBe(0)
+ expect(second.stdout).toContain('ENGINE_READY:')
+ expect(second.stdout).not.toContain('engine is missing')
+
+ // The availability probe uses the same per-user candidates as the launch, without installing.
+ const probe = join(f.home, '..', 'bash')
+ writeFileSync(probe, '#!/bin/sh\nshift\nexec /bin/sh -c "$@"\n', { mode: 0o700 })
+ vi.stubEnv('PATH', f.env.PATH)
+ await expect(commandAvailableInInteractiveShell(f.name, probe, f.recipe)).resolves.toBe(true)
+ })
+
+ it('keeps using an existing global engine instead of installing another copy', () => {
+ const f = fixture()
+ // This prefix is writable during setup only; the missing-engine test above owns EACCES.
+ chmodSync(f.shared, 0o755)
+ const node = f.runtime('node-one')
+ execFileSync(npm, ['install', '-g', '--offline', '--ignore-scripts', '--no-audit', '--no-fund', join(f.home, '..', 'package')], {
+ env: { ...f.env, PATH: `${join(node, '..')}:${f.env.PATH}` }, stdio: 'pipe',
+ })
+ chmodSync(f.shared, 0o555)
+ const result = f.run(node, { ...f.recipe, command: 'exit 93' })
+ expect(result.status, result.stdout + result.stderr).toBe(0)
+ expect(result.stdout).toContain('ENGINE_READY:')
+ expect(existsSync(join(f.home, '.local/bin', f.name))).toBe(false)
+ })
+})
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index 17f068403..ce55afc42 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -1030,7 +1030,7 @@ if [ "$1" = prefix ]; then exit 0; fi
)
expect(result).toMatchObject({ code: 0, ranEngine: true })
- expect(result.stdout).toContain('enabling Harness managed Node.js/npm')
+ expect(result.stdout).toContain('installing for this user')
})
it('does not add the npm bootstrap to non-npm installers', () => {
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 904fe5434..e9290c7ab 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -4,7 +4,7 @@ import { isAbsolute, basename, dirname, join } from 'node:path'
import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
import { binaryOnPath, resolveBinaryOnPath } from './binaryOnPath.js'
import { engineBin } from './engineBin.js'
-import type { EngineInstallRecipe } from './engineInstall.js'
+import { engineInstallPaths, npmEnginePrefix, type EngineInstallRecipe } from './engineInstall.js'
import { GRID_NO_UPDATE_CHECK_VAR, gridBinaryPath } from './gridExec.js'
import { managedNodePath } from './nodeRuntime.js'
import { RAISE_OPEN_FILES_SH } from './openFiles.js'
@@ -649,13 +649,6 @@ export function shellSingleQuote(value: string): string {
return `'${value.replace(/'/g, `'"'"'`)}'`
}
-function installedPathCandidates(recipe: EngineInstallRecipe): string[] {
- return [
- ...(recipe.executable.homeRelativePaths ?? []).map((path) => join(homedir(), path)),
- ...(recipe.executable.absolutePaths ?? []),
- ]
-}
-
/**
* Make npm recipes work on machines where Harness owns Node instead of installing it system-wide.
*
@@ -665,31 +658,22 @@ function installedPathCandidates(recipe: EngineInstallRecipe): string[] {
* 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 {
+function npmRuntimePrelude(recipe: EngineInstallRecipe, runtimeNode: string): 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',
+ 'if ! command -v node >/dev/null 2>&1 || ! 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')
}
@@ -730,7 +714,12 @@ export function gridPanePrelude(binary: string): 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(' ')
+ const paths = engineInstallPaths(recipe).map(shellSingleQuote).join(' ')
+ // Scope both npm env spellings to the installer subprocess. Do not rewrite .npmrc or install
+ // into a different OS user's shared prefix, and do not tie the engine to a versioned Node folder.
+ const installCommand = recipe.executable.npmGlobal
+ ? `(export npm_config_prefix=${shellSingleQuote(npmEnginePrefix())} NPM_CONFIG_PREFIX=${shellSingleQuote(npmEnginePrefix())}; eval ${shellSingleQuote(install)})`
+ : `eval ${shellSingleQuote(install)}`
const candidates = [names, paths].filter(Boolean).join(' ')
const tryCandidates = candidates
? `for candidate in ${candidates}; do try_engine "$candidate" "$@" || true; done`
@@ -758,12 +747,21 @@ function installIfMissingThenExecScript(recipe: EngineInstallRecipe, runtimeNode
' shift',
' harness_engine "$resolved" "$@"',
'}',
+ // A previously installed npm launcher also needs Node. Resolve the runtime before executing
+ // it, not just before installing it; fresh users often have no system node on PATH.
+ npmRuntimePrelude(recipe, runtimeNode),
'try_engine "$1" "$@" || true',
tryCandidates,
- npmRuntimePrelude(recipe, runtimeNode, true),
tryNpmGlobal,
+ ...(recipe.executable.npmGlobal ? [
+ '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',
+ ] : []),
`printf '%s\\n' 'harness: engine is missing — installing it in this terminal' 'harness: $ ${install.replace(/'/g, "'\\''")}' ''`,
- `if eval ${JSON.stringify(install)}; then`,
+ ...(recipe.executable.npmGlobal ? [`printf '%s\\n' ${shellSingleQuote(`harness: installing for this user in ${npmEnginePrefix()}`)}`] : []),
+ `if ${installCommand}; then`,
' hash -r 2>/dev/null || true',
' try_engine "$1" "$@" || true',
` ${tryCandidates}`,
@@ -778,10 +776,10 @@ function installIfMissingThenExecScript(recipe: EngineInstallRecipe, runtimeNode
function availabilityScript(recipe: EngineInstallRecipe | undefined): string {
const names = recipe?.executable.names.map(shellSingleQuote).join(' ') ?? ''
- const paths = recipe ? installedPathCandidates(recipe).map(shellSingleQuote).join(' ') : ''
+ const paths = recipe ? engineInstallPaths(recipe).map(shellSingleQuote).join(' ') : ''
const candidates = [names, paths].filter(Boolean).join(' ')
return [
- ...(recipe ? [npmRuntimePrelude(recipe, managedNodePath(), false)] : []),
+ ...(recipe ? [npmRuntimePrelude(recipe, managedNodePath())] : []),
`for candidate in "$@" ${candidates}; do`,
' case "$candidate" in',
' */*) resolved="$candidate" ;;',
@@ -813,7 +811,7 @@ export async function commandAvailableInInteractiveShell(
const interactive = interactiveEngineShell(shell)
if (!interactive) {
return binaryOnPath(command)
- || (recipe ? installedPathCandidates(recipe).some((candidate) => binaryOnPath(candidate)) : false)
+ || (recipe ? engineInstallPaths(recipe).some((candidate) => binaryOnPath(candidate)) : false)
}
return await new Promise((resolve) => {
execFile(