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 user login shell environment into one-shot process execution to restore missing variables

0xken159a793ade9da2
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index c6dc8d63a..8c751f11e 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -25,6 +25,7 @@ import { homedir, hostname } from 'os'
import { env } from './config/env.js'
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'
@@ -829,6 +830,18 @@ async function runForeground(session: AuthSession): Promise<void> {
}
const sqliteWarning = sqlitePreflightMessage()
if (sqliteWarning) console.warn(sqliteWarning)
+ // Capture the user's shell environment NOW, not on the first recap. It is a synchronous spawn, and
+ // paying it here — where the daemon is already doing blocking startup work — keeps it off the path
+ // of a live turn, where a slow profile (nvm, conda, …) would stall frame handling instead.
+ // See lib/loginShellEnv.ts: this is what lets a recap reach a credential the user exports from their
+ // rc file, which a launchd/systemd-parented daemon never read.
+ {
+ const t0 = Date.now()
+ const captured = Object.keys(warmLoginShellEnvironment()).length
+ console.log(captured
+ ? `[env] read ${captured} variables from the login shell in ${Date.now() - t0}ms (engine one-shots only)`
+ : '[env] could not read a login shell environment — engine one-shots use the daemon environment only')
+ }
for (const target of herdrStartup) {
console.log(target.state === 'available'
? `[terminal] Herdr session ${target.sessionName}: available`
diff --git a/cli/src/lib/loginShellEnv.spec.ts b/cli/src/lib/loginShellEnv.spec.ts
new file mode 100644
index 000000000..28ddb6bf4
--- /dev/null
+++ b/cli/src/lib/loginShellEnv.spec.ts
@@ -0,0 +1,69 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import {
+ loginShellEnvironment,
+ oneShotParentEnv,
+ resetLoginShellEnvironmentCache,
+ warmLoginShellEnvironment,
+} from './loginShellEnv.js'
+
+const realShell = process.env.SHELL
+
+afterEach(() => {
+ if (realShell === undefined) delete process.env.SHELL
+ else process.env.SHELL = realShell
+ delete process.env.HARNESS_LOGIN_SHELL_PROBE
+ resetLoginShellEnvironmentCache()
+})
+
+describe('loginShellEnvironment', () => {
+ /**
+ * The property the pi fix rests on: the daemon's own environment always wins, so every variable it
+ * already has keeps its value and nothing that works today can change. The shell only fills gaps.
+ */
+ it('never lets the shell override a variable the daemon already has', () => {
+ process.env.HARNESS_LOGIN_SHELL_PROBE = 'from-daemon'
+ resetLoginShellEnvironmentCache()
+ warmLoginShellEnvironment()
+
+ expect(oneShotParentEnv().HARNESS_LOGIN_SHELL_PROBE).toBe('from-daemon')
+ })
+
+ it('never spawns a shell on the one-shot path — only an explicit warm-up does', () => {
+ resetLoginShellEnvironmentCache()
+ // Reading before warming must be free: a ~1s synchronous spawn inside a recap raced a 200ms
+ // timeout in devinTrust.spec and would stall a live turn just the same.
+ expect(loginShellEnvironment()).toEqual({})
+ expect(oneShotParentEnv().PATH).toBe(process.env.PATH)
+ })
+
+ it('still carries the daemon environment when no shell can be consulted', () => {
+ delete process.env.SHELL
+ resetLoginShellEnvironmentCache()
+
+ expect(warmLoginShellEnvironment()).toEqual({})
+ expect(oneShotParentEnv().PATH).toBe(process.env.PATH)
+ })
+
+ it('refuses a relative or bogus SHELL rather than spawning it', () => {
+ process.env.SHELL = 'zsh' // not absolute
+ resetLoginShellEnvironmentCache()
+ expect(warmLoginShellEnvironment()).toEqual({})
+ })
+
+ it('caches, so a recap never pays for the probe twice', () => {
+ resetLoginShellEnvironmentCache()
+ expect(warmLoginShellEnvironment()).toBe(warmLoginShellEnvironment())
+ })
+
+ // Reads ~/.zshrc etc., so it only runs where a real shell exists — the environment this fixes.
+ it.skipIf(process.platform === 'win32' || !realShell?.startsWith('/'))(
+ 'captures variables an interactive login shell exports', () => {
+ resetLoginShellEnvironmentCache()
+ const captured = warmLoginShellEnvironment()
+
+ // A login shell always exports these two; if neither came back, the capture is not working.
+ expect(Object.keys(captured).length).toBeGreaterThan(0)
+ expect(captured.PATH ?? captured.HOME).toBeDefined()
+ },
+ )
+})
diff --git a/cli/src/lib/loginShellEnv.ts b/cli/src/lib/loginShellEnv.ts
new file mode 100644
index 000000000..e32d26e19
--- /dev/null
+++ b/cli/src/lib/loginShellEnv.ts
@@ -0,0 +1,84 @@
+/**
+ * The environment the user's own shell would give a command — for engine one-shots only.
+ *
+ * A recap child inherits the DAEMON's environment, and the daemon is detached: its parent is launchd
+ * (or systemd), not a shell, so it never read the user's profile. An engine that resolves its
+ * credential from an environment variable therefore works in the user's pane and fails in the recap.
+ *
+ * Measured, and this is the whole bug behind "pi stopped recapping": `~/.pi/agent/models.json` holds
+ * "apiKey": "$LOCAL_API_KEY"
+ * and that variable is exported from `~/.zshrc`. The daemon has no such variable, so pi exited 1 with
+ * "No API key found for the selected model" after 14ms, every time, while `pi` in a tmux pane was fine.
+ *
+ * INTERACTIVE login shell, deliberately. `zsh -lc` reads .zprofile/.zlogin and would NOT have found it;
+ * `.zshrc` is only read for interactive shells. Verified both ways on the reporting machine.
+ *
+ * This is not a new privilege: an engine started in a pane already runs with exactly this environment.
+ * All it does is let the recap run where the agent it summarises runs.
+ */
+import { spawnSync } from 'node:child_process'
+
+/** Printed before the dump so anything a chatty rc file writes to stdout is skipped, not parsed. */
+const SENTINEL = '__HARNESS_ENV_BEGIN__'
+const CAPTURE_TIMEOUT_MS = 5_000
+
+let cached: NodeJS.ProcessEnv | null = null
+
+/** What was captured, or `{}` if nothing has been. NEVER spawns — see warmLoginShellEnvironment. */
+export function loginShellEnvironment(): NodeJS.ProcessEnv {
+ return cached ?? {}
+}
+
+/**
+ * Perform the capture. Best-effort and once per process; a shell that is missing, slow, or broken
+ * yields `{}` and the caller still gets `process.env`, i.e. exactly today's behaviour.
+ *
+ * This is a SYNCHRONOUS spawn and it is deliberately not called lazily from the one-shot path. It was,
+ * and it cost ~1s inside `runDevinOneShot`, which raced that suite's 200ms timeout into a flaky
+ * failure — a live turn would have paid the same stall. The daemon warms it during startup instead,
+ * where blocking work already happens, and tests never spawn a shell at all.
+ */
+export function warmLoginShellEnvironment(): NodeJS.ProcessEnv {
+ if (cached) return cached
+ cached = {}
+ if (process.platform === 'win32') return cached
+ const shell = process.env.SHELL
+ if (!shell || !shell.startsWith('/')) return cached
+
+ let result
+ try {
+ result = spawnSync(shell, ['-lic', `printf %s ${SENTINEL}; env -0`], {
+ timeout: CAPTURE_TIMEOUT_MS,
+ encoding: 'utf8',
+ // An interactive shell with no tty still runs rc files; keep its stdin closed so nothing waits.
+ stdio: ['ignore', 'pipe', 'ignore'],
+ })
+ } catch { return cached }
+ const stdout = result?.stdout
+ if (result?.error || typeof stdout !== 'string') return cached
+ const start = stdout.indexOf(SENTINEL)
+ if (start < 0) return cached
+
+ const parsed: NodeJS.ProcessEnv = {}
+ for (const entry of stdout.slice(start + SENTINEL.length).split('\0')) {
+ const eq = entry.indexOf('=')
+ if (eq <= 0) continue
+ parsed[entry.slice(0, eq)] = entry.slice(eq + 1)
+ }
+ cached = parsed
+ return cached
+}
+
+/**
+ * The base environment for a one-shot child: the user's shell environment, with the daemon's own
+ * environment layered ON TOP.
+ *
+ * That precedence is the safety property — every variable the daemon already has keeps its current
+ * value, so nothing that works today can change. The shell only fills in what is missing.
+ */
+export function oneShotParentEnv(): NodeJS.ProcessEnv {
+ return { ...loginShellEnvironment(), ...process.env }
+}
+
+/** Test seam. */
+export function resetLoginShellEnvironmentCache(): void { cached = null }
diff --git a/cli/src/lib/oneshot.ts b/cli/src/lib/oneshot.ts
index dbc201e60..5cc3edd3b 100644
--- a/cli/src/lib/oneshot.ts
+++ b/cli/src/lib/oneshot.ts
@@ -15,6 +15,7 @@ import {
type DisposableWorker,
type OneShotEngine,
} from './disposableOneShotPool.js'
+import { oneShotParentEnv } from './loginShellEnv.js'
import { scrubTerminalContext } from './terminalEnvironment.js'
function claudeBin(): string {
@@ -287,7 +288,7 @@ class CodexWorker extends ProcessWorker {
...(effort ? ['-c', `model_reasoning_effort="${effort}"`] : []),
'-',
]
- const processEnv = scrubTerminalContext({ ...process.env })
+ const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
const child = spawn(process.env.CODEX_PATH || 'codex', args, {
cwd, env: processEnv, detached: true, stdio: ['pipe', 'ignore', 'pipe'],
})
@@ -376,7 +377,7 @@ class CursorWorker extends ProcessWorker {
'--output-format', 'stream-json',
...(model ? ['--model', model] : []),
]
- const processEnv = scrubTerminalContext({ ...process.env })
+ const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
const child = spawn(cursorBin(), args, {
cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
})
@@ -497,7 +498,7 @@ class OpencodeWorker extends ProcessWorker {
// self-registers this ephemeral recap session). `--format json` streams `{type:'text',part:{text}}`.
mkdirSync(OPENCODE_RECAP_DATA_DIR, { recursive: true, mode: 0o700 })
const args = ['run', '--pure', '--format', 'json', ...(model ? ['--model', model] : [])]
- const processEnv = scrubTerminalContext({ ...process.env })
+ const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
processEnv.OPENCODE_DATA_DIR = OPENCODE_RECAP_DATA_DIR
const child = spawn(opencodeBin(), args, {
cwd: OPENCODE_RECAP_DATA_DIR, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
@@ -648,7 +649,7 @@ class KiloWorker extends ProcessWorker {
// the moment a prompt arrived, i.e. every recap ran against the user's real repository instead of an
// empty scratch dir. It then hung indexing and gathering context until the 60s timeout, so no
// `turn_summary` was ever emitted and the device tile stayed on `processing` forever.
- const { args, env: processEnv } = kiloOneShotSpawn(model, process.env)
+ const { args, env: processEnv } = kiloOneShotSpawn(model, oneShotParentEnv())
const child = spawn(kiloBin(), args, {
cwd: KILO_RECAP_DATA_DIR, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
})
@@ -744,7 +745,7 @@ class PiWorker extends ProcessWorker {
// answer, so the worker can be pre-warmed and fed later. `--no-session` keeps the recap out of the
// user's session store; `--no-extensions` stops the machine discovery extension from registering it.
const args = ['-p', '--no-session', '--no-extensions', ...(model ? ['--model', model] : [])]
- const processEnv = scrubTerminalContext({ ...process.env })
+ const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
const child = spawn(piBin(), args, {
cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
})
@@ -822,7 +823,7 @@ class CommandCodeWorker extends ProcessWorker {
// recap shows up as a session. There is no --no-hooks flag; the scrubbed terminal context below
// stops our own SessionStart hook registering this process.
const args = ['-p', '--no-session', ...(model ? ['-m', model] : [])]
- const processEnv = scrubTerminalContext({ ...process.env })
+ const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
const child = spawn(commandCodeBin(), args, {
cwd, env: processEnv, detached: true, stdio: ['pipe', 'pipe', 'pipe'],
})
@@ -990,7 +991,7 @@ export function runCursorOneShot(opts: OneShotOptions): Promise<OneShotResult> {
export function grokOneShotSpawn(
opts: Pick<OneShotOptions, 'prompt' | 'model' | 'effort' | 'cwd'>,
scratchHome: string,
- parentEnv: NodeJS.ProcessEnv = process.env,
+ parentEnv: NodeJS.ProcessEnv = oneShotParentEnv(),
): { args: string[]; env: NodeJS.ProcessEnv } {
const args = [
'--cwd', opts.cwd,
@@ -1091,7 +1092,7 @@ export async function runGrokOneShot(opts: OneShotOptions): Promise<OneShotResul
*/
export function agyOneShotSpawn(
opts: Pick<OneShotOptions, 'prompt' | 'model' | 'effort'>,
- parentEnv: NodeJS.ProcessEnv = process.env,
+ parentEnv: NodeJS.ProcessEnv = oneShotParentEnv(),
): { args: string[]; env: NodeJS.ProcessEnv } {
const args = [
'--output-format', 'json',
@@ -1215,7 +1216,7 @@ export async function runAgyOneShot(opts: OneShotOptions): Promise<OneShotResult
export function copilotOneShotSpawn(
opts: Pick<OneShotOptions, 'prompt' | 'model'>,
sessionId: string,
- parentEnv: NodeJS.ProcessEnv = process.env,
+ parentEnv: NodeJS.ProcessEnv = oneShotParentEnv(),
): { args: string[]; env: NodeJS.ProcessEnv } {
const args = [
'-p', opts.prompt,
@@ -1318,7 +1319,7 @@ function museBin(): string {
export function runMuseOneShot(opts: OneShotOptions): Promise<OneShotResult> {
if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('muse one-shot aborted'), { name: 'AbortError' }))
const args = ['exec', opts.prompt, ...(opts.model ? ['--model', opts.model] : [])]
- const processEnv: NodeJS.ProcessEnv = scrubTerminalContext({ ...process.env, MUSE_NO_AUTO_UPDATE: '1' })
+ const processEnv: NodeJS.ProcessEnv = scrubTerminalContext({ ...oneShotParentEnv(), MUSE_NO_AUTO_UPDATE: '1' })
const timeoutMs = opts.timeoutMs ?? 60_000
return new Promise<OneShotResult>((resolve, reject) => {
@@ -1387,7 +1388,7 @@ export function runMuseOneShot(opts: OneShotOptions): Promise<OneShotResult> {
*/
function ampOneShotAttempt(opts: OneShotOptions, timeoutMs: number): Promise<OneShotResult | null> {
const args = ['-x', '--no-notifications', '-m', opts.model || env.AMP_SUMMARY_MODE]
- const processEnv: NodeJS.ProcessEnv = scrubTerminalContext({ ...process.env, AMP_DISABLE_PLUGINS: '1' })
+ const processEnv: NodeJS.ProcessEnv = scrubTerminalContext({ ...oneShotParentEnv(), AMP_DISABLE_PLUGINS: '1' })
delete processEnv.MACHINE_ID
return new Promise<OneShotResult | null>((resolve, reject) => {
@@ -1452,7 +1453,7 @@ export async function runAmpOneShot(opts: OneShotOptions): Promise<OneShotResult
export function runHermesOneShot(opts: OneShotOptions): Promise<OneShotResult> {
if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('hermes one-shot aborted'), { name: 'AbortError' }))
const args = ['chat', '-q', opts.prompt, '-Q', '--source', 'tool', ...(opts.model ? ['-m', opts.model] : [])]
- const processEnv = scrubTerminalContext({ ...process.env })
+ const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
const timeoutMs = opts.timeoutMs ?? 60_000
return new Promise<OneShotResult>((resolve, reject) => {
@@ -1515,7 +1516,7 @@ export function runDevinOneShot(opts: OneShotOptions): Promise<OneShotResult> {
if (opts.signal?.aborted) return Promise.reject(Object.assign(new Error('devin one-shot aborted'), { name: 'AbortError' }))
if (opts.cwd) trustDevinWorkspace(opts.cwd, (m) => console.warn('[recap] could not trust the devin scratch dir:', m))
const args = ['-p', opts.prompt, ...(opts.model ? ['--model', opts.model] : [])]
- const processEnv = scrubTerminalContext({ ...process.env })
+ const processEnv = scrubTerminalContext({ ...oneShotParentEnv() })
const timeoutMs = opts.timeoutMs ?? 60_000
return new Promise<OneShotResult>((resolve, reject) => {