Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor([issue-3194]): own AI-CLI child-env composition in one helper
[._.]/ Adam Eivy6b628752e8f7
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.jsindex e51468c517..ca1a3d7bd2 100644--- a/server/cos-runner/index.js+++ b/server/cos-runner/index.js@@ -17,7 +17,7 @@ import http from 'http';import { Server as SocketServer } from 'socket.io';import { ensureDir, PATHS, sleep } from '../lib/fileUtils.js';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';-import { withSpawnCwdEnv } from '../lib/spawnCwd.js';+import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { prepareCliPrompt } from '../lib/cliProviderArgs.js';import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';import { createStreamJsonParser } from './streamJsonParser.js';@@ -188,10 +188,17 @@ app.post('/spawn', async (req, res) => {// Ensure workspacePath is validconst cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : ROOT_DIR;- // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). This is the path the- // bug was reported through: the log line above named the app's workspace- // correctly while every OpenCode agent still ran in the PortOS folder.- const childEnv = (() => { const e = withSpawnCwdEnv({ ...process.env, ...envVars }, cwd); delete e.CLAUDECODE; return e; })();+ // Shared composition (provider.envVars + OpenCode models map + PWD pin ++ // CLAUDECODE strip) — see buildCliChildEnv. The runner receives the provider's+ // envVars over HTTP rather than a provider record, so it wraps them into the+ // `provider` slot; with no `command` in the payload the OpenCode layer is a+ // no-op and the result is exactly `{ ...process.env, ...envVars }` as before.+ // The PWD pin is the path #3193 was reported through: the log line above named+ // the app's workspace correctly while every OpenCode agent still ran in the+ // PortOS folder. No `guard`, preserving today's behavior: this runner is a+ // separate process that does not carry the pm2 shim (only the in-process+ // agent-spawning paths opt in).+ const childEnv = buildCliChildEnv({ provider: { envVars }, cwd });// Resolve a bare npm-installed CLI (opencode/codex/claude/… — a .cmd/.bat// shim on Windows) to its real path and wrap a shim as `cmd.exe /c <path>` sodiff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.jsindex 01b1e22abe..d43d45fe58 100644--- a/server/cos-runner/index.test.js+++ b/server/cos-runner/index.test.js@@ -34,10 +34,11 @@ describe('cos-runner spawn — Windows CLI shim resolve+wrap (#2243)', () => {});it('resolves the command against the child env (childEnv) so a provider PATH override is honored', () => {- // childEnv (process.env + provider envVars, CLAUDECODE stripped) is built- // BEFORE the resolve so PATH resolution sees the child's PATH, and is reused- // as the spawn env — matching the working server/services/runner.js path.- const childEnvIdx = RUNNER_SRC.indexOf('const childEnv = (() =>');+ // childEnv (process.env + provider envVars, CLAUDECODE stripped, PWD pinned+ // — composed by the shared buildCliChildEnv) is built BEFORE the resolve so+ // PATH resolution sees the child's PATH, and is reused as the spawn env —+ // matching the working server/services/runner.js path.+ const childEnvIdx = RUNNER_SRC.indexOf('const childEnv = buildCliChildEnv(');const prepareIdx = RUNNER_SRC.indexOf('prepareCliSpawn(command, deliveredArgs, childEnv)');expect(childEnvIdx, 'childEnv must be defined').toBeGreaterThan(-1);expect(prepareIdx, 'prepareCliSpawn must run against childEnv').toBeGreaterThan(-1);diff --git a/server/lib/README.md b/server/lib/README.mdindex 3bd8e91b2f..0344f9a447 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -105,6 +105,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). || `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring the models map under `provider.ollama.models` (bare ids) for Ollama-backed OpenCode providers. Fixes --model rejection. |+| `cliChildEnv.js` | `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` — the one place the AI-CLI child environment is composed. Layers `baseEnv → before → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to the spawn cwd, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. Replaces the hand-rolled copy that lived at all five spawn sites (`services/runner.js`, `cliProviderRun.js`, `services/agentCliSpawning.js`, `tuiPromptRunner.js`, `cos-runner/index.js`) and made every env-level fix an N-file sweep (#3194). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY) — `cliChildEnv.test.js` asserts the composed order per call site. || `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. || `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. || `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |diff --git a/server/lib/cliChildEnv.js b/server/lib/cliChildEnv.jsnew file mode 100644index 0000000000..6c648651d6--- /dev/null+++ b/server/lib/cliChildEnv.js@@ -0,0 +1,112 @@+/**+ * Child-environment composition for every AI-CLI spawn.+ *+ * Five spawn sites — `services/runner.js` (Run Prompt), `lib/cliProviderRun.js`+ * (fire-and-collect), `services/agentCliSpawning.js` (CoS agents),+ * `lib/tuiPromptRunner.js` (PTY TUI runs), and `cos-runner/index.js`+ * (`POST /spawn`) — each independently rebuilt the same env tuple:+ *+ * { ...baseEnv, ...providerEnv, ...opencodeEnv }+ * → pin PWD to the spawn cwd+ * → strip CLAUDECODE+ * → prepend the pm2 guard shim (agent-spawning sites only)+ *+ * Three separate fixes each paid an N-file sweep to keep those five in step:+ * the OpenCode declared-models map (#2190/#2243), the `CLAUDECODE` strip, and+ * the `PWD` pin (#3193). Every time, the guard against missing a site was+ * "a reviewer noticed" or a source-grep test. This module owns the composition+ * so the next env-level concern is a one-file change (#3194).+ *+ * **Precedence is the load-bearing part.** The sites do NOT all layer their+ * extras the same way, and flattening them into one order would silently change+ * which value wins:+ *+ * - `agentCliSpawning` puts `forgeTokenEnv`/`claudeSettingsEnv` BEFORE+ * `provider.envVars`, so an explicit provider `GH_TOKEN` still overrides the+ * repo-owner-pinned one.+ * - `tuiPromptRunner` puts `TERM`/`COLORTERM` AFTER everything, so the PTY+ * always gets a truecolor terminal regardless of provider config.+ *+ * Hence two distinct slots — `before` (lower precedence than the provider) and+ * `extra` (higher) — rather than one `extra`. `cliChildEnv.test.js` asserts the+ * exact composed order for each of the five call sites.+ *+ * Deliberately NOT in scope: a `spawnAiCli({ command, args, cwd, env })` wrapper+ * that would also own cwd resolution and the Windows `.cmd` shim. The eight+ * spawn shapes differ too much (child_process vs node-pty, stdio variants,+ * kill-tree wiring) to fold in the same change. `lib/aiToolkit/runner.js` is+ * also out of scope: it is vendored and must not import out to other PortOS+ * modules (see `lib/aiToolkit/CLAUDE.md`), so it keeps its inline pin.+ */++import { withSpawnCwdEnv } from './spawnCwd.js';+import { buildOpencodeEnvVars } from './opencodeConfig.js';+import { agentGuardEnv } from './agentGuard/index.js';++/**+ * Compose the environment an AI-CLI child process is spawned with.+ *+ * Layering, lowest precedence first:+ * `baseEnv` → `before` → `provider.envVars` → OpenCode env → `extra`+ * then `PWD` is pinned to `cwd`, `CLAUDECODE` is stripped, and — only when+ * `guard` is true — the pm2 guard shim is prepended to the final `PATH`.+ *+ * @param {object} options+ * @param {NodeJS.ProcessEnv|object} [options.baseEnv=process.env] - env to start from.+ * Callers that must not leak host credentials to an autonomous agent (e.g. the+ * autofixer) pass a sanitized allowlist here; every later layer still overlays it.+ * @param {object|null} [options.before] - env spread AFTER `baseEnv` but BEFORE+ * `provider.envVars`, so a provider-configured value still wins over it+ * (forgeTokenEnv, claudeSettingsEnv).+ * @param {{command?:string, envVars?:object, models?:string[], defaultModel?:string|null, ollamaBacked?:boolean}|null} [options.provider]+ * - the provider record. `provider.envVars` is layered in, and the provider's+ * command/ollamaBacked flags decide whether an OpenCode config is built.+ * @param {string|null} [options.model] - the model being run this invocation, used+ * to build the OpenCode declared-models map. Pass `provider.defaultModel` when+ * the site has no per-call model.+ * @param {string|undefined|null} options.cwd - the directory being handed to+ * `spawn`/`pty.spawn`; `PWD` is pinned to it (see `withSpawnCwdEnv`, #3193).+ * @param {object|null} [options.extra] - env spread LAST, so it overrides every+ * other layer including `provider.envVars` (TERM/COLORTERM for a PTY).+ * @param {boolean} [options.guard=false] - prepend the pm2 guard shim onto the+ * final `PATH` so an unrestricted agent can't `pm2 kill` the shared daemon.+ * Only the two agent-spawning sites opt in; the Run Prompt / fire-and-collect+ * paths keep today's unguarded behavior.+ * @returns {object} a fresh env object safe to hand straight to `spawn`+ */+export function buildCliChildEnv({+ baseEnv = process.env,+ before = null,+ provider = null,+ model = null,+ cwd,+ extra = null,+ guard = false,+} = {}) {+ // buildOpencodeEnvVars rebuilds OPENCODE_CONFIG_CONTENT with a declared models+ // map for OpenCode Ollama providers (an empty object for everyone else) so the+ // injected `--model ollama/<id>` isn't rejected as "not valid" — see #2190.+ // It comes after provider.envVars to override the provider's STATIC+ // OPENCODE_CONFIG_CONTENT, which it was built from.+ const env = withSpawnCwdEnv(+ {+ ...baseEnv,+ ...(before || {}),+ ...(provider?.envVars || {}),+ ...buildOpencodeEnvVars(provider, model),+ ...(extra || {}),+ },+ cwd,+ );++ // CLAUDECODE is set when PortOS itself runs inside Claude Code; passing it+ // through would make a spawned Claude CLI think it's nested inside the parent+ // session.+ delete env.CLAUDECODE;++ // Must be applied to the FINAL PATH (after every override above), or a+ // provider-configured PATH would drop the shim back off the front.+ if (guard) Object.assign(env, agentGuardEnv(env));++ return env;+}diff --git a/server/lib/cliChildEnv.test.js b/server/lib/cliChildEnv.test.jsnew file mode 100644index 0000000000..d3277dd4fd--- /dev/null+++ b/server/lib/cliChildEnv.test.js@@ -0,0 +1,296 @@+import { describe, it, expect } from 'vitest';+import { readFileSync, readdirSync } from 'fs';+import { join, relative } from 'path';+import { fileURLToPath } from 'url';+import { buildCliChildEnv } from './cliChildEnv.js';+import { AGENT_GUARD_BIN } from './agentGuard/index.js';++// An OpenCode provider that IS ollama-backed — the only shape for which+// buildOpencodeEnvVars returns anything. Everyone else gets `{}`, which is why+// the OpenCode layer is invisible at the other call sites.+const OLLAMA_OPENCODE = {+ command: 'opencode',+ ollamaBacked: true,+ models: ['qwen2.5:7b'],+ defaultModel: 'qwen2.5:7b',+ envVars: { OPENCODE_CONFIG_CONTENT: '{"permission":"deny"}', API_KEY: 'from-provider' },+};++const declaredModels = (env) => Object.keys(JSON.parse(env.OPENCODE_CONFIG_CONTENT).provider.ollama.models);++describe('buildCliChildEnv — layering', () => {+ it('layers baseEnv < before < provider.envVars < extra', () => {+ const env = buildCliChildEnv({+ baseEnv: { WHO: 'base', FROM_BASE: '1' },+ before: { WHO: 'before', FROM_BEFORE: '1' },+ provider: { envVars: { WHO: 'provider', FROM_PROVIDER: '1' } },+ extra: { WHO: 'extra', FROM_EXTRA: '1' },+ });+ expect(env.WHO).toBe('extra');+ // Every layer still contributes its own non-conflicting keys.+ expect(env).toMatchObject({ FROM_BASE: '1', FROM_BEFORE: '1', FROM_PROVIDER: '1', FROM_EXTRA: '1' });+ });++ // The `before` slot exists specifically so agentCliSpawning's forgeTokenEnv+ // can be overridden by an explicit provider credential. Collapsing it into+ // `extra` would silently flip which GH_TOKEN the agent's `gh pr create` uses.+ it('lets provider.envVars beat `before` but lose to `extra`', () => {+ const env = buildCliChildEnv({+ baseEnv: {},+ before: { GH_TOKEN: 'repo-owner-pinned' },+ provider: { envVars: { GH_TOKEN: 'provider-explicit', TERM: 'dumb' } },+ extra: { TERM: 'xterm-256color' },+ });+ expect(env.GH_TOKEN).toBe('provider-explicit');+ expect(env.TERM).toBe('xterm-256color');+ });++ // The OpenCode map is built FROM provider.envVars.OPENCODE_CONFIG_CONTENT, so+ // it must land after it — otherwise the static value the map was derived from+ // wins and `--model ollama/<id>` is rejected again (#2190).+ it('overrides the provider static OPENCODE_CONFIG_CONTENT with the declared-models map', () => {+ const env = buildCliChildEnv({ baseEnv: {}, provider: OLLAMA_OPENCODE, model: 'llama3.1:8b' });+ expect(declaredModels(env).sort()).toEqual(['llama3.1:8b', 'qwen2.5:7b']);+ // Non-conflicting provider vars survive.+ expect(env.API_KEY).toBe('from-provider');+ // The stored base is merged, not clobbered.+ expect(JSON.parse(env.OPENCODE_CONFIG_CONTENT).permission).toBe('deny');+ });++ it('is a no-op OpenCode layer for a non-OpenCode provider', () => {+ const env = buildCliChildEnv({ baseEnv: {}, provider: { command: 'claude', envVars: { A: '1' } }, model: 'opus' });+ expect(env.OPENCODE_CONFIG_CONTENT).toBeUndefined();+ expect(env.A).toBe('1');+ });++ it('tolerates an absent provider / before / extra', () => {+ expect(buildCliChildEnv({ baseEnv: { A: '1' } })).toEqual({ A: '1' });+ expect(buildCliChildEnv({ baseEnv: { A: '1' }, provider: null, before: null, extra: null })).toEqual({ A: '1' });+ });++ it('defaults baseEnv to process.env', () => {+ expect(buildCliChildEnv({ cwd: undefined }).PATH).toBe(process.env.PATH);+ });++ it('copies rather than mutating the caller env', () => {+ const baseEnv = { A: '1' };+ const env = buildCliChildEnv({ baseEnv, extra: { B: '2' } });+ expect(baseEnv).toEqual({ A: '1' });+ expect(env).not.toBe(baseEnv);+ });+});++describe('buildCliChildEnv — PWD pin and CLAUDECODE strip', () => {+ it('pins PWD to the spawn cwd, overriding a stale inherited value (#3193)', () => {+ const env = buildCliChildEnv({ baseEnv: { PWD: '/repos/PortOS' }, cwd: '/repos/my-app' });+ expect(env.PWD).toBe('/repos/my-app');+ });++ it('leaves the inherited PWD alone when no cwd is passed', () => {+ expect(buildCliChildEnv({ baseEnv: { PWD: '/repos/PortOS' } }).PWD).toBe('/repos/PortOS');+ });++ // The pin runs LAST, over the composed object — so a provider that sets its+ // own PWD cannot re-point the child at the wrong repo.+ it('pins PWD over a provider-supplied PWD', () => {+ const env = buildCliChildEnv({+ baseEnv: {}, provider: { envVars: { PWD: '/somewhere/else' } }, cwd: '/repos/my-app',+ });+ expect(env.PWD).toBe('/repos/my-app');+ });++ it('strips CLAUDECODE from every layer that could supply it', () => {+ const env = buildCliChildEnv({+ baseEnv: { CLAUDECODE: '1' },+ before: { CLAUDECODE: '1' },+ provider: { envVars: { CLAUDECODE: '1' } },+ extra: { CLAUDECODE: '1' },+ });+ expect(env.CLAUDECODE).toBeUndefined();+ });+});++describe('buildCliChildEnv — pm2 guard', () => {+ it('leaves PATH untouched without `guard` (Run Prompt / fire-and-collect paths)', () => {+ const env = buildCliChildEnv({ baseEnv: { PATH: '/usr/bin' } });+ expect(env.PATH).toBe('/usr/bin');+ expect(env.PORTOS_REAL_PM2).toBeUndefined();+ });++ // Load-bearing: the shim must sit on the FINAL PATH. Prepending it before the+ // provider's override would let a `--dangerously-skip-permissions` agent reach+ // the real pm2 and `pm2 kill` the shared daemon.+ it('prepends the guard shim onto the PATH a provider override produced', () => {+ const env = buildCliChildEnv({+ baseEnv: { PATH: '/usr/bin' },+ provider: { envVars: { PATH: '/provider/bin' } },+ guard: true,+ });+ expect(env.PATH.startsWith(`${AGENT_GUARD_BIN}`)).toBe(true);+ expect(env.PATH).toContain('/provider/bin');+ expect(env.PATH).not.toContain('/usr/bin');+ });+});++// One case per real call site, asserting the precedence THAT site depends on.+// The sites do not all layer the same way, so a single "extra wins" rule would+// have silently changed two of them — these pin the actual contracts.+describe('buildCliChildEnv — per-call-site composition', () => {+ it('runner.js / cliProviderRun.js: provider.envVars over baseEnv, guarded only for the runner', () => {+ const args = { baseEnv: { A: 'base', PATH: '/usr/bin' }, provider: { envVars: { A: 'provider' } }, cwd: '/w' };+ expect(buildCliChildEnv({ ...args, guard: true }).A).toBe('provider');+ expect(buildCliChildEnv({ ...args, guard: true }).PATH).toContain(AGENT_GUARD_BIN);+ // The fire-and-collect path is not an agent — it must stay unguarded.+ expect(buildCliChildEnv(args).PATH).toBe('/usr/bin');+ });++ it('cliProviderRun.js: honors a sanitized baseEnv instead of process.env', () => {+ // The autofixer passes an allowlist so host credentials never reach the CLI.+ const env = buildCliChildEnv({ baseEnv: { PATH: '/usr/bin' }, provider: { envVars: {} }, cwd: '/w' });+ expect(env.HOME).toBeUndefined();+ expect(env.PATH).toBe('/usr/bin');+ });++ it('agentCliSpawning.js: forgeToken/claudeSettings sit UNDER provider.envVars', () => {+ const env = buildCliChildEnv({+ baseEnv: { PATH: '/usr/bin' },+ before: { GH_TOKEN: 'forge', AWS_PROFILE: 'from-settings' },+ provider: { envVars: { GH_TOKEN: 'provider' } },+ model: 'opus',+ cwd: '/w',+ guard: true,+ });+ expect(env.GH_TOKEN).toBe('provider'); // explicit provider credential wins+ expect(env.AWS_PROFILE).toBe('from-settings'); // non-conflicting settings survive+ expect(env.PWD).toBe('/w');+ expect(env.PATH).toContain(AGENT_GUARD_BIN);+ });++ it('tuiPromptRunner.js / tuiUsageScrape.js: TERM/COLORTERM beat provider.envVars', () => {+ const env = buildCliChildEnv({+ baseEnv: { TERM: 'dumb' },+ provider: { envVars: { TERM: 'vt100', COLORTERM: '' } },+ cwd: '/sandbox',+ extra: { TERM: 'xterm-256color', COLORTERM: 'truecolor' },+ });+ expect(env.TERM).toBe('xterm-256color');+ expect(env.COLORTERM).toBe('truecolor');+ expect(env.PWD).toBe('/sandbox');+ // A PTY prompt run is not an agent — no shim.+ expect(env.PORTOS_REAL_PM2).toBeUndefined();+ });++ it('cos-runner/index.js: request envVars over process.env, no OpenCode layer, unguarded', () => {+ // The runner receives loose envVars over HTTP with no `command` to classify.+ const env = buildCliChildEnv({+ baseEnv: { A: 'base', PATH: '/usr/bin', CLAUDECODE: '1' },+ provider: { envVars: { A: 'request' } },+ cwd: '/workspace',+ });+ expect(env).toEqual({ A: 'request', PATH: '/usr/bin', PWD: '/workspace' });+ });++ it('askService.js: no cwd means no PWD is invented', () => {+ const env = buildCliChildEnv({ baseEnv: { PATH: '/usr/bin' }, provider: { envVars: {} }, model: 'opus' });+ expect(env.PWD).toBeUndefined();+ });++ it('visionCli.js: the image dir is pinned as PWD so the CLI can find the file', () => {+ const env = buildCliChildEnv({+ baseEnv: { PWD: '/repos/PortOS' }, provider: OLLAMA_OPENCODE, model: 'llava:7b', cwd: '/tmp/portos-vision-x',+ });+ expect(env.PWD).toBe('/tmp/portos-vision-x');+ // And the vision model is declared, so `--model ollama/llava:7b` is accepted.+ expect(declaredModels(env)).toContain('llava:7b');+ });+});++// Source invariant. The whole point of this module is that the next env-level+// concern is a ONE-file change — which only holds if no spawn site quietly+// rebuilds the tuple by hand again. Three separate fixes (the OpenCode models+// map, the CLAUDECODE strip, the PWD pin) each had to sweep every site because+// nothing failed when one was missed.+//+// Deliberately DISCOVERS the offenders rather than listing the known call sites:+// an allowlist of "these files must call the builder" passes the day someone+// adds a ninth spawn site, which is exactly when the guard needs to fire.+describe('no spawn site rebuilds the CLI child env by hand', () => {+ const SERVER_DIR = fileURLToPath(new URL('..', import.meta.url));++ // Files allowed to compose the tuple themselves, each with the reason.+ const EXEMPT = new Map([+ ['lib/cliChildEnv.js', 'this module IS the shared composer'],+ ['lib/aiToolkit/runner.js', 'vendored toolkit — must not import out to other PortOS modules'],+ ]);++ const collectSources = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ if (entry.name === 'node_modules' || entry.name.startsWith('.')) return [];+ const abs = join(dir, entry.name);+ if (entry.isDirectory()) return collectSources(abs);+ if (!entry.name.endsWith('.js') || entry.name.endsWith('.test.js')) return [];+ return [relative(SERVER_DIR, abs)];+ });++ // Two independent markers, because either one alone has a blind spot: a new+ // site could strip CLAUDECODE without spreading provider.envVars, or spread+ // provider.envVars while forgetting the strip (which is itself the bug).+ //+ // Marker A — the CLAUDECODE strip. Crisp: every path that runs a coding CLI+ // strips it, and nothing else in the tree does.+ const STRIPS_CLAUDECODE = /delete\s+[A-Za-z_$][\w$]*\.CLAUDECODE\b/;++ // Marker B — a provider-env-over-base composition that is handed to a child+ // running in a workspace. The `cwd` requirement is what separates a real spawn+ // env from the two shapes that merge the same objects for a different purpose+ // and correctly need none of this: a model-id LOOKUP env+ // (`resolveBedrockCliModel({ env })`, `resolveWindowsExecutable(…, searchEnv)`)+ // and a capability PROBE (`agy models`, `--version`) — neither runs a model,+ // writes files, or has a workspace to be misrouted into.+ //+ // A window rather than a parser: the composition is always one object literal.+ // KNOWN BLIND SPOT, stated rather than papered over: a real spawn env built+ // with NO cwd (askService's Ask path is the one such shape today) is invisible+ // to this marker. Marker A still catches it as long as the new site strips+ // CLAUDECODE — and a site that does not strip it has the very bug marker B+ // was never going to be able to name.+ const SPREADS_PROVIDER_ENV_INTO_SPAWN = (src) => {+ for (const m of src.matchAll(/\.\.\.\s*(?:process\.env|baseEnv)\b/g)) {+ // Wide enough to span the comment blocks that sit between the composition+ // and the spawn call it feeds (the vendored toolkit runner has ~500 chars+ // of them). Over-matching costs one EXEMPT line; under-matching silently+ // reopens the N-file sweep, so the bias is deliberate.+ const window = src.slice(m.index, m.index + 900);+ if (/\.\.\.\s*[A-Za-z_$][\w$]*\??\.envVars\b/.test(window) && /\bcwd\s*[:,]/.test(window)) return true;+ }+ return false;+ };++ const offenders = () => collectSources(SERVER_DIR).filter((rel) => {+ if (EXEMPT.has(rel)) return false;+ const src = readFileSync(join(SERVER_DIR, rel), 'utf8');+ return STRIPS_CLAUDECODE.test(src) || SPREADS_PROVIDER_ENV_INTO_SPAWN(src);+ });++ it('finds the exempt files (guard is not vacuous)', () => {+ // If the markers stop matching even the composer itself, the scan broke and+ // the assertion below would pass for the wrong reason.+ for (const rel of EXEMPT.keys()) {+ const src = readFileSync(join(SERVER_DIR, rel), 'utf8');+ expect(+ STRIPS_CLAUDECODE.test(src) || SPREADS_PROVIDER_ENV_INTO_SPAWN(src),+ `${rel} no longer matches either marker — the scan broke`,+ ).toBe(true);+ }+ });++ it('every AI-CLI spawn composes its child env through buildCliChildEnv', () => {+ expect(+ offenders(),+ 'These files build an AI-CLI child environment by hand instead of calling '+ + 'buildCliChildEnv (server/lib/cliChildEnv.js). That is what made the OpenCode '+ + 'models map (#2190), the CLAUDECODE strip, and the PWD pin (#3193) each cost an '+ + 'N-file sweep, with a missed site failing silently. Route the spawn through the '+ + 'shared builder, or add the file to EXEMPT above with the reason it must not.',+ ).toEqual([]);+ });+});diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.jsindex 3c099fb397..dae9d49a48 100644--- a/server/lib/cliProviderRun.js+++ b/server/lib/cliProviderRun.js@@ -18,9 +18,8 @@import { spawn } from 'child_process';import { buildCliArgs, prepareCliPrompt } from './cliProviderArgs.js';-import { buildOpencodeEnvVars } from './opencodeConfig.js';import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';-import { withSpawnCwdEnv } from './spawnCwd.js';+import { buildCliChildEnv } from './cliChildEnv.js';/*** Resolve which CLI provider + model a feature should use from the providers@@ -102,19 +101,19 @@ export function runCliProviderPrompt(args = {}) {let stderr = '';let settled = false;- // CLAUDECODE is deleted from the child env so a nested invocation doesn't- // think it's running inside the parent Claude Code session.- // buildOpencodeEnvVars rebuilds OPENCODE_CONFIG_CONTENT with a declared- // models map for OpenCode Ollama providers (empty/no-op otherwise) so the- // injected `--model ollama/<id>` isn't rejected as "not valid" — see- // issue-2190. effectiveProvider carries the per-call model as defaultModel.- // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193).+ // Shared composition (provider.envVars + OpenCode models map + PWD pin ++ // CLAUDECODE strip) — see buildCliChildEnv. No `guard`: this is the+ // fire-and-collect path, not an autonomous agent, so it keeps the unguarded+ // PATH it has always had. effectiveProvider carries the per-call model as+ // defaultModel, which is what the OpenCode declared-models map is built from+ // (its envVars are provider's, unchanged).const effectiveCwd = cwd || process.cwd();- const childEnv = withSpawnCwdEnv(- { ...baseEnv, ...provider.envVars, ...buildOpencodeEnvVars(effectiveProvider, effectiveProvider.defaultModel) },- effectiveCwd,- );- delete childEnv.CLAUDECODE;+ const childEnv = buildCliChildEnv({+ baseEnv,+ provider: effectiveProvider,+ model: effectiveProvider.defaultModel,+ cwd: effectiveCwd,+ });// npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrap// (cmd.exe /c) instead of enabling a shell — shell:true + an args arraydiff --git a/server/lib/index.js b/server/lib/index.jsindex 34f93ddcfa..c173dfed8f 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -85,6 +85,7 @@ export * from './ansiStrip.js';// ANTIGRAVITY_CONFIGURED_DEFAULT, so a flat `export *` would trip the// barrel's duplicate-identifier collision check.export * as antigravity from './antigravity.js';+export * from './cliChildEnv.js';export * from './cliProviderArgs.js';export * from './cliProviderRun.js';export * from './codexAssistantExtract.js';diff --git a/server/lib/spawnCwd.test.js b/server/lib/spawnCwd.test.jsindex f153a633ee..2b3443245a 100644--- a/server/lib/spawnCwd.test.js+++ b/server/lib/spawnCwd.test.js@@ -323,9 +323,13 @@ describe('every cwd-passing spawn pins PWD', () => {// Count pins rather than merely asserting one exists: a file that already// pins its first spawn would otherwise pass forever, even after a second,// unpinned cwd-spawn is added to it.+ // Two markers count as a pin: the low-level helper, and buildCliChildEnv —+ // the shared AI-CLI env composer, which calls withSpawnCwdEnv internally+ // (#3194). Counting the composer here is what lets the five AI-CLI spawn+ // sites collapse to one call each without going dark to this guard.const pins = INLINE_PIN.has(rel)? (src.match(/childEnv\.PWD\s*=/g) || []).length- : (src.match(/withSpawnCwdEnv\(/g) || []).length;+ : (src.match(/(?:withSpawnCwdEnv|buildCliChildEnv)\(/g) || []).length;if (pins < sites) unpinned.push(`${rel} (${sites} cwd-passing spawn(s), ${pins} pin(s))`);}expect(diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex e20b98977e..ad42ecab0b 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -57,8 +57,7 @@ import {buildTuiInvocation,detectMissingTuiBinary,} from './tuiHandshake.js';-import { buildOpencodeEnvVars } from './opencodeConfig.js';-import { withSpawnCwdEnv } from './spawnCwd.js';+import { buildCliChildEnv } from './cliChildEnv.js';// One-shot defaults that don't apply to the long-running agent path:// - hard run cap (5 min vs unbounded for agents)@@ -171,20 +170,18 @@ ${prompt}`;// unstripped) is counted the same way the stripped post-paste buffer is.const promptMarkerCount = countPasteMarkers(stripAnsi(wrappedPrompt));- // CLAUDECODE is set when PortOS itself runs inside Claude Code; passing it- // through to a spawned Claude Code TUI would make the child think it's- // nested. Other AI spawn paths (runner.js, agentCliSpawning.js) strip it- // for the same reason.- // For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with- // the models map so --model is accepted (the static env var lacked this).- // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). This PTY runs the- // CLI directly, so there is no login shell to rewrite PWD for us.- const opencodeEnv = buildOpencodeEnvVars(provider, provider.defaultModel);- const childEnv = withSpawnCwdEnv(- { ...process.env, ...(provider.envVars || {}), ...opencodeEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor' },- workingDir,- );- delete childEnv.CLAUDECODE;+ // Shared composition (provider.envVars + OpenCode models map + PWD pin ++ // CLAUDECODE strip) — see buildCliChildEnv. The PWD pin matters here because+ // this PTY runs the CLI directly, so there is no login shell to rewrite PWD+ // for us. TERM/COLORTERM go in `extra` so they override any provider setting —+ // the PTY is always a truecolor xterm regardless of provider config. No+ // `guard`: this is a Run Prompt TUI, not an autonomous agent.+ const childEnv = buildCliChildEnv({+ provider,+ model: provider.defaultModel,+ cwd: workingDir,+ extra: { TERM: 'xterm-256color', COLORTERM: 'truecolor' },+ });let ptyProcess;try {diff --git a/server/lib/tuiUsageScrape.js b/server/lib/tuiUsageScrape.jsindex 0f5512875c..1c3114bac7 100644--- a/server/lib/tuiUsageScrape.js+++ b/server/lib/tuiUsageScrape.js@@ -4,7 +4,7 @@ import { tmpdir } from 'os';import { join } from 'path';import { stripAnsi } from './ansiStrip.js';import { sleep } from './fileUtils.js';-import { withSpawnCwdEnv } from './spawnCwd.js';+import { buildCliChildEnv } from './cliChildEnv.js';/*** Drive an interactive coding-agent TUI (Antigravity `agy`, Grok Build `grok`)@@ -96,16 +96,18 @@ export async function scrapeTuiUsage({mkdirSync(sandboxDir, { recursive: true });- // Provider envVars (auth/config) merged over process.env, then the PTY hints.- // CLAUDECODE leaks when PortOS itself runs under Claude Code; strip it so a- // spawned TUI doesn't think it's nested (mirrors tuiPromptRunner.js).- // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). Keeps the scrape in- // the throwaway sandbox instead of opening the PortOS checkout as a project.- const env = withSpawnCwdEnv(- { ...process.env, ...extraEnv, TERM: 'xterm-256color', COLORTERM: 'truecolor' },- sandboxDir,- );- delete env.CLAUDECODE;+ // Shared composition (provider envVars + PWD pin + CLAUDECODE strip) — see+ // buildCliChildEnv. `extraEnv` is the provider's auth/config env, handed in+ // loose rather than as a provider record; with no command to classify, the+ // OpenCode layer is a no-op here. TERM/COLORTERM go in `extra` so the PTY is+ // always a truecolor xterm regardless of provider config (mirrors+ // tuiPromptRunner.js). The PWD pin keeps the scrape in the throwaway sandbox+ // instead of opening the PortOS checkout as a project.+ const env = buildCliChildEnv({+ provider: { envVars: extraEnv },+ cwd: sandboxDir,+ extra: { TERM: 'xterm-256color', COLORTERM: 'truecolor' },+ });let pty;try {diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 84f306f940..092b32d43e 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -30,11 +30,9 @@ import { prepareCliPrompt } from '../lib/cliProviderArgs.js';import { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';import { isKimiCommand, ensureKimiHeadlessArgs } from '../lib/kimi.js';import { resolveCliModel, buildEffortArgs, buildCodexStartupArgs, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';-import { agentGuardEnv } from '../lib/agentGuard/index.js';import { resolveForgeTokenEnv } from './git.js';-import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';-import { withSpawnCwdEnv } from '../lib/spawnCwd.js';+import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { resolvePrCompletion } from '../lib/prDisposition.js';const AGENTS_DIR = PATHS.cosAgents;@@ -483,17 +481,19 @@ export async function spawnDirectly({providerSuppliesGithubToken(provider) ? Promise.resolve({}) : resolveForgeTokenEnv(cwd),]);- // For OpenCode Ollama providers, build dynamic OPENCODE_CONFIG_CONTENT with- // the models map so --model is accepted (the static env var lacked this).- const opencodeEnv = buildOpencodeEnvVars(provider, model);-- // The pm2 shim must be prepended onto the FINAL PATH (after any- // provider.envVars override) so a `--dangerously-skip-permissions` agent- // can't `pm2 kill` the shared daemon. opencodeEnv comes LAST to override- // the static OPENCODE_CONFIG_CONTENT in provider.envVars; forgeTokenEnv sits- // before provider.envVars so an explicit provider GH_TOKEN override still wins.- // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193).- const childEnv = (() => { const e = withSpawnCwdEnv({ ...process.env, ...forgeTokenEnv, ...claudeSettingsEnv, ...provider.envVars, ...opencodeEnv }, cwd); delete e.CLAUDECODE; Object.assign(e, agentGuardEnv(e)); return e; })();+ // Shared composition (provider.envVars + OpenCode models map + PWD pin ++ // CLAUDECODE strip) — see buildCliChildEnv. forgeTokenEnv/claudeSettingsEnv go+ // in `before` so they sit UNDER provider.envVars and an explicit provider+ // GH_TOKEN override still wins. `guard: true` prepends the pm2 shim onto the+ // final PATH so a `--dangerously-skip-permissions` agent can't `pm2 kill` the+ // shared daemon.+ const childEnv = buildCliChildEnv({+ before: { ...forgeTokenEnv, ...claudeSettingsEnv },+ provider,+ model,+ cwd,+ guard: true,+ });// Resolve a bare npm-installed CLI (a .cmd/.bat shim on Windows) to its real// path and wrap a shim as `cmd.exe /c <path>` so spawn() under shell:falsediff --git a/server/services/askService.js b/server/services/askService.jsindex 9bbc207c10..45faa46e0d 100644--- a/server/services/askService.js+++ b/server/services/askService.js@@ -36,6 +36,7 @@ import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antimport { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';import { prepareCliPrompt } from '../lib/cliProviderArgs.js';import { prepareCliSpawn } from '../lib/bufferedSpawn.js';+import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';import { evaluateSecretEndpoint } from '../lib/aiToolkit/internal/endpointGuard.js';@@ -603,7 +604,14 @@ async function* streamCompletion(provider, model, prompt, signal) {// --print VALUE (agy doesn't read stdin); grok's /dev/stdin sentinel via stdin// (POSIX) / temp file (Windows); everyone else via stdin (writePromptToStdin).const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(provider.command, args, prompt);- const childEnv = (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })();+ // Shared composition (provider.envVars + OpenCode models map + CLAUDECODE+ // strip) — see buildCliChildEnv. No cwd is passed to spawn below, so there is+ // no PWD to pin; no `guard` — Ask is a one-shot answer, not an agent. Routing+ // through the shared builder also brings the OpenCode declared-models map here+ // for the first time, so the `--model` this path injects above isn't rejected+ // by an Ollama-backed OpenCode provider (the #2190 fix, previously applied+ // only at the runner/agent sites).+ const childEnv = buildCliChildEnv({ provider, model: cliModel });// Resolve a bare npm-installed CLI (a .cmd/.bat shim on Windows) to its real// path and wrap it as `cmd.exe /c <path>` so spawn() under shell:false can// launch it — a bare shim name ENOENTs otherwise. No-op off Windows. Mirrorsdiff --git a/server/services/runner.js b/server/services/runner.jsindex 57f5829fb2..821b51b602 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -6,11 +6,10 @@ import { spawn } from 'child_process';import { writeFile, readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite, ensureDir, tryReadFile, PATHS } from '../lib/fileUtils.js';-import { resolveSpawnCwd, withSpawnCwdEnv } from '../lib/spawnCwd.js';+import { resolveSpawnCwd } from '../lib/spawnCwd.js';import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';-import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';-import { agentGuardEnv } from '../lib/agentGuard/index.js';+import { buildCliChildEnv } from '../lib/cliChildEnv.js';import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';import {@@ -261,18 +260,16 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, onconst { args, useStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(provider.command, builtArgs, prompt);console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via ${useStdin ? 'stdin' : 'argv'})`);- // Prepend the pm2 shim (agentGuardEnv) onto the final PATH so an unrestricted- // agent can't `pm2 kill` the shared daemon. See server/lib/agentGuard.- // buildOpencodeEnvVars rebuilds OPENCODE_CONFIG_CONTENT with a declared models- // map for OpenCode Ollama providers (empty/no-op otherwise) so the injected- // `--model ollama/<id>` isn't rejected as "not valid" — see issue-2190.- // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193).- const childEnv = withSpawnCwdEnv(- { ...process.env, ...provider.envVars, ...buildOpencodeEnvVars(provider, provider.defaultModel) },- effectiveCwd,- );- delete childEnv.CLAUDECODE;- Object.assign(childEnv, agentGuardEnv(childEnv));+ // Shared composition (provider.envVars + OpenCode models map + PWD pin ++ // CLAUDECODE strip) — see buildCliChildEnv. `guard: true` prepends the pm2+ // shim onto the final PATH so an unrestricted agent can't `pm2 kill` the+ // shared daemon.+ const childEnv = buildCliChildEnv({+ provider,+ model: provider.defaultModel,+ cwd: effectiveCwd,+ guard: true,+ });// See the executeCliRun docblock above for why this is a resolve+wrap, not// a shell:true. Resolved against `childEnv` (not bare process.env) so adiff --git a/server/services/visionCli.js b/server/services/visionCli.jsindex 7b1af653be..65850d8c15 100644--- a/server/services/visionCli.js+++ b/server/services/visionCli.js@@ -31,7 +31,7 @@ import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';import { resolveCliModel, isCodexProvider, buildCodexStartupArgs } from '../lib/providerModels.js';import { extractCodexAssistant, extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';-import { withSpawnCwdEnv } from '../lib/spawnCwd.js';+import { buildCliChildEnv } from '../lib/cliChildEnv.js';const CLI_VISION_TIMEOUT_MS = 120000;const IMAGE_BASENAME = 'vision-input.png';@@ -128,13 +128,18 @@ export async function describeImageViaCli({const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup } = prepareCliPrompt(command, args, stdin);cleanupPromptFile = cleanup;- // Pin PWD to the spawn cwd — see withSpawnCwdEnv (#3193). Load-bearing here:- // the non-codex branch above tells the CLI the image is "in the current- // directory", and the vision provider is user-configurable — so on OpenCode- // (which resolves its project root from PWD) a stale value both hides- // vision-input.png and turns the CLI loose in the PortOS checkout.- const childEnv = withSpawnCwdEnv({ ...process.env, ...provider?.envVars }, cwd);- delete childEnv.CLAUDECODE;+ // Shared composition (provider.envVars + OpenCode models map + PWD pin ++ // CLAUDECODE strip) — see buildCliChildEnv. The PWD pin is load-bearing+ // here: the non-codex branch above tells the CLI the image is "in the+ // current directory", and the vision provider is user-configurable — so on+ // OpenCode (which resolves its project root from PWD) a stale value both+ // hides vision-input.png and turns the CLI loose in the PortOS checkout.+ // Routing through the shared builder also brings the OpenCode declared-models+ // map here for the first time, so the `--model` buildCliVisionInvocation+ // injects isn't rejected by an Ollama-backed OpenCode provider (the #2190+ // fix, previously applied only at the runner/agent sites). No `guard` —+ // vision is a one-shot describe, not an agent.+ const childEnv = buildCliChildEnv({ provider, model: visionModel, cwd });// npm-installed CLI providers are .cmd/.bat shims on Windows; resolve+wrap// (cmd.exe /c) instead of enabling a shell. This matters even more here