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.

refactor: wrap engine processes in interactive shells to correctly resolve user-scoped environment variables and CLI binaries.

0xken15e16a87a3ecf3
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 1937ce119..aaffdb2bb 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -27,7 +27,6 @@ import { VERSION } from './version.js'
import { sqlitePreflightMessage } from './lib/sqliteAvailability.js'
import { warmLoginShellEnvironment } from './lib/loginShellEnv.js'
import { ensureUtf8Locale } from './lib/childLocale.js'
-import { binaryOnPath } from './lib/binaryOnPath.js'
import { CableSession } from './cable/cableSession.js'
import { DaemonCableHost, cableEventFor, cableQuestionFor } from './cable/cableHost.js'
import { MachineListCache } from './device/machineList.js'
@@ -41,7 +40,7 @@ import { readOrMintComputerId } from './lib/computerIdentity.js'
import { renderLoginSuccessHtml } from './lib/loginPage.js'
import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession, writeAuthSession, type AuthSession } from './lib/authSession.js'
import { ENGINE_CLI_COMMANDS, ENGINES } from './lib/engineBin.js'
-import { buildEngineLaunchArgv } from './lib/engineLaunch.js'
+import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, interactiveEngineShell } from './lib/engineLaunch.js'
import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'
import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'
import { findLiveSession } from './lib/sessionRepair.js'
@@ -2642,7 +2641,9 @@ async function runForeground(session: AuthSession): Promise<void> {
return { ok: false, error: 'CWD_NOT_FOUND' }
}
const label = `${engine}-${Date.now()}`.replace(/[^A-Za-z0-9_-]/g, '-')
- const argv = buildEngineLaunchArgv(engine, { bypassPermission })
+ const launchOptions = { bypassPermission }
+ const command = buildEngineCommandArgv(engine, launchOptions)
+ const argv = buildEngineLaunchArgv(engine, launchOptions)
const spawned = await tmuxBackend.create({ cwd, label, command: argv })
if (spawned.state !== 'succeeded') {
console.warn(`[agent] create ${engine} failed · tmux could not open a pane · ${spawned.reason ?? ''}`)
@@ -2654,22 +2655,18 @@ async function runForeground(session: AuthSession): Promise<void> {
const session = registry.byRuntimeEngine(spawned.runtime, engine)
if (session) return { ok: true, session }
}
- // `tmux new-session` reports success for a command that does not exist — it opens the pane, the
- // shell says "<engine>: command not found", and the session is gone a moment later. Discovery then
- // finds nothing and the user is told ENGINE_DID_NOT_START, which on a fresh machine is almost
- // always "that CLI is not installed" and reads like a Harness bug instead. Measured on a container
- // with only claude present: `tmux new-session -d "codex …"` exits 0 and leaves no session.
- //
- // The check is done HERE rather than before spawning on purpose: the tmux server may carry a
- // different PATH than this daemon (it inherits from whoever started it), so a binary we cannot see
- // might still launch. Refusing up front would turn that into a false negative; explaining a failure
- // that already happened cannot.
- const bin = argv[0]
- if (!binaryOnPath(bin)) {
- console.warn(`[agent] create ${engine} failed · "${bin}" is not installed or not on PATH`)
+ // A detached daemon and an already-running tmux server do not necessarily have the user's terminal
+ // PATH. The launch above therefore used the interactive shell; inspect that same context before
+ // claiming a binary is absent. Checking process.env here was a false "not installed" report on
+ // macOS and Ubuntu whenever the CLI lived in .zshrc/.bashrc (nvm, asdf, vendor installers).
+ const bin = command[0]
+ if (!await commandAvailableInInteractiveShell(bin)) {
+ const shell = interactiveEngineShell()
+ console.warn(`[agent] create ${engine} failed · "${bin}" is unavailable from the user's ${shell?.label ?? 'daemon PATH'}`)
return { ok: false, error: 'ENGINE_NOT_INSTALLED' }
}
- console.warn(`[agent] create ${engine} failed · "${bin}" started but no engine process appeared in the pane`)
+ const shell = interactiveEngineShell()
+ console.warn(`[agent] create ${engine} failed · "${bin}" resolved from the user's ${shell?.label ?? 'daemon PATH'} but no engine process appeared in the pane`)
return { ok: false, error: 'ENGINE_DID_NOT_START' }
}
diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.ts
index 1cc4bf4cb..8482f8989 100644
--- a/cli/src/lib/engineLaunch.spec.ts
+++ b/cli/src/lib/engineLaunch.spec.ts
@@ -1,28 +1,48 @@
-import { describe, expect, it } from 'vitest'
-import { BYPASS_PERMISSION_FLAGS, buildEngineLaunchArgv } from './engineLaunch.js'
+import { afterEach, describe, expect, it } from 'vitest'
+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import {
+ BYPASS_PERMISSION_FLAGS,
+ buildEngineCommandArgv,
+ buildEngineLaunchArgv,
+ commandAvailableInInteractiveShell,
+} from './engineLaunch.js'
import { ENGINES } from '../engines/types.js'
import { engineBin } from './engineBin.js'
describe('buildEngineLaunchArgv', () => {
- it('starts with the resolved binary and adds nothing when bypass is not requested', () => {
- expect(buildEngineLaunchArgv('claude')).toEqual([engineBin('claude')])
- expect(buildEngineLaunchArgv('claude', { bypassPermission: false })).toEqual([engineBin('claude')])
+ it('wraps zsh in its interactive login form and execs the resolved binary', () => {
+ expect(buildEngineLaunchArgv('claude', {}, '/bin/zsh')).toEqual([
+ '/bin/zsh', '-lic', 'exec "$@"', 'harness-engine', engineBin('claude'),
+ ])
+ })
+
+ it('uses Ubuntu bash interactive startup files without making it a login shell', () => {
+ expect(buildEngineLaunchArgv('claude', {}, '/bin/bash')).toEqual([
+ '/bin/bash', '-ic', 'exec "$@"', 'harness-engine', engineBin('claude'),
+ ])
+ })
+
+ it('falls back to direct execution when no absolute shell is available', () => {
+ expect(buildEngineLaunchArgv('claude', {}, '')).toEqual([engineBin('claude')])
+ expect(buildEngineLaunchArgv('claude', {}, 'zsh')).toEqual([engineBin('claude')])
})
it('appends the confirmed flag for engines with a known bypass flag', () => {
- expect(buildEngineLaunchArgv('claude', { bypassPermission: true }))
+ expect(buildEngineCommandArgv('claude', { bypassPermission: true }))
.toEqual([engineBin('claude'), '--dangerously-skip-permissions'])
- expect(buildEngineLaunchArgv('codex', { bypassPermission: true }))
+ expect(buildEngineCommandArgv('codex', { bypassPermission: true }))
.toEqual([engineBin('codex'), '--dangerously-bypass-approvals-and-sandbox'])
- expect(buildEngineLaunchArgv('cursor', { bypassPermission: true }))
+ expect(buildEngineCommandArgv('cursor', { bypassPermission: true }))
.toEqual([engineBin('cursor'), '--force'])
- expect(buildEngineLaunchArgv('opencode', { bypassPermission: true }))
+ expect(buildEngineCommandArgv('opencode', { bypassPermission: true }))
.toEqual([engineBin('opencode'), '--auto'])
})
it('is a no-op for engines with no confirmed flag, even when bypass is requested', () => {
- expect(buildEngineLaunchArgv('pi', { bypassPermission: true })).toEqual([engineBin('pi')])
- expect(buildEngineLaunchArgv('hermes', { bypassPermission: true })).toEqual([engineBin('hermes')])
+ expect(buildEngineCommandArgv('pi', { bypassPermission: true })).toEqual([engineBin('pi')])
+ expect(buildEngineCommandArgv('hermes', { bypassPermission: true })).toEqual([engineBin('hermes')])
})
it('has an entry (possibly null) for every known engine — no engine silently falls through', () => {
@@ -31,3 +51,48 @@ describe('buildEngineLaunchArgv', () => {
}
})
})
+
+const dirs: string[] = []
+const originalProbePath = process.env.HARNESS_ENGINE_TEST_PATH
+
+afterEach(() => {
+ if (originalProbePath === undefined) delete process.env.HARNESS_ENGINE_TEST_PATH
+ else process.env.HARNESS_ENGINE_TEST_PATH = originalProbePath
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+})
+
+function executable(dir: string, name: string): string {
+ const path = join(dir, name)
+ writeFileSync(path, '#!/bin/sh\nexit 0\n')
+ chmodSync(path, 0o700)
+ return path
+}
+
+function bashProbeShell(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'harness-engine-shell-'))
+ dirs.push(dir)
+ const shell = join(dir, 'bash')
+ writeFileSync(shell, `#!/bin/sh
+[ "$1" = '-ic' ] || exit 97
+shift
+script="$1"
+shift
+PATH="$HARNESS_ENGINE_TEST_PATH"
+export PATH
+exec /bin/sh -c "$script" "$@"
+`)
+ chmodSync(shell, 0o700)
+ return shell
+}
+
+describe('commandAvailableInInteractiveShell', () => {
+ it('uses the same bash interactive PATH that launches a new engine', async () => {
+ const binDir = mkdtempSync(join(tmpdir(), 'harness-engine-bin-'))
+ dirs.push(binDir)
+ executable(binDir, 'kilo')
+ process.env.HARNESS_ENGINE_TEST_PATH = binDir
+
+ await expect(commandAvailableInInteractiveShell('kilo', bashProbeShell())).resolves.toBe(true)
+ await expect(commandAvailableInInteractiveShell('missing-engine', bashProbeShell())).resolves.toBe(false)
+ })
+})
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 392a1a7ea..5a4f08296 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -1,4 +1,8 @@
+import { execFile } from 'node:child_process'
+import { userInfo } from 'node:os'
+import { isAbsolute, basename } from 'node:path'
import type { AgentEngine } from '../engines/types.js'
+import { binaryOnPath } from './binaryOnPath.js'
import { engineBin } from './engineBin.js'
/**
@@ -28,9 +32,8 @@ export interface LaunchCommandOptions {
bypassPermission?: boolean
}
-/** Full argv (binary first) to launch `engine` in a fresh tmux pane. `cwd` is set separately via
- * tmux `new-session -c`, not part of this argv. */
-export function buildEngineLaunchArgv(engine: AgentEngine, opts: LaunchCommandOptions = {}): string[] {
+/** The executable argv, before the interactive-shell wrapper is applied. */
+export function buildEngineCommandArgv(engine: AgentEngine, opts: LaunchCommandOptions = {}): string[] {
const argv = [engineBin(engine)]
if (opts.bypassPermission) {
const flags = BYPASS_PERMISSION_FLAGS[engine]
@@ -38,3 +41,78 @@ export function buildEngineLaunchArgv(engine: AgentEngine, opts: LaunchCommandOp
}
return argv
}
+
+export interface InteractiveEngineShell {
+ path: string
+ args: readonly string[]
+ label: string
+}
+
+/**
+ * The shell users get in a terminal is not the detached daemon's environment.
+ *
+ * zsh needs its login files as well as .zshrc; Ubuntu's usual bash setup puts
+ * nvm/asdf and vendor PATH edits in .bashrc, so it must be interactive but not
+ * login. Other POSIX-like shells get the portable interactive form.
+ */
+function currentUserShell(): string | undefined {
+ if (process.env.SHELL && isAbsolute(process.env.SHELL)) return process.env.SHELL
+ try {
+ const shell = userInfo().shell
+ return shell && isAbsolute(shell) ? shell : undefined
+ } catch {
+ return undefined
+ }
+}
+
+export function interactiveEngineShell(shell: string | undefined = undefined): InteractiveEngineShell | null {
+ const candidate = shell === undefined ? currentUserShell() : shell
+ if (!candidate || !isAbsolute(candidate)) return null
+ switch (basename(candidate).toLowerCase()) {
+ case 'zsh': return { path: candidate, args: ['-lic'], label: 'zsh login shell' }
+ case 'bash': return { path: candidate, args: ['-ic'], label: 'bash interactive shell' }
+ default: return { path: candidate, args: ['-ic'], label: `${basename(candidate)} interactive shell` }
+ }
+}
+
+/**
+ * Full argv for a fresh tmux pane. `exec` replaces the shell with the engine,
+ * preserving process discovery while loading the same startup files a user
+ * gets in Terminal/iTerm/Ubuntu Terminal. Arguments are positional, not a
+ * shell command string, so engine paths and flags cannot be interpolated.
+ */
+export function buildEngineLaunchArgv(
+ engine: AgentEngine,
+ opts: LaunchCommandOptions = {},
+ shell: string | undefined = undefined,
+): string[] {
+ const command = buildEngineCommandArgv(engine, opts)
+ const interactive = interactiveEngineShell(shell)
+ if (!interactive) return command
+ return [interactive.path, ...interactive.args, 'exec "$@"', 'harness-engine', ...command]
+}
+
+const AVAILABILITY_SCRIPT = 'resolved="$(command -v "$1" 2>/dev/null)" || exit 1\n'
+ + '[ -n "$resolved" ] && [ -f "$resolved" ] && [ -x "$resolved" ]'
+
+/**
+ * Does the same interactive shell that launches a new agent resolve this CLI?
+ *
+ * The fallback is intentionally the daemon PATH: without a usable absolute
+ * SHELL there is no safer context to consult and direct launch is used too.
+ */
+export async function commandAvailableInInteractiveShell(
+ command: string,
+ shell: string | undefined = undefined,
+): Promise<boolean> {
+ const interactive = interactiveEngineShell(shell)
+ if (!interactive) return binaryOnPath(command)
+ return await new Promise((resolve) => {
+ execFile(
+ interactive.path,
+ [...interactive.args, AVAILABILITY_SCRIPT, 'harness-engine-probe', command],
+ { timeout: 5_000 },
+ (error) => resolve(!error),
+ )
+ })
+}
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index a2dfe44fb..8d53bad2b 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -39,6 +39,7 @@ esac
await expect(backend.kill(created.runtime)).resolves.toEqual({ state: 'succeeded', dispatch: 'executed' })
expect(readFileSync(calls, 'utf8').trim().split('\n')).toEqual([
'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test',
+ 'set-option -t %42 mouse on',
'display-message -p -t %42 #{session_id}',
'kill-session -t $7',
])