Skip to content

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

address review (codex): scope provider auth and preserve delivery env

[._.]/ Adam Eivy0c1a2618ea97
diff --git a/server/lib/README.md b/server/lib/README.md
index 5def0a4a4a..e0da7d87ff 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -250,7 +250,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `githubRepoUrl.js` | `parseGitHubUrl(url)` → `{ owner, repo }` / `isGitHubRepoUrl(url)` — authoritative "is this a clonable GitHub repo URL?" rule, re-exported by `services/githubCloner.js`. Mirrored to `client/src/lib/githubRepoUrl.js` (parity pinned by `githubRepoUrl.mirror.test.js`) so the Brain capture boxes reveal the post-clone agent options for exactly the URLs the server will clone. |
| `glabArgs.js` | `GLAB_JSON_ARGS`, `withGlabJson(args)` — pure `glab` argv conventions. The JSON output flag is `--output json`, NOT `-F json`: on `glab issue list` (and only there) `-F` is `--output-format` (details/ids/urls), so `-F json` is accepted, ignored, and answers with the human table at exit 0. Shared by all three `glab` runners so the spelling has one definition; guarded tree-wide by `services/gitlab.glabFlags.test.js`. |
| `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. |
-| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; `buildSafeCliBaseEnv(env)` allowlists runtime essentials and provider auth before an AI CLI inherits the server environment. Route Node→Python and other background CLI spawns through the process helpers. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await; `findCommandOnPath(name, { env, cwd })` resolves an executable from the exact child environment without needing `which` itself on that PATH. |
+| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; `buildSafeCliBaseEnv(env, provider)` allowlists runtime/delivery essentials and only the selected CLI's ambient provider auth before an AI CLI inherits the server environment. Route Node→Python and other background CLI spawns through the process helpers. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await; `findCommandOnPath(name, { env, cwd })` resolves an executable from the exact child environment without needing `which` itself on that PATH. |
| `branchUpstreamGuard.js` | `enforceSafeBranchUpstream(repo, branch)` / `readBranchUpstream` / `isSafeBranchUpstream` — the agent-branch upstream invariant (#4172): a branch handed to a CoS agent tracks either NOTHING or its OWN ref, never `refs/heads/main`. `git worktree add -b <b> <path> origin/main` does not leave the branch untracked — `branch.autoSetupMerge` records `merge=refs/heads/main` — and `/do:pr` derives its push destination from that config (`git push <remote> HEAD:<merge>`), so the agent's work lands straight on the default branch with no PR. Prevention is `--no-track` at the `worktreeManager.js` creation sites; this is the backstop that also REPAIRS branches created before the fix (drops the bogus upstream, logs it) and throws only if the repair doesn't take. Fails CLOSED: `readBranchUpstream` returns `null` for could-not-read (distinct from `''` = genuinely unset), and an unverifiable upstream is refused rather than waved through — `worktreeManager.js` undoes the `worktree add` on refusal so the throw can't strand a tree. Pairs with `primaryCheckoutGuard.js`, which catches the other way agent work reaches `main`. |
| `primaryCheckoutGuard.js` | `capturePrimaryCheckoutState(path)` / `detectPrimaryCheckoutDrift(baseline, {agentBranch})` + `PRIMARY_CHECKOUT_MUTATED_REASON`/`_CATEGORY` — the branch-jack detector (#3680): stamps the PRIMARY checkout's branch + HEAD onto a worktree agent's metadata at spawn (`agentLifecycle.js`) and re-reads it in the shared finalize path (`agentFinalization.js`), so a worktree-isolated agent that commits to the primary is recorded as a FAILURE naming the drifted branch, the commit count, and the `git reset --hard` recovery — instead of a silent "completed". Detect-and-report only: the reset discards commits, so it stays a human decision. Non-throwing (runs outside the request lifecycle); an unreadable checkout reports no drift rather than inventing one. |
| `pythonSetup.js` | Python venv / runner setup helpers. |
diff --git a/server/lib/cliChildEnv.js b/server/lib/cliChildEnv.js
index 9334faf96b..58975f4c8d 100644
--- a/server/lib/cliChildEnv.js
+++ b/server/lib/cliChildEnv.js
@@ -162,7 +162,7 @@ export function buildCliChildEnv({
guard = false,
} = {}) {
const env = withSpawnCwdEnv(
- { ...buildSafeCliBaseEnv(baseEnv), ...composeProviderEnv({ before, provider, model, extra }) },
+ { ...buildSafeCliBaseEnv(baseEnv, provider), ...composeProviderEnv({ before, provider, model, extra }) },
cwd,
);
diff --git a/server/lib/processEnv.js b/server/lib/processEnv.js
index 3b91e45317..aee90df3a3 100644
--- a/server/lib/processEnv.js
+++ b/server/lib/processEnv.js
@@ -36,11 +36,11 @@ export function safeChildProcessOptions(options = {}) {
return { ...rest, env: stripDebugMallocEnv(env), windowsHide: true };
}
-// AI CLIs need the host's runtime essentials and provider authentication, but
-// they do not need the rest of the server's ambient environment. Keeping this
-// list here makes the boundary reusable by direct and durable agent spawns;
-// explicit provider.envVars / before overlays remain available for configured
-// credentials and per-run settings.
+// AI CLIs need the host's runtime essentials and forge-delivery fallbacks, but
+// they do not need the rest of the server's ambient environment. Provider
+// authentication is selected below per child provider; explicit provider.envVars
+// / before overlays remain available for configured credentials and per-run
+// settings.
const SAFE_CLI_BASE_ENV_KEYS = new Set([
'PATH', 'Path', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'PWD', 'TMPDIR', 'TMP', 'TEMP',
'LANG', 'LANGUAGE', 'TERM', 'COLORTERM', 'TZ', 'HOSTNAME', 'NODE', 'NODE_ENV', 'NODE_PATH',
@@ -48,30 +48,59 @@ const SAFE_CLI_BASE_ENV_KEYS = new Set([
'SSL_CERT_FILE', 'SSL_CERT_DIR', 'EDITOR', 'VISUAL', 'PORTOS_REAL_PM2',
'SystemRoot', 'SystemDrive', 'ComSpec', 'PATHEXT', 'USERPROFILE', 'APPDATA',
'LOCALAPPDATA', 'ProgramData', 'ProgramFiles', 'HOMEDRIVE', 'HOMEPATH',
- 'AWS_REGION', 'AWS_DEFAULT_REGION',
- 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',
- 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX',
- 'OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_API_BASE',
- 'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_GENAI_API_KEY',
- 'XAI_API_KEY', 'GROK_API_KEY', 'OPENROUTER_API_KEY',
- 'OLLAMA_HOST', 'OLLAMA_API_BASE', 'OPENCODE_CONFIG_CONTENT',
+ 'AWS_REGION', 'AWS_DEFAULT_REGION', 'SSH_AUTH_SOCK', 'GH_TOKEN', 'GITHUB_TOKEN',
]);
-const SAFE_CLI_BASE_ENV_PREFIXES = ['LC_', 'CLAUDE_CODE_', 'CLAUDE_', 'GEMINI_CLI_'];
+const SAFE_CLI_BASE_ENV_PREFIXES = ['LC_'];
+
+const CLI_PROVIDER_AUTH_RULES = Object.freeze({
+ claude: {
+ keys: ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX'],
+ prefixes: ['CLAUDE_CODE_', 'CLAUDE_'],
+ },
+ codex: { keys: ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_API_BASE'], prefixes: [] },
+ agy: { keys: ['GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GOOGLE_GENAI_API_KEY'], prefixes: ['GEMINI_CLI_'] },
+ grok: { keys: ['XAI_API_KEY', 'GROK_API_KEY'], prefixes: [] },
+ kimi: { keys: ['KIMI_API_KEY', 'MOONSHOT_API_KEY'], prefixes: [] },
+ cursor: { keys: ['CURSOR_API_KEY'], prefixes: [] },
+});
+
+const LOCAL_PROVIDER_MARKERS = ['ollamaBacked', 'mtplxBacked', 'llamaBacked', 'vllmBacked', 'sglangBacked'];
+
+function cliProviderAuthRule(provider) {
+ const command = typeof provider?.command === 'string'
+ ? provider.command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '')
+ : '';
+ const id = String(provider?.id || '').toLowerCase();
+ const local = LOCAL_PROVIDER_MARKERS.some((marker) => provider?.[marker] === true);
+ if (local) return null;
+ if (command === 'claude' || id.startsWith('claude-code')) return CLI_PROVIDER_AUTH_RULES.claude;
+ if (command === 'codex' || id === 'codex' || id === 'codex-tui') return CLI_PROVIDER_AUTH_RULES.codex;
+ if (command === 'agy' || command === 'antigravity' || id.startsWith('antigravity')) return CLI_PROVIDER_AUTH_RULES.agy;
+ if (command === 'grok' || id.startsWith('grok-')) return CLI_PROVIDER_AUTH_RULES.grok;
+ if (command === 'kimi' || id.startsWith('kimi-')) return CLI_PROVIDER_AUTH_RULES.kimi;
+ if (command === 'cursor-agent' || id.startsWith('cursor-')) return CLI_PROVIDER_AUTH_RULES.cursor;
+ return null;
+}
/**
- * Keep only the environment an AI CLI needs to start and authenticate.
- * Provider-specific values should be supplied through the explicit overlays,
- * not inherited from the PortOS server process.
+ * Keep only the environment an AI CLI needs to start, deliver work, and use
+ * the selected provider's ambient auth. Unrelated provider credentials are
+ * dropped; provider-specific values should otherwise be supplied through the
+ * explicit overlays, not inherited from the PortOS server process.
*
* @param {NodeJS.ProcessEnv|object} [env=process.env]
+ * @param {{id?:string, command?:string, ollamaBacked?:boolean, mtplxBacked?:boolean, llamaBacked?:boolean, vllmBacked?:boolean, sglangBacked?:boolean}|null} [provider]
* @returns {Record<string,string>}
*/
-export function buildSafeCliBaseEnv(env = process.env) {
+export function buildSafeCliBaseEnv(env = process.env, provider = null) {
+ const authRule = cliProviderAuthRule(provider);
return Object.fromEntries(
Object.entries(env || {}).filter(([key, value]) => value != null && (
SAFE_CLI_BASE_ENV_KEYS.has(key)
|| SAFE_CLI_BASE_ENV_PREFIXES.some((prefix) => key.startsWith(prefix))
+ || authRule?.keys.includes(key)
+ || authRule?.prefixes.some((prefix) => key.startsWith(prefix))
)),
);
}
diff --git a/server/lib/processEnv.test.js b/server/lib/processEnv.test.js
index 909a00a345..81201df663 100644
--- a/server/lib/processEnv.test.js
+++ b/server/lib/processEnv.test.js
@@ -70,7 +70,10 @@ describe('buildSafeCliBaseEnv', () => {
PATH: '/usr/bin',
HOME: '/home/example',
CODEX_HOME: '/tmp/example-codex',
- ANTHROPIC_API_KEY: 'provider-key',
+ SSH_AUTH_SOCK: '/tmp/example-agent.sock',
+ GH_TOKEN: 'owner-token',
+ GITHUB_TOKEN: 'owner-token-alias',
+ ANTHROPIC_API_KEY: 'unselected-provider-key',
PRIVATE_APP_AUTH_KEYS: 'sidecar-secret',
PRIVATE_APP_TOKEN: 'sidecar-token',
});
@@ -79,10 +82,26 @@ describe('buildSafeCliBaseEnv', () => {
PATH: '/usr/bin',
HOME: '/home/example',
CODEX_HOME: '/tmp/example-codex',
- ANTHROPIC_API_KEY: 'provider-key',
+ SSH_AUTH_SOCK: '/tmp/example-agent.sock',
+ GH_TOKEN: 'owner-token',
+ GITHUB_TOKEN: 'owner-token-alias',
});
});
+ it('keeps only the selected provider auth and drops paid keys for local providers', () => {
+ const source = {
+ ANTHROPIC_API_KEY: 'claude-key',
+ CLAUDE_CODE_OAUTH_TOKEN: 'claude-oauth',
+ OPENAI_API_KEY: 'openai-key',
+ };
+
+ expect(buildSafeCliBaseEnv(source, { id: 'claude-code', command: 'claude' })).toEqual({
+ ANTHROPIC_API_KEY: 'claude-key',
+ CLAUDE_CODE_OAUTH_TOKEN: 'claude-oauth',
+ });
+ expect(buildSafeCliBaseEnv(source, { id: 'opencode-ollama', command: 'opencode', ollamaBacked: true })).toEqual({});
+ });
+
it('does not mutate the source environment', () => {
const source = { PATH: '/usr/bin', PRIVATE_APP_AUTH_KEYS: 'sidecar-secret' };
buildSafeCliBaseEnv(source);