From 7a7ab7149527c4bf6bffcc225e2b589c89bf3473 Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 15:43:51 -0800 Subject: [PATCH 1/4] docs(proxy): plan fail-open Claude and Codex proxy resilience --- docs/plans/2026-11-27-proxy-resilience.md | 59 +++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 docs/plans/2026-11-27-proxy-resilience.md diff --git a/docs/plans/2026-11-27-proxy-resilience.md b/docs/plans/2026-11-27-proxy-resilience.md new file mode 100644 index 000000000..925d96967 --- /dev/null +++ b/docs/plans/2026-11-27-proxy-resilience.md @@ -0,0 +1,59 @@ +# Plan: Bulletproof Claude & Codex Proxy Resilience + +Fixes #1552 + +## Problem + +Agent Code optionally routes Claude (via per-session `mitmdump`) and Codex (via local `ResponsesProxy`) through local proxies to obtain richer semantic streaming events. Today both proxy paths fail closed or misconfigure user environments in common real-world setups: + +1. **Claude (`ClaudeSession`)** + - Unconditionally spawns `mitmdump` when `useProxy: true` even when the user's environment is incompatible (corporate `HTTPS_PROXY`/`HTTP_PROXY`, non-Anthropic cloud backends like Bedrock/Vertex/Foundry, or a local/plain-HTTP `ANTHROPIC_BASE_URL`). + - Overwrites user `NO_PROXY`/`no_proxy` instead of merging loopback hosts, breaking internal/corporate bypass lists. + - Overwrites user `NODE_EXTRA_CA_CERTS` instead of merging the user's CA bundle with the mitmproxy CA cert, breaking corporate TLS roots. + - Fails closed if `resolveBundledTool('mitmdump')`, `createProxyServer`, or `proxy.start()` throws, aborting Claude spawn instead of degrading to direct spawn. +2. **Codex (`CodexSession`)** + - Unconditionally starts `ResponsesProxy` when `useProxy: true` even when a corporate proxy env var is set (Node's `fetch()` in `ResponsesProxy` ignores `HTTPS_PROXY`), when `$CODEX_HOME/config.toml` sets a non-`openai` `model_provider`, or when auth mode cannot be determined (e.g. macOS Keychain / `keyring` / `auto` store or not-yet-logged-in user, where guessing `api.openai.com` causes 401s). + - Does not honor `openai_base_url` from `$CODEX_HOME/config.toml` or `OPENAI_BASE_URL` when forwarding upstream, nor preserve/merge `NO_PROXY`/`no_proxy` with loopback hosts. + - Fails closed if `allocateProxyEventsFile` or `ResponsesProxy.create` throws, aborting Codex spawn instead of spawning directly. +3. **Terminal-mode panes (`session.ts` & `rehydrate.ts`)** + - Passes `useProxy: true` even when the pane's effective view mode (`meta?.agentViewModeOverride ?? settings.agentViewMode`) is hard `'terminal'`, spinning up unnecessary proxy processes for raw-PTY panes. + +## Scope & Design + +All changes live in the main `agent-code` repository (`src/`) so this lands as a single PR without modifying git submodules. + +### 1. Shared proxy environment hygiene (`src/providers/shared/runtime/proxyEnv.ts`) +- `hasCorporateProxyEnv(env)` — detects non-empty `HTTPS_PROXY`, `https_proxy`, `HTTP_PROXY`, or `http_proxy`. +- `mergeNoProxy(env, requiredHosts)` — merges `localhost,127.0.0.1,::1` into any existing `NO_PROXY` / `no_proxy` entries without duplicates or clobbering. + +### 2. Claude fail-open & env hygiene (`src/providers/claude/runtime/claudeProxyPolicy.ts`, `claudeSession.ts`) +- `evaluateClaudeProxyCompatibility(cleanEnv)` skips local mitmproxy when: + - corporate proxy env vars are set; + - `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, or `CLAUDE_CODE_USE_FOUNDRY` is truthy; + - `ANTHROPIC_BASE_URL` uses `http://` or targets loopback (`localhost`, `127.0.0.1`, `::1`, `[::1]`, `*.localhost`). +- `buildClaudeProxyEnv(cleanEnv, proxyInfo)` merges `NO_PROXY`/`no_proxy` and, when `cleanEnv.NODE_EXTRA_CA_CERTS` is set, combines it with `proxyInfo.caCertPath` into `combined-extra-ca-certs.pem` inside `proxyInfo.workDir` (throwing on unreadable/unwritable paths so the fail-open wrapper falls back cleanly). +- `ClaudeSession.start()` wraps proxy resolution, creation, startup, and env construction in `try/catch`; on any failure it tears down any started proxy, logs a warning, emits a non-fatal `transcript-diagnostic`, sets `effectiveUseProxy = false`, and spawns Claude directly without the proxy. + +### 3. Codex fail-open & config/auth/env hygiene (`src/providers/codex/runtime/codexProxyPolicy.ts`, `codexSession.ts`) +- `resolveCodexProxyDecision(cleanEnv)` inspects `cleanEnv`, `$CODEX_HOME/config.toml` (parsed via `@iarna/toml`), and `$CODEX_HOME/auth.json` before starting `ResponsesProxy`: + - Skips if corporate proxy env vars are set. + - Skips if `config.toml` sets `model_provider` to anything other than `"openai"` (or if `config.toml` cannot be parsed). + - Uses `config.toml`'s `openai_base_url` or `cleanEnv.OPENAI_BASE_URL` as `upstreamBaseUrl` when present. + - Otherwise inspects `$CODEX_HOME/auth.json`: + - ChatGPT-family `auth_mode` (`chatgpt`, `chatgptAuthTokens`, `headers`, `agentIdentity`, `personalAccessToken`) or `tokens` without `OPENAI_API_KEY` → `authMode: 'chatgpt'`. + - `auth_mode === 'apikey'` or `OPENAI_API_KEY` present in `auth.json` or `cleanEnv` → `authMode: 'apikey'`. + - Otherwise (missing/indeterminate auth, e.g., Keychain/keyring or not logged in) → skip proxy. +- When `ResponsesProxy` is used, merges `localhost,127.0.0.1,::1` into `cleanEnv.NO_PROXY` and `cleanEnv.no_proxy`. +- Wraps `resolveCodexProxyDecision`, `allocateProxyEventsFile`, and `ResponsesProxy.create` in `try/catch`; on any failure logs a warning, emits a non-fatal `transcript-diagnostic`, leaves `this.proxyServer = null`, omits `--config openai_base_url=...`, and spawns Codex directly. + +### 4. Skip proxy for Terminal-mode panes (`agentDisplayMode.ts`, `session.ts`, `rehydrate.ts`) +- Add `shouldUseProxyForSession({ kind, useProxyStreaming, globalMode, override })` in `src/renderer/src/workspace/agentDisplayMode.ts`: returns `false` when `resolveConfiguredAgentViewMode(globalMode, override) === 'terminal'`. +- Wire it into `spawn`, `ensureSessionLive`, `reloadAgentSessions` in `src/renderer/src/workspace/hook/actions/session.ts` and `rehydrateWorkspace` in `src/renderer/src/workspace/hook/persistence/rehydrate.ts`. + +### 5. Verification +- Fail-first unit tests for: + - `proxyEnv.ts` (`hasCorporateProxyEnv`, `mergeNoProxy`) + - `claudeProxyPolicy.ts` (env compatibility, CA cert merging, unreadable CA fallback) and `ClaudeSession` fail-open direct spawn + - `codexProxyPolicy.ts` (corporate proxy, `config.toml` `model_provider` & `openai_base_url`, `OPENAI_BASE_URL`, `auth.json` modes, indeterminate auth skip) and `CodexSession` fail-open direct spawn + - `shouldUseProxyForSession` and terminal-mode proxy suppression in renderer session actions / rehydrate +- `npm run typecheck` and targeted vitest suites. From bdce46333fadddd1f11ea8f14e3056300c1b464c Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 15:47:45 -0800 Subject: [PATCH 2/4] fix(proxy): make Claude and Codex proxies fail-open with env and config hygiene Skip local proxies in incompatible corporate/cloud/custom-provider/indeterminate-auth environments, preserve user NO_PROXY and NODE_EXTRA_CA_CERTS, and fall back to direct spawn on any proxy startup failure instead of aborting session launch. Refs #1552 --- .../claude/runtime/claudeProxyPolicy.test.ts | 306 ++++++++++++++++++ .../claude/runtime/claudeProxyPolicy.ts | 147 +++++++++ src/providers/claude/runtime/claudeSession.ts | 265 +++++++-------- .../codex/runtime/codexProxyPolicy.test.ts | 276 ++++++++++++++++ .../codex/runtime/codexProxyPolicy.ts | 161 +++++++++ src/providers/codex/runtime/codexSession.ts | 118 ++++--- src/providers/shared/runtime/proxyEnv.ts | 76 +++++ 7 files changed, 1148 insertions(+), 201 deletions(-) create mode 100644 src/providers/claude/runtime/claudeProxyPolicy.test.ts create mode 100644 src/providers/claude/runtime/claudeProxyPolicy.ts create mode 100644 src/providers/codex/runtime/codexProxyPolicy.test.ts create mode 100644 src/providers/codex/runtime/codexProxyPolicy.ts create mode 100644 src/providers/shared/runtime/proxyEnv.ts diff --git a/src/providers/claude/runtime/claudeProxyPolicy.test.ts b/src/providers/claude/runtime/claudeProxyPolicy.test.ts new file mode 100644 index 000000000..834727b77 --- /dev/null +++ b/src/providers/claude/runtime/claudeProxyPolicy.test.ts @@ -0,0 +1,306 @@ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { hasCorporateProxyEnv, mergeNoProxy } from '@providers/shared/runtime/proxyEnv.js' +import { + buildClaudeProxyEnv, + evaluateClaudeProxyCompatibility, +} from './claudeProxyPolicy.js' +import { ClaudeSession } from './claudeSession.js' + +const harness = vi.hoisted(() => ({ + ptySpawns: [] as Array<{ binary: string; args: string[]; env: Record }>, + headlessOptions: [] as Array>, + proxyCreateCalls: 0, + proxyCreateBehavior: 'ok' as 'ok' | 'throw-create' | 'throw-start', + proxyStopped: 0, + proxyWorkDir: '', + proxyCaCertPath: '', +})) + +vi.mock('node-pty', () => ({ + spawn: (binary: string, args: string[], opts: { env: Record }) => { + harness.ptySpawns.push({ binary, args, env: { ...opts.env } }) + return { + pid: 4242, + process: binary, + write: () => undefined, + resize: () => undefined, + kill: () => undefined, + onData: () => ({ dispose: () => undefined }), + onExit: () => ({ dispose: () => undefined }), + } + }, +})) + +vi.mock('@main/setup/runtimeTools.js', () => ({ + resolveBundledTool: async () => '/fake/mitmdump', +})) + +vi.mock('@main/setup/toolchain.js', () => ({ + getToolPath: () => null, +})) + +vi.mock('@main/proxy/mitmproxyReaper.js', () => ({ + MITMPROXY_SHARED_CONF_DIR: '/fake/mitmproxy-conf', + stopProxyServerWithDeadline: async (proxy: { stop: () => Promise }) => { + await proxy.stop() + return { outcome: 'stopped', processes: [] } + }, +})) + +vi.mock('claude-code-headless', async () => { + const { EventEmitter } = await import('node:events') + const { join: pathJoin } = await import('node:path') + class FakeClaudeCodeHeadless extends EventEmitter { + semantic = new EventEmitter() + committed = new EventEmitter() + + constructor(options: Record) { + super() + harness.headlessOptions.push(options) + } + + async start() { + return { projectDir: '/fake/project-dir' } + } + async stop() {} + getSlashPickerState() { return { visible: false, items: [] } } + getConditionSnapshot() { return { provider: 'claude', conditions: {}, ts: 0 } } + getComposerState() { return { kind: 'empty' } } + getScreen() { return '' } + getScreenMarkdown() { return '' } + getComposerAttributes() { return null } + ingestProxyEvent() {} + noteProxyTransportGap() {} + } + + return { + ClaudeCodeHeadless: FakeClaudeCodeHeadless, + createProxyServer: async () => { + harness.proxyCreateCalls += 1 + if (harness.proxyCreateBehavior === 'throw-create') { + throw new Error('mitmdump binary missing') + } + const emitter = new EventEmitter() + return Object.assign(emitter, { + info: { + workDir: harness.proxyWorkDir, + confDir: '/fake/mitmproxy-conf', + mitmDumpPath: '/fake/mitmdump', + proxyPort: 18080, + proxyUrl: 'http://127.0.0.1:18080', + addonPath: '/fake/addon.py', + eventsFile: pathJoin(harness.proxyWorkDir, 'proxy-events.jsonl'), + caCertPath: harness.proxyCaCertPath, + }, + start: async () => { + if (harness.proxyCreateBehavior === 'throw-start') { + throw new Error('mitmdump failed to bind port') + } + }, + stop: async () => { + harness.proxyStopped += 1 + }, + }) + }, + } +}) + +describe('shared proxy env hygiene', () => { + it('detects corporate proxy env vars across upper and lower case', () => { + expect(hasCorporateProxyEnv({})).toBe(false) + expect(hasCorporateProxyEnv({ HTTPS_PROXY: ' ' })).toBe(false) + expect(hasCorporateProxyEnv({ HTTPS_PROXY: 'http://corp:8080' })).toBe(true) + expect(hasCorporateProxyEnv({ https_proxy: 'http://corp:8080' })).toBe(true) + expect(hasCorporateProxyEnv({ HTTP_PROXY: 'http://corp:8080' })).toBe(true) + expect(hasCorporateProxyEnv({ http_proxy: 'http://corp:8080' })).toBe(true) + }) + + it('merges loopback hosts into existing NO_PROXY and no_proxy without clobbering or duplicating', () => { + expect(mergeNoProxy({})).toBe('localhost,127.0.0.1,::1') + expect( + mergeNoProxy({ + NO_PROXY: 'internal.corp, 10.0.0.0/8, LOCALHOST', + no_proxy: 'internal.corp, .svc.local', + }), + ).toBe('internal.corp,10.0.0.0/8,LOCALHOST,.svc.local,127.0.0.1,::1') + }) +}) + +describe('evaluateClaudeProxyCompatibility', () => { + it('allows default clean environments', () => { + expect(evaluateClaudeProxyCompatibility({ PATH: '/usr/bin' })).toEqual({ allow: true }) + }) + + it.each(['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'])( + 'skips proxy when %s is set', + key => { + const decision = evaluateClaudeProxyCompatibility({ [key]: 'http://proxy.corp:8080' }) + expect(decision.allow).toBe(false) + if (!decision.allow) expect(decision.reason).toBe('corporate-proxy-env') + }, + ) + + it.each(['CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY'])( + 'skips proxy when %s is truthy and allows when explicitly falsy', + key => { + const truthy = evaluateClaudeProxyCompatibility({ [key]: '1' }) + expect(truthy.allow).toBe(false) + if (!truthy.allow) expect(truthy.reason).toBe('non-anthropic-backend') + + expect(evaluateClaudeProxyCompatibility({ [key]: '0' })).toEqual({ allow: true }) + expect(evaluateClaudeProxyCompatibility({ [key]: 'false' })).toEqual({ allow: true }) + }, + ) + + it('skips proxy for plain-HTTP or loopback ANTHROPIC_BASE_URL', () => { + for (const url of [ + 'http://litellm.internal:4000', + 'https://localhost:8443/v1', + 'https://127.0.0.1:8443', + 'https://[::1]:8443', + ]) { + const decision = evaluateClaudeProxyCompatibility({ ANTHROPIC_BASE_URL: url }) + expect(decision.allow).toBe(false) + if (!decision.allow) expect(decision.reason).toBe('local-or-http-base-url') + } + expect( + evaluateClaudeProxyCompatibility({ ANTHROPIC_BASE_URL: 'https://api.anthropic.com' }), + ).toEqual({ allow: true }) + }) +}) + +describe('buildClaudeProxyEnv', () => { + let tempDir: string + + beforeEach(async () => { + tempDir = await mkdtemp(join(tmpdir(), 'claude-proxy-env-')) + }) + + afterEach(async () => { + await rm(tempDir, { recursive: true, force: true }) + }) + + it('merges user NODE_EXTRA_CA_CERTS with mitmproxy CA into workDir and preserves NO_PROXY', async () => { + const userCa = join(tempDir, 'corp-ca.pem') + const mitmCa = join(tempDir, 'mitm-ca.pem') + await writeFile(userCa, '-----BEGIN CERTIFICATE-----\nCORP\n-----END CERTIFICATE-----', 'utf8') + await writeFile(mitmCa, '-----BEGIN CERTIFICATE-----\nMITM\n-----END CERTIFICATE-----\n', 'utf8') + + const env = await buildClaudeProxyEnv( + { + NO_PROXY: 'corp.local', + NODE_EXTRA_CA_CERTS: userCa, + }, + { + proxyUrl: 'http://127.0.0.1:18080', + caCertPath: mitmCa, + workDir: tempDir, + }, + ) + + expect(env.NO_PROXY).toBe('corp.local,localhost,127.0.0.1,::1') + expect(env.no_proxy).toBe('corp.local,localhost,127.0.0.1,::1') + expect(env.NODE_EXTRA_CA_CERTS).toBe(join(tempDir, 'combined-extra-ca-certs.pem')) + const merged = await readFile(env.NODE_EXTRA_CA_CERTS, 'utf8') + expect(merged).toContain('CORP') + expect(merged).toContain('MITM') + }) + + it('throws when user NODE_EXTRA_CA_CERTS is unreadable so caller can fail open', async () => { + const mitmCa = join(tempDir, 'mitm-ca.pem') + await writeFile(mitmCa, '-----BEGIN CERTIFICATE-----\nMITM\n-----END CERTIFICATE-----\n', 'utf8') + + await expect( + buildClaudeProxyEnv( + { NODE_EXTRA_CA_CERTS: join(tempDir, 'does-not-exist.pem') }, + { proxyUrl: 'http://127.0.0.1:18080', caCertPath: mitmCa, workDir: tempDir }, + ), + ).rejects.toThrow() + }) +}) + +describe('ClaudeSession proxy fail-open', () => { + let tempDir: string + + beforeEach(async () => { + tempDir = await mkdtemp(join(tmpdir(), 'claude-session-proxy-')) + harness.ptySpawns = [] + harness.headlessOptions = [] + harness.proxyCreateCalls = 0 + harness.proxyCreateBehavior = 'ok' + harness.proxyStopped = 0 + harness.proxyWorkDir = tempDir + harness.proxyCaCertPath = join(tempDir, 'mitm-ca.pem') + await writeFile(harness.proxyCaCertPath, '-----BEGIN CERTIFICATE-----\nMITM\n-----END CERTIFICATE-----\n', 'utf8') + }) + + afterEach(async () => { + await rm(tempDir, { recursive: true, force: true }) + }) + + it('falls back to direct spawn without aborting when proxy.start() throws', async () => { + harness.proxyCreateBehavior = 'throw-start' + const session = new ClaudeSession({ + cwd: tempDir, + useProxy: true, + env: { HTTPS_PROXY: undefined, https_proxy: undefined, HTTP_PROXY: undefined, http_proxy: undefined }, + }) + const diagnostics: unknown[] = [] + const started: Array<{ projectDir: string; proxyUrl?: string }> = [] + session.on('transcript-diagnostic', d => diagnostics.push(d)) + session.on('started', s => started.push(s)) + + await session.start() + + expect(harness.proxyCreateCalls).toBe(1) + expect(harness.proxyStopped).toBe(1) + expect(harness.ptySpawns).toHaveLength(1) + expect(harness.ptySpawns[0].env.HTTPS_PROXY).toBeUndefined() + expect(harness.headlessOptions[0].proxy).toBeUndefined() + expect(started).toEqual([{ projectDir: '/fake/project-dir', proxyUrl: undefined }]) + expect(diagnostics.length).toBeGreaterThan(0) + }) + + it('tears down proxy and falls back to direct spawn when user NODE_EXTRA_CA_CERTS is unreadable', async () => { + const session = new ClaudeSession({ + cwd: tempDir, + useProxy: true, + env: { + HTTPS_PROXY: undefined, + https_proxy: undefined, + HTTP_PROXY: undefined, + http_proxy: undefined, + NODE_EXTRA_CA_CERTS: join(tempDir, 'missing.pem'), + }, + }) + + await session.start() + + expect(harness.proxyCreateCalls).toBe(1) + expect(harness.proxyStopped).toBe(1) + expect(harness.ptySpawns).toHaveLength(1) + expect(harness.ptySpawns[0].env.HTTPS_PROXY).toBeUndefined() + expect(harness.ptySpawns[0].env.NODE_EXTRA_CA_CERTS).toBe(join(tempDir, 'missing.pem')) + expect(harness.headlessOptions[0].proxy).toBeUndefined() + }) + + it('skips creating mitmproxy altogether when corporate HTTPS_PROXY is already set', async () => { + const session = new ClaudeSession({ + cwd: tempDir, + useProxy: true, + env: { HTTPS_PROXY: 'http://corp-proxy:8080' }, + }) + + await session.start() + + expect(harness.proxyCreateCalls).toBe(0) + expect(harness.ptySpawns).toHaveLength(1) + expect(harness.ptySpawns[0].env.HTTPS_PROXY).toBe('http://corp-proxy:8080') + expect(harness.headlessOptions[0].proxy).toBeUndefined() + }) +}) diff --git a/src/providers/claude/runtime/claudeProxyPolicy.ts b/src/providers/claude/runtime/claudeProxyPolicy.ts new file mode 100644 index 000000000..a1e9f5c0b --- /dev/null +++ b/src/providers/claude/runtime/claudeProxyPolicy.ts @@ -0,0 +1,147 @@ +import { readFile, writeFile } from 'node:fs/promises' +import { join } from 'node:path' + +import { hasCorporateProxyEnv, mergeNoProxy } from '@providers/shared/runtime/proxyEnv.js' + +/** + * Compatibility and environment-hygiene policy for Claude's local mitmproxy + * (#1552). + * + * WHY this policy is evaluated BEFORE spawning mitmdump: + * Agent Code's mitmproxy is purely an observational enhancement for semantic + * streaming; Claude Code works completely fine without it (screen-driven + + * JSONL semantics). Spawning mitmdump in environments where it cannot + * safely intercept Anthropic traffic — corporate proxies, Bedrock/Vertex/ + * Foundry cloud backends, or local/plain-HTTP gateways — either breaks + * outbound connectivity outright or wastes a subprocess for zero captured + * events. Detecting those setups up front lets ClaudeSession skip the proxy + * cleanly and spawn Claude directly. + */ + +export type ClaudeProxyCompatibilityDecision = + | { allow: true } + | { + allow: false + reason: 'corporate-proxy-env' | 'non-anthropic-backend' | 'local-or-http-base-url' + detail: string + } + +const NON_ANTHROPIC_BACKEND_FLAGS = [ + 'CLAUDE_CODE_USE_BEDROCK', + 'CLAUDE_CODE_USE_VERTEX', + 'CLAUDE_CODE_USE_FOUNDRY', +] as const + +const FALSY_ENV_VALUES = new Set(['', '0', 'false', 'no', 'off']) + +function isTruthyEnvFlag(value: string | undefined): boolean { + if (typeof value !== 'string') return false + return !FALSY_ENV_VALUES.has(value.trim().toLowerCase()) +} + +function isLocalOrPlainHttpBaseUrl(rawUrl: string): boolean { + const trimmed = rawUrl.trim() + if (!trimmed) return false + try { + const parsed = new URL(trimmed) + if (parsed.protocol === 'http:') return true + const host = parsed.hostname.toLowerCase() + if ( + host === 'localhost' || + host === '127.0.0.1' || + host === '::1' || + host === '[::1]' || + host.endsWith('.localhost') + ) { + return true + } + return false + } catch { + // Fallback for malformed URLs that still start with http:// or reference + // loopback explicitly — fail safe by skipping MITM rather than guessing. + const lower = trimmed.toLowerCase() + return ( + lower.startsWith('http://') || + lower.includes('localhost') || + lower.includes('127.0.0.1') || + lower.includes('::1') + ) + } +} + +export function evaluateClaudeProxyCompatibility( + env: Readonly>, +): ClaudeProxyCompatibilityDecision { + if (hasCorporateProxyEnv(env)) { + return { + allow: false, + reason: 'corporate-proxy-env', + detail: 'Existing HTTP(S)_PROXY environment variable detected; skipping local mitmproxy.', + } + } + + for (const flag of NON_ANTHROPIC_BACKEND_FLAGS) { + if (isTruthyEnvFlag(env[flag])) { + return { + allow: false, + reason: 'non-anthropic-backend', + detail: `${flag} is enabled; skipping local Anthropic mitmproxy.`, + } + } + } + + const baseUrl = env.ANTHROPIC_BASE_URL + if (typeof baseUrl === 'string' && isLocalOrPlainHttpBaseUrl(baseUrl)) { + return { + allow: false, + reason: 'local-or-http-base-url', + detail: 'ANTHROPIC_BASE_URL points to plain HTTP or loopback; skipping local mitmproxy.', + } + } + + return { allow: true } +} + +/** + * Build the child process environment for a proxied Claude spawn. + * + * WHY NODE_EXTRA_CA_CERTS is merged into a combined PEM instead of overwritten: + * Users behind enterprise TLS inspection or private registries often set + * `NODE_EXTRA_CA_CERTS` to trust their corporate root CA. Overwriting it + * with only mitmproxy's CA silently breaks every Node tool spawned inside + * the session that talks to internal HTTPS endpoints. Concatenating the + * user's bundle and mitmproxy's CA into a per-run PEM inside `proxyInfo.workDir` + * preserves both trust roots. If the user's CA file cannot be read, we + * intentionally throw so `ClaudeSession.start()`'s fail-open catch tears + * down the proxy and spawns Claude directly with the user's untouched env. + */ +export async function buildClaudeProxyEnv( + cleanEnv: Readonly>, + proxyInfo: { proxyUrl: string; caCertPath: string; workDir: string }, +): Promise> { + const proxyEnv: Record = { ...cleanEnv } + proxyEnv.HTTPS_PROXY = proxyInfo.proxyUrl + proxyEnv.https_proxy = proxyInfo.proxyUrl + proxyEnv.HTTP_PROXY = proxyInfo.proxyUrl + proxyEnv.http_proxy = proxyInfo.proxyUrl + + const mergedNoProxy = mergeNoProxy(cleanEnv) + proxyEnv.NO_PROXY = mergedNoProxy + proxyEnv.no_proxy = mergedNoProxy + + const userExtraCa = cleanEnv.NODE_EXTRA_CA_CERTS?.trim() + if (userExtraCa) { + const [userPem, mitmPem] = await Promise.all([ + readFile(userExtraCa, 'utf8'), + readFile(proxyInfo.caCertPath, 'utf8'), + ]) + const combinedPath = join(proxyInfo.workDir, 'combined-extra-ca-certs.pem') + const combinedPem = `${userPem.trimEnd()}\n${mitmPem.trimStart()}` + await writeFile(combinedPath, combinedPem, { encoding: 'utf8', mode: 0o600 }) + proxyEnv.NODE_EXTRA_CA_CERTS = combinedPath + } else { + proxyEnv.NODE_EXTRA_CA_CERTS = proxyInfo.caCertPath + } + + return proxyEnv +} diff --git a/src/providers/claude/runtime/claudeSession.ts b/src/providers/claude/runtime/claudeSession.ts index 24dd3c4f3..63623690c 100644 --- a/src/providers/claude/runtime/claudeSession.ts +++ b/src/providers/claude/runtime/claudeSession.ts @@ -28,6 +28,10 @@ import type { PromptReadinessOutcome, } from '@shared/types/session.js' import { unwrapClaudePastedContent } from '@shared/claude/pastedContent.js' +import { + buildClaudeProxyEnv, + evaluateClaudeProxyCompatibility, +} from '@providers/claude/runtime/claudeProxyPolicy.js' import { ClaudeCodeHeadless, createProxyServer } from 'claude-code-headless' import type { ClaudeCondition, @@ -277,162 +281,113 @@ export class ClaudeSession extends EventEmitter { } // Two spawn paths: - // useProxy=false → plain node-pty spawn, screen-driven semantics. - // useProxy=true → start per-session mitmproxy, spawn `claude` with the - // proxy env built inline below (HTTPS_PROXY + - // additive NODE_EXTRA_CA_CERTS), route transport events - // into the adapter. + // effectiveUseProxy=false → plain node-pty spawn, screen-driven semantics. + // effectiveUseProxy=true → start per-session mitmproxy, spawn `claude` + // with the proxy env built by + // buildClaudeProxyEnv (HTTPS_PROXY + merged + // NO_PROXY + additive/merged NODE_EXTRA_CA_CERTS), + // route transport events into the adapter. // - // The proxy branch builds its env inline rather than calling the - // claude-code-headless `spawnClaudeWithProxy` helper. We used to call the - // helper for the no-arg case and inline only for --resume / - // --dangerously-skip-permissions, but the two had drifted (the helper also - // injected trust-store-REPLACING CA vars — see #281 — and silently dropped - // options.env). Both cases now share one inline env so resume args and CA - // policy live in exactly one place. + // WHY proxy startup is fail-open (#1552): + // mitmproxy is strictly an observational enhancement for richer live + // streaming; Claude Code operates normally without it via screen + JSONL + // semantics. Hard-aborting Claude spawn when mitmdump is missing, fails + // to bind, or cannot read a user's NODE_EXTRA_CA_CERTS turns a diagnostic + // layer into a single point of failure. Likewise, environments with an + // existing corporate proxy, Bedrock/Vertex/Foundry backend, or plain-HTTP/ + // loopback ANTHROPIC_BASE_URL are skipped up front so we never break + // connectivity or clobber user network config. + let effectiveUseProxy = false + let spawnEnv: Record = cleanEnv + if (this.useProxy) { - // WHY proxy runtime storage must not live under `cwd`: - // - // Passing the workspace cwd into createProxyServer made the proxy layer - // create timestamped runtime directories in whatever project the user had - // open. That polluted repos with `proxy-events.jsonl`, mitmproxy CA - // state, and other runtime artifacts. Agent Code owns the storage policy - // and passes its concrete app-state root into the reusable package. - // Resolve which mitmdump binary the proxy runtime should - // spawn. Order of preference: - // - // 1. process.env.CLAUDE_HEADLESS_MITMDUMP (or the legacy - // CC_PROXY_TEST_MITMDUMP alias) — debug / instrumented - // builds. Must win over everything else so contributors can - // point this at a hand-built mitmdump without first un- - // installing the bundled helper. - // 2. Bundled artifact unpacked from the packaged app (#119). - // Resolves lazily; first call extracts the .app into - // userData, subsequent calls return the cached path. - // 3. Setup-cached PATH path (e.g. user's Homebrew mitmdump). - // 4. claude-code-headless' own fallback chain (homebrew / - // /usr/local lookup) when we pass nothing. - // - // WHY we check the env var here even though claude-code-headless - // also checks it: the package's check only runs when its caller - // (us) does NOT pass `mitmDumpPath`. If we eagerly resolved the - // bundled helper and passed it through, the env override would - // be silently shadowed — exactly the contract violation flagged - // in the runtimeTools.ts module header. We short-circuit here so - // bundled resolution and setup-cached lookup are both skipped - // whenever the env override is set; the package then sees no - // `mitmDumpPath`, falls into its own fallback chain, and uses - // the env override. - // - // WHY we resolve here and not inside claude-code-headless: - // The reusable package must stay Electron-agnostic — it must - // not know about app.asar.unpacked or app.getPath('userData'). - // Agent Code main owns the bundled-helper policy; the package - // just spawns whatever path it's handed. - const envOverrideSet = Boolean( - process.env.CLAUDE_HEADLESS_MITMDUMP || process.env.CC_PROXY_TEST_MITMDUMP, - ) - const bundledMitmDump = envOverrideSet - ? null - : await resolveBundledTool('mitmdump') - const setupMitmDump = - envOverrideSet || bundledMitmDump - ? null - : getToolPath('mitmdump', '') || null - const mitmDumpPath = bundledMitmDump ?? setupMitmDump ?? undefined + const compatibility = evaluateClaudeProxyCompatibility(cleanEnv) + if (!compatibility.allow) { + console.warn( + `[claudeSession] skipping local proxy for session ${this.shellSessionId ?? ''}: ${compatibility.detail}`, + ) + this.emit('transcript-diagnostic', { + kind: 'claude-proxy-skipped', + reason: compatibility.reason, + detail: compatibility.detail, + }) + } else { + let createdProxy: ProxyServer | null = null + try { + // Resolve which mitmdump binary the proxy runtime should spawn. + // Order of preference: + // 1. process.env.CLAUDE_HEADLESS_MITMDUMP (or CC_PROXY_TEST_MITMDUMP) + // 2. Bundled artifact unpacked from the packaged app (#119) + // 3. Setup-cached PATH path (e.g. Homebrew mitmdump) + // 4. claude-code-headless' own fallback chain when we pass nothing. + const envOverrideSet = Boolean( + process.env.CLAUDE_HEADLESS_MITMDUMP || process.env.CC_PROXY_TEST_MITMDUMP, + ) + const bundledMitmDump = envOverrideSet + ? null + : await resolveBundledTool('mitmdump') + const setupMitmDump = + envOverrideSet || bundledMitmDump + ? null + : getToolPath('mitmdump', '') || null + const mitmDumpPath = bundledMitmDump ?? setupMitmDump ?? undefined + + createdProxy = await createProxyServer({ + storageRoot: PROXY_EVENTS_DIR, + // WHY the shared constant and not an inline join: `--set confdir=` + // is the argv token the mitmproxy reaper uses to recognise processes + // Agent Code started (see mitmproxyReaper.ts). + confDir: MITMPROXY_SHARED_CONF_DIR, + cwd: this.cwd, + sessionKey: this.resumeSessionId + ? `resume-${this.resumeSessionId}` + : (this.shellSessionId ? `shell-${this.shellSessionId}` : undefined), + ...(mitmDumpPath ? { mitmDumpPath } : {}), + }) + await createdProxy.start() + this.proxyServer = createdProxy + spawnEnv = await buildClaudeProxyEnv(cleanEnv, createdProxy.info) + effectiveUseProxy = true + } catch (err) { + // Ensure any partially-created or started proxy process is stopped + // before falling back to direct spawn so we never leak a bound port + // or orphaned mitmdump child. + if (createdProxy && !this.proxyServer) { + this.proxyServer = createdProxy + } + await this.teardownProxy() + spawnEnv = cleanEnv + effectiveUseProxy = false + const detail = err instanceof Error ? err.message : String(err) + console.warn( + `[claudeSession] proxy startup failed for session ${this.shellSessionId ?? ''}; falling back to direct spawn:`, + err, + ) + this.emit('transcript-diagnostic', { + kind: 'claude-proxy-fallback', + reason: 'proxy-start-failed', + detail, + }) + } + } + } - const proxy = await createProxyServer({ - storageRoot: PROXY_EVENTS_DIR, - // WHY the shared constant and not an inline join: `--set confdir=` - // is the argv token the mitmproxy reaper uses to recognise processes - // Agent Code started (see mitmproxyReaper.ts). Spawning with the same - // constant we later search for makes the identification exact by - // construction instead of by two strings that happen to agree. - confDir: MITMPROXY_SHARED_CONF_DIR, + // From here on we may have a live mitmdump child (when effectiveUseProxy is + // true) but no PTY, no ClaudeCodeHeadless, and therefore no exit/stop + // plumbing. Wrap the spawn so a failure rolls back every acquired resource + // (#495 A9; same shape as codexSession's guarded spawn). + try { + await this.appendPrivateMcpConfig(args, spawnEnv) + this.pty = ptySpawn(this.binary, args, { + name: 'xterm-256color', + cols: this.cols, + rows: this.rows, cwd: this.cwd, - sessionKey: this.resumeSessionId - ? `resume-${this.resumeSessionId}` - : (this.shellSessionId ? `shell-${this.shellSessionId}` : undefined), - ...(mitmDumpPath ? { mitmDumpPath } : {}), + env: spawnEnv, }) - await proxy.start() - this.proxyServer = proxy - - // ONE env for both the no-arg and resume/dangerous spawns. Built inline - // (no longer via spawnClaudeWithProxy) so CA policy lives in exactly one - // place. The helper and this block had drifted, and BOTH injected the - // proxy CA as trust-store-REPLACING single-cert files (SSL_CERT_FILE / - // CURL_CA_BUNDLE / REQUESTS_CA_BUNDLE). That is the #281 bug: each of - // those vars replaces the *entire* root store with just the mitmproxy - // CA, so every host the proxy PASSES THROUGH (npmjs, PyPI, Azure, - // GitHub, …) presents its real cert and is then rejected — breaking npm, - // pip, az, curl and git for any tool that reads those vars. It is not a - // missing-tool problem; it is an actively harmful replace, and chasing it - // per-tool (adding npm_config_cafile, GIT_SSL_CAINFO, AZURE_*, …) is an - // unwinnable allowlist. - // - // The proxy only MITMs api.anthropic.com (allow_hosts in proxyServer.ts); - // everything else is a clean TLS passthrough with a real cert, so - // non-Claude tools need NO CA help whatsoever. The universal, list-free - // fix is to inject ONLY NODE_EXTRA_CA_CERTS — which is ADDITIVE: it - // augments the real root store instead of replacing it. Claude (node) - // then trusts the mitmproxy cert for api.anthropic.com while still - // trusting real certs for every other host, and every other tool keeps - // its normal trust and just works. Verified: node→anthropic authorized - // (issuer mitmproxy), node→npmjs authorized (issuer Google), npm ping OK. - // - // Trade-off: a NON-node tool that needs to reach api.anthropic.com - // THROUGH the proxy would no longer trust the mitm cert. That host is - // only ever spoken to by Claude itself (node), so this is acceptable; we - // deliberately do NOT maintain a per-tool CA-var allowlist. - // - // cleanEnv already carries TERM/COLORTERM/CLAUDE_CODE_ENTRYPOINT and any - // options.env overrides, so unifying onto it also fixes the old fast path - // silently dropping options.env. - const proxyEnv: Record = { ...cleanEnv } - proxyEnv.HTTPS_PROXY = proxy.info.proxyUrl - proxyEnv.https_proxy = proxy.info.proxyUrl - proxyEnv.HTTP_PROXY = proxy.info.proxyUrl - proxyEnv.http_proxy = proxy.info.proxyUrl - proxyEnv.NODE_EXTRA_CA_CERTS = proxy.info.caCertPath - proxyEnv.NO_PROXY = 'localhost,127.0.0.1,::1' - proxyEnv.no_proxy = proxyEnv.NO_PROXY - // From here on we have a live mitmdump child but no PTY, no - // ClaudeCodeHeadless, and therefore no exit/stop plumbing. Any - // throw between proxy.start() above and the end of start() leaks - // the proxy process — nothing else would ever call stop() on it. - // Wrap the spawn so a failure rolls the proxy back (#495 A9; same - // shape as codexSession's guarded spawn). - try { - await this.appendPrivateMcpConfig(args, proxyEnv) - this.pty = ptySpawn(this.binary, args, { - name: 'xterm-256color', - cols: this.cols, - rows: this.rows, - cwd: this.cwd, - env: proxyEnv, - }) - } catch (err) { - await this.rollbackStart() - throw err - } - } else { - // No proxy in this branch, so rollbackStart is near-vacuous today — - // kept anyway so both spawn paths share one failure contract and a - // future resource acquired before this point is covered by default. - try { - await this.appendPrivateMcpConfig(args, cleanEnv) - this.pty = ptySpawn(this.binary, args, { - name: 'xterm-256color', - cols: this.cols, - rows: this.rows, - cwd: this.cwd, - env: cleanEnv, - }) - } catch (err) { - await this.rollbackStart() - throw err - } + } catch (err) { + await this.rollbackStart() + throw err } this.headless = new ClaudeCodeHeadless({ @@ -456,11 +411,9 @@ export class ClaudeSession extends EventEmitter { allowMissingTranscript: this.resumeSessionId === null, // Enabling proxy on the headless instance is what flips the // semantic source of truth from screen to proxy inside - // ClaudeCodeHeadless. Even without this, subscribing to - // semantic events would still yield screen-sourced deltas - // (source='screen', confidence='fallback') — but consumers - // that opted into proxy specifically want the richer stream. - proxy: this.useProxy + // ClaudeCodeHeadless. Use `effectiveUseProxy` (not `this.useProxy`) so a + // skipped or fail-open direct spawn still receives screen-sourced deltas. + proxy: effectiveUseProxy ? { // Sidecar Haiku filtering — see ClaudeProxyAdapter for // the full rationale, and docs/design/ghost-system.md diff --git a/src/providers/codex/runtime/codexProxyPolicy.test.ts b/src/providers/codex/runtime/codexProxyPolicy.test.ts new file mode 100644 index 000000000..e2b8129cd --- /dev/null +++ b/src/providers/codex/runtime/codexProxyPolicy.test.ts @@ -0,0 +1,276 @@ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { resolveCodexProxyDecision } from './codexProxyPolicy.js' +import { CodexSession } from './codexSession.js' + +const harness = vi.hoisted(() => ({ + ptySpawns: [] as Array<{ binary: string; args: string[]; env: Record }>, + proxyCreateCalls: [] as Array>, + proxyShouldThrow: false, +})) + +vi.mock('@main/storage/paths.js', async (importOriginal) => { + const actual = await importOriginal() + const { tmpdir: osTmpdir } = await import('node:os') + const { join: pathJoin } = await import('node:path') + return { + ...actual, + PROXY_EVENTS_DIR: pathJoin(osTmpdir(), 'agent-code-codex-proxy-test'), + TLDR_HOOK_RUNTIME_DIR: pathJoin(osTmpdir(), 'agent-code-codex-tldr-test'), + } +}) + +vi.mock('node-pty', () => ({ + spawn: (binary: string, args: string[], opts: { env: Record }) => { + harness.ptySpawns.push({ binary, args: [...args], env: { ...opts.env } }) + return { + pid: 5150, + process: binary, + write: () => undefined, + resize: () => undefined, + kill: () => undefined, + onData: () => ({ dispose: () => undefined }), + onExit: () => ({ dispose: () => undefined }), + } + }, +})) + +vi.mock('codex-headless', async () => { + const { EventEmitter } = await import('node:events') + class FakeCodexHeadless extends EventEmitter { + semantic = new EventEmitter() + async start() { return { sessionsDir: '/fake/codex/sessions' } } + async stop() {} + getScreen() { return '' } + getSettledScreen() { return '' } + getComposerState() { return 'empty' } + getConditionSnapshot() { return { provider: 'codex', conditions: {}, ts: 0 } } + } + + return { + CodexHeadless: FakeCodexHeadless, + CodexResponsesAdapter: class { + attach() {} + detach() {} + diagnostics() { return { flows: 0, bufferedChars: 0 } } + }, + ResponsesProxy: class { + info = { + proxyBaseUrl: 'http://127.0.0.1:19090/v1', + upstreamBaseUrl: 'https://chatgpt.com/backend-api/codex', + authMode: 'chatgpt' as const, + } + static async create(options: Record) { + harness.proxyCreateCalls.push(options) + if (harness.proxyShouldThrow) { + throw new Error('EADDRINUSE: failed to bind local proxy') + } + return new this() + } + async stop() {} + }, + ensureCodexProjectTrust: async () => 'already-trusted', + prepareCodex01491PromptInputProfile: async () => ({ ok: false, reason: 'test-stub' }), + prepareCodexResumeRollout: async () => ({ dispose: async () => {} }), + } +}) + +describe('resolveCodexProxyDecision', () => { + let codexHome: string + + beforeEach(async () => { + codexHome = await mkdtemp(join(tmpdir(), 'codex-proxy-policy-')) + }) + + afterEach(async () => { + await rm(codexHome, { recursive: true, force: true }) + }) + + it('skips proxy when corporate proxy env var is set', async () => { + await writeFile(join(codexHome, 'auth.json'), JSON.stringify({ auth_mode: 'chatgpt' }), 'utf8') + const decision = await resolveCodexProxyDecision({ + CODEX_HOME: codexHome, + HTTPS_PROXY: 'http://corp.proxy:8080', + }) + expect(decision).toMatchObject({ useProxy: false, reason: 'corporate-proxy-env' }) + }) + + it('skips proxy when config.toml sets a non-openai model_provider', async () => { + await writeFile(join(codexHome, 'config.toml'), 'model_provider = "azure"\n', 'utf8') + await writeFile(join(codexHome, 'auth.json'), JSON.stringify({ auth_mode: 'apikey' }), 'utf8') + const decision = await resolveCodexProxyDecision({ CODEX_HOME: codexHome }) + expect(decision).toMatchObject({ useProxy: false, reason: 'custom-model-provider' }) + }) + + it('uses config.toml openai_base_url or OPENAI_BASE_URL as upstreamBaseUrl', async () => { + await writeFile( + join(codexHome, 'config.toml'), + 'model_provider = "openai"\nopenai_base_url = "https://gateway.example/v1"\n', + 'utf8', + ) + expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toEqual({ + useProxy: true, + upstreamBaseUrl: 'https://gateway.example/v1', + }) + + await writeFile(join(codexHome, 'config.toml'), '', 'utf8') + expect( + await resolveCodexProxyDecision({ + CODEX_HOME: codexHome, + OPENAI_BASE_URL: 'https://env-gateway.example/v1', + }), + ).toEqual({ + useProxy: true, + upstreamBaseUrl: 'https://env-gateway.example/v1', + }) + }) + + it.each(['chatgpt', 'chatgptAuthTokens', 'headers', 'agentIdentity', 'personalAccessToken'])( + 'detects chatgpt authMode for auth_mode=%s', + async mode => { + await writeFile(join(codexHome, 'auth.json'), JSON.stringify({ auth_mode: mode }), 'utf8') + expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toEqual({ + useProxy: true, + authMode: 'chatgpt', + }) + }, + ) + + it('detects chatgpt authMode when tokens exist without OPENAI_API_KEY', async () => { + await writeFile( + join(codexHome, 'auth.json'), + JSON.stringify({ tokens: { access_token: 'jwt' } }), + 'utf8', + ) + expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toEqual({ + useProxy: true, + authMode: 'chatgpt', + }) + }) + + it('detects apikey authMode from auth_mode or OPENAI_API_KEY in auth.json or env', async () => { + await writeFile(join(codexHome, 'auth.json'), JSON.stringify({ auth_mode: 'apikey' }), 'utf8') + expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toEqual({ + useProxy: true, + authMode: 'apikey', + }) + + await writeFile(join(codexHome, 'auth.json'), JSON.stringify({ OPENAI_API_KEY: 'sk-test' }), 'utf8') + expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toEqual({ + useProxy: true, + authMode: 'apikey', + }) + + await rm(join(codexHome, 'auth.json')) + expect( + await resolveCodexProxyDecision({ CODEX_HOME: codexHome, OPENAI_API_KEY: 'sk-env' }), + ).toEqual({ + useProxy: true, + authMode: 'apikey', + }) + }) + + it('skips proxy when auth.json is absent and OPENAI_API_KEY is unset (e.g. keyring store)', async () => { + expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toMatchObject({ + useProxy: false, + reason: 'indeterminate-auth-mode', + }) + }) +}) + +describe('CodexSession proxy fail-open and NO_PROXY hygiene', () => { + let codexHome: string + + beforeEach(async () => { + codexHome = await mkdtemp(join(tmpdir(), 'codex-session-proxy-')) + harness.ptySpawns = [] + harness.proxyCreateCalls = [] + harness.proxyShouldThrow = false + }) + + afterEach(async () => { + await rm(codexHome, { recursive: true, force: true }) + }) + + it('merges NO_PROXY and passes detected authMode when ResponsesProxy starts', async () => { + await writeFile(join(codexHome, 'auth.json'), JSON.stringify({ auth_mode: 'chatgpt' }), 'utf8') + const session = new CodexSession({ + cwd: codexHome, + useProxy: true, + env: { + CODEX_HOME: codexHome, + NO_PROXY: 'internal.corp', + HTTPS_PROXY: undefined, + https_proxy: undefined, + HTTP_PROXY: undefined, + http_proxy: undefined, + OPENAI_API_KEY: undefined, + OPENAI_BASE_URL: undefined, + }, + }) + + await session.start() + + expect(harness.proxyCreateCalls).toHaveLength(1) + expect(harness.proxyCreateCalls[0]).toMatchObject({ authMode: 'chatgpt' }) + expect(harness.ptySpawns).toHaveLength(1) + expect(harness.ptySpawns[0].args).toContain('openai_base_url="http://127.0.0.1:19090/v1"') + expect(harness.ptySpawns[0].env.NO_PROXY).toBe('internal.corp,localhost,127.0.0.1,::1') + expect(harness.ptySpawns[0].env.no_proxy).toBe('internal.corp,localhost,127.0.0.1,::1') + }) + + it('falls back to direct spawn when ResponsesProxy.create throws', async () => { + harness.proxyShouldThrow = true + await writeFile(join(codexHome, 'auth.json'), JSON.stringify({ auth_mode: 'chatgpt' }), 'utf8') + const session = new CodexSession({ + cwd: codexHome, + useProxy: true, + env: { + CODEX_HOME: codexHome, + HTTPS_PROXY: undefined, + https_proxy: undefined, + HTTP_PROXY: undefined, + http_proxy: undefined, + OPENAI_API_KEY: undefined, + OPENAI_BASE_URL: undefined, + }, + }) + const diagnostics: unknown[] = [] + const started: Array<{ projectDir: string; proxyUrl?: string }> = [] + session.on('transcript-diagnostic', d => diagnostics.push(d)) + session.on('started', s => started.push(s)) + + await session.start() + + expect(harness.ptySpawns).toHaveLength(1) + expect(harness.ptySpawns[0].args.join(' ')).not.toContain('openai_base_url') + expect(started).toEqual([{ projectDir: '/fake/codex/sessions', proxyUrl: undefined }]) + expect(diagnostics.some(d => (d as { type?: string }).type === 'codex-proxy-fallback')).toBe(true) + }) + + it('skips proxy completely when auth mode is indeterminate', async () => { + const session = new CodexSession({ + cwd: codexHome, + useProxy: true, + env: { + CODEX_HOME: codexHome, + HTTPS_PROXY: undefined, + https_proxy: undefined, + HTTP_PROXY: undefined, + http_proxy: undefined, + OPENAI_API_KEY: undefined, + OPENAI_BASE_URL: undefined, + }, + }) + + await session.start() + + expect(harness.proxyCreateCalls).toHaveLength(0) + expect(harness.ptySpawns).toHaveLength(1) + expect(harness.ptySpawns[0].args.join(' ')).not.toContain('openai_base_url') + }) +}) diff --git a/src/providers/codex/runtime/codexProxyPolicy.ts b/src/providers/codex/runtime/codexProxyPolicy.ts new file mode 100644 index 000000000..33f496ba1 --- /dev/null +++ b/src/providers/codex/runtime/codexProxyPolicy.ts @@ -0,0 +1,161 @@ +import { readFile } from 'node:fs/promises' +import { homedir } from 'node:os' +import { join } from 'node:path' + +import { parse as parseToml } from '@iarna/toml' +import type { CodexAuthMode } from 'codex-headless' + +import { hasCorporateProxyEnv } from '@providers/shared/runtime/proxyEnv.js' + +/** + * Compatibility and upstream-resolution policy for Codex's local + * `ResponsesProxy` (#1552). + * + * WHY this runs BEFORE `ResponsesProxy.create()`: + * 1. Node's built-in `fetch()` inside `ResponsesProxy` does not honor + * `HTTPS_PROXY` / `HTTP_PROXY`. In corporate proxy environments, routing + * Codex through `ResponsesProxy` breaks outbound requests that Codex's + * own Rust HTTP client would have proxied cleanly. + * 2. `CodexSession` injects `--config openai_base_url=...`, which only + * redirects the built-in `openai` provider. If the user configured a + * custom `model_provider` in `$CODEX_HOME/config.toml`, spinning up + * `ResponsesProxy` is wasted work (and risks interfering with config). + * 3. `ResponsesProxy`'s default fallback when `~/.codex/auth.json` is absent + * is `apikey` → `https://api.openai.com/v1`. On macOS Keychain / keyring / + * `auto` credential stores (or before a user has logged in), `auth.json` + * does not exist even for ChatGPT-authenticated users — guessing + * `api.openai.com` sends a ChatGPT JWT to the wrong host and causes 401s. + * When we cannot prove the upstream/auth mode, skipping the proxy is + * strictly safer than guessing. + */ + +export type CodexProxyDecision = + | { + useProxy: true + upstreamBaseUrl?: string + authMode?: CodexAuthMode + } + | { + useProxy: false + reason: + | 'corporate-proxy-env' + | 'custom-model-provider' + | 'invalid-config' + | 'indeterminate-auth-mode' + detail: string + } + +const CHATGPT_AUTH_MODES = new Set([ + 'chatgpt', + 'chatgptAuthTokens', + 'headers', + 'agentIdentity', + 'personalAccessToken', +]) + +function resolveCodexHome(env: Readonly>): string { + const configured = env.CODEX_HOME?.trim() + return configured ? configured : join(homedir(), '.codex') +} + +async function readOptionalFile(path: string): Promise<{ exists: boolean; content: string | null }> { + try { + const content = await readFile(path, 'utf8') + return { exists: true, content } + } catch (err) { + const code = (err as NodeJS.ErrnoException | null)?.code + if (code === 'ENOENT') return { exists: false, content: null } + throw err + } +} + +export async function resolveCodexProxyDecision( + env: Readonly>, +): Promise { + if (hasCorporateProxyEnv(env)) { + return { + useProxy: false, + reason: 'corporate-proxy-env', + detail: 'Existing HTTP(S)_PROXY environment variable detected; skipping local ResponsesProxy.', + } + } + + const codexHome = resolveCodexHome(env) + + // 1. Inspect $CODEX_HOME/config.toml for model_provider and openai_base_url. + let configBaseUrl: string | undefined + try { + const configFile = await readOptionalFile(join(codexHome, 'config.toml')) + if (configFile.exists && configFile.content !== null) { + const parsed = parseToml(configFile.content) as Record + const modelProvider = parsed.model_provider + if ( + typeof modelProvider === 'string' && + modelProvider.trim().length > 0 && + modelProvider.trim() !== 'openai' + ) { + return { + useProxy: false, + reason: 'custom-model-provider', + detail: `Codex config.toml uses model_provider=${JSON.stringify(modelProvider.trim())}; skipping local ResponsesProxy.`, + } + } + if (typeof parsed.openai_base_url === 'string' && parsed.openai_base_url.trim().length > 0) { + configBaseUrl = parsed.openai_base_url.trim() + } + } + } catch (err) { + return { + useProxy: false, + reason: 'invalid-config', + detail: `Unable to read/parse Codex config.toml (${err instanceof Error ? err.message : String(err)}); skipping local ResponsesProxy.`, + } + } + + const envBaseUrl = env.OPENAI_BASE_URL?.trim() || undefined + const upstreamBaseUrl = configBaseUrl ?? envBaseUrl + if (upstreamBaseUrl) { + return { + useProxy: true, + upstreamBaseUrl, + } + } + + // 2. No explicit upstream URL: inspect $CODEX_HOME/auth.json and OPENAI_API_KEY + // to determine whether traffic belongs on chatgpt.com or api.openai.com. + let authData: Record | null = null + try { + const authFile = await readOptionalFile(join(codexHome, 'auth.json')) + if (authFile.exists && authFile.content !== null) { + const parsed = JSON.parse(authFile.content) as unknown + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + authData = parsed as Record + } + } + } catch { + // Unreadable or malformed auth.json: treat as indeterminate below rather + // than crashing or guessing the wrong upstream. + authData = null + } + + const envApiKey = typeof env.OPENAI_API_KEY === 'string' && env.OPENAI_API_KEY.trim().length > 0 + const fileApiKey = + typeof authData?.OPENAI_API_KEY === 'string' && authData.OPENAI_API_KEY.trim().length > 0 + const authModeRaw = typeof authData?.auth_mode === 'string' ? authData.auth_mode.trim() : '' + const hasTokens = Boolean(authData?.tokens) + + if (CHATGPT_AUTH_MODES.has(authModeRaw) || (hasTokens && !fileApiKey && !envApiKey)) { + return { useProxy: true, authMode: 'chatgpt' } + } + + if (authModeRaw === 'apikey' || fileApiKey || envApiKey) { + return { useProxy: true, authMode: 'apikey' } + } + + return { + useProxy: false, + reason: 'indeterminate-auth-mode', + detail: + 'Neither $CODEX_HOME/auth.json nor OPENAI_API_KEY indicates the Codex auth mode; skipping local ResponsesProxy to avoid misrouting.', + } +} diff --git a/src/providers/codex/runtime/codexSession.ts b/src/providers/codex/runtime/codexSession.ts index 4a56545d9..db37ef277 100644 --- a/src/providers/codex/runtime/codexSession.ts +++ b/src/providers/codex/runtime/codexSession.ts @@ -39,6 +39,8 @@ import { addCodexBuiltInMcpLaunchConfig } from '@providers/shared/runtime/builtI import { addCodexUserMcpLaunchConfig, type CodexShellPolicyStyle } from '@providers/shared/runtime/userMcpLaunch.js' import type { ResolvedUserMcpServer } from '@shared/userMcp/types.js' import { forwardCodexRolloutEntries } from '@providers/codex/runtime/codexHeadlessForwarding.js' +import { resolveCodexProxyDecision } from '@providers/codex/runtime/codexProxyPolicy.js' +import { mergeNoProxy } from '@providers/shared/runtime/proxyEnv.js' /** Allocate a per-session run directory and return the path of its @@ -144,6 +146,12 @@ export type CodexPromptEvidenceDiagnostic = { reason: string } +export type CodexProxyDiagnostic = { + type: 'codex-proxy-skipped' | 'codex-proxy-fallback' + reason: string + detail: string +} + export type CodexSessionEvents = { // Declared for AgentSession contract parity (grok Stage 4): a durable-history // generation boundary. This provider never emits it today; it exists so the @@ -169,7 +177,7 @@ export type CodexSessionEvents = { 'transcript-diagnostic': [CodexRolloutDiagnostic | { type: 'provider-request-observation' observation: CodexSemanticProviderRequestEvent - } | CodexPromptEvidenceDiagnostic] + } | CodexPromptEvidenceDiagnostic | CodexProxyDiagnostic] // process-state carries the optional spinner-derived status string // (e.g. "working… 12s") so the renderer can show provider-specific // verbiage in its activity indicator. Without this, the renderer @@ -371,51 +379,71 @@ export class CodexSession extends EventEmitter { addCodexUserMcpLaunchConfig(this.userMcpServers, args, cleanEnv, this.userMcpCodexShellPolicy) excludeExternalControlFromCodex(args, cleanEnv.CODEX_HOME) if (this.useProxy) { - // Mirror the Claude proxy's on-disk layout so a single - // bundle-inspection tool can read either provider's - // proxy-events.jsonl without branching: - // ~/.config/agent-code/proxy////proxy-events.jsonl - // - // The path discipline is identical to what - // claude-code-headless' createProxyServer does (see ProxyServer - // in proxy/proxyServer.ts createWorkDir). Codex's - // ResponsesProxy doesn't own that allocation today (the - // testing harness used to construct it without disk - // persistence at all), so we compute it here and pass it as - // an explicit `eventsFile` option. - // - // sessionKey naming mirrors Claude exactly: `resume-` when - // resuming a known thread, else `shell-` so a fresh - // session still produces a stable folder name. Both segments - // are sanitised before joining so a path-traversal attempt via - // a malformed cwd or session id can't escape the proxy root. - const eventsFile = await allocateProxyEventsFile({ - cwd: this.cwd, - sessionKey: this.resumeSessionId - ? `resume-${this.resumeSessionId}` - // Fresh sessions do not have an upstream-stable provider id yet, but - // the app-local pane id is stable for the lifetime of the process and - // is the only identifier the renderer has when a user saves a bundle - // before Codex writes session_meta. Match Claude's `shell-` - // convention so manual bundles can request exact fresh-session proxy - // evidence instead of falling back to "latest run in this project". - : (this.shellSessionId - ? `shell-${this.shellSessionId}` - : `shell-${new Date().toISOString().replace(/[:.]/g, '-')}`), - }) - if (!this.isStartAttemptActive(attempt)) return - const proxy = await ResponsesProxy.create({ eventsFile }) - if (!this.isStartAttemptActive(attempt)) { - // WHY stop can win while create() is awaiting a listening socket. The - // returned proxy did not exist when stop snapshotted the attempt, so the - // continuation that receives it must close it locally and must never - // publish it into fields now owned by a later generation. - try { await proxy.stop() } catch { /* best-effort */ } - return + // WHY proxy setup is pre-checked and fail-open (#1552): + // ResponsesProxy is an observational enhancement; Codex's rollout + // tailer and PTY work without it. Pre-checking corporate proxy env, + // config.toml model_provider/openai_base_url, and auth.json avoids + // misrouting ChatGPT/keyring/custom-provider users, and catching any + // startup error guarantees a proxy failure never aborts Codex spawn. + try { + const decision = await resolveCodexProxyDecision(cleanEnv) + if (!this.isStartAttemptActive(attempt)) return + if (!decision.useProxy) { + console.warn( + `[codexSession] skipping local proxy for session ${this.shellSessionId ?? ''}: ${decision.detail}`, + ) + this.emit('transcript-diagnostic', { + type: 'codex-proxy-skipped', + reason: decision.reason, + detail: decision.detail, + }) + } else { + // Mirror the Claude proxy's on-disk layout so a single + // bundle-inspection tool can read either provider's + // proxy-events.jsonl without branching. + const eventsFile = await allocateProxyEventsFile({ + cwd: this.cwd, + sessionKey: this.resumeSessionId + ? `resume-${this.resumeSessionId}` + : (this.shellSessionId + ? `shell-${this.shellSessionId}` + : `shell-${new Date().toISOString().replace(/[:.]/g, '-')}`), + }) + if (!this.isStartAttemptActive(attempt)) return + const proxy = await ResponsesProxy.create({ + eventsFile, + ...(decision.upstreamBaseUrl ? { upstreamBaseUrl: decision.upstreamBaseUrl } : {}), + ...(decision.authMode ? { authMode: decision.authMode } : {}), + }) + if (!this.isStartAttemptActive(attempt)) { + // WHY stop can win while create() is awaiting a listening socket. The + // returned proxy did not exist when stop snapshotted the attempt, so the + // continuation that receives it must close it locally and must never + // publish it into fields now owned by a later generation. + try { await proxy.stop() } catch { /* best-effort */ } + return + } + attempt.proxyServer = proxy + this.proxyServer = proxy + const mergedNoProxy = mergeNoProxy(cleanEnv) + cleanEnv.NO_PROXY = mergedNoProxy + cleanEnv.no_proxy = mergedNoProxy + args.push('--config', `openai_base_url=${JSON.stringify(proxy.info.proxyBaseUrl)}`) + } + } catch (err) { + attempt.proxyServer = null + this.proxyServer = null + const detail = err instanceof Error ? err.message : String(err) + console.warn( + `[codexSession] proxy startup failed for session ${this.shellSessionId ?? ''}; falling back to direct spawn:`, + err, + ) + this.emit('transcript-diagnostic', { + type: 'codex-proxy-fallback', + reason: 'proxy-start-failed', + detail, + }) } - attempt.proxyServer = proxy - this.proxyServer = proxy - args.push('--config', `openai_base_url=${JSON.stringify(proxy.info.proxyBaseUrl)}`) } // From here on we have a listening proxy (if useProxy was set) but // no PTY, no CodexHeadless, and therefore no exit/stop plumbing. diff --git a/src/providers/shared/runtime/proxyEnv.ts b/src/providers/shared/runtime/proxyEnv.ts new file mode 100644 index 000000000..8c6436857 --- /dev/null +++ b/src/providers/shared/runtime/proxyEnv.ts @@ -0,0 +1,76 @@ +/** + * Shared environment-hygiene helpers for local Claude & Codex proxies (#1552). + * + * WHY these live in one shared module: + * Both `ClaudeSession` (mitmproxy) and `CodexSession` (ResponsesProxy) face + * the exact same two corporate/network environment hazards: + * 1. Existing HTTP(S)_PROXY variables — chaining our local proxy in front + * of a corporate proxy (or having ResponsesProxy's Node `fetch()` ignore + * `HTTPS_PROXY` altogether) breaks outbound API requests instead of + * observing them. + * 2. Existing NO_PROXY / no_proxy variables — overwriting them with a bare + * loopback list drops the user's internal corporate domains, breaking + * MCP servers, private registries, and internal hosts reachable from + * the agent's shell. + */ + +export const LOOPBACK_NO_PROXY_HOSTS = ['localhost', '127.0.0.1', '::1'] as const + +const CORPORATE_PROXY_ENV_KEYS = [ + 'HTTPS_PROXY', + 'https_proxy', + 'HTTP_PROXY', + 'http_proxy', +] as const + +/** + * Returns true if the child environment already configures an upstream HTTP(S) + * proxy. Whitespace-only values are treated as unset. + */ +export function hasCorporateProxyEnv( + env: Readonly>, +): boolean { + return CORPORATE_PROXY_ENV_KEYS.some(key => { + const value = env[key] + return typeof value === 'string' && value.trim().length > 0 + }) +} + +/** + * Merge loopback bypass hosts into any existing `NO_PROXY` / `no_proxy` + * values without clobbering user entries or introducing duplicates. + * + * WHY we read BOTH casings and return a single merged string for both: + * Tools disagree on whether `NO_PROXY` or `no_proxy` wins (curl checks + * lowercase first, Node/undici and Go check both, Python urllib prefers + * lowercase). Merging the union of both existing values and writing the + * result to both `NO_PROXY` and `no_proxy` preserves every user-configured + * bypass entry regardless of which casing they set. + */ +export function mergeNoProxy( + env: Readonly>, + requiredHosts: readonly string[] = LOOPBACK_NO_PROXY_HOSTS, +): string { + const entries: string[] = [] + const seen = new Set() + + const add = (raw: string | undefined): void => { + if (!raw) return + for (const part of raw.split(',')) { + const trimmed = part.trim() + if (!trimmed) continue + const key = trimmed.toLowerCase() + if (seen.has(key)) continue + seen.add(key) + entries.push(trimmed) + } + } + + add(env.NO_PROXY) + add(env.no_proxy) + for (const host of requiredHosts) { + add(host) + } + + return entries.join(',') +} From 49cad4c9e77bae64da783f57530a2c105e4246b0 Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 15:47:45 -0800 Subject: [PATCH 3/4] fix(proxy): skip local proxy for terminal-mode agent panes Hard terminal-mode panes render the raw provider PTY directly and never mount Agent Code's semantic feed. Pass useProxy: false when the effective view mode (per-pane override or global setting) is 'terminal' across spawn, wake, reload, and rehydrate. Refs #1552 --- .../workspace/agentDisplayMode.proxy.test.ts | 75 +++++++++++++++++++ .../src/workspace/agentDisplayMode.ts | 27 ++++++- .../src/workspace/hook/actions/session.ts | 31 ++++++-- ...essionReplacementHandoff.renderer.test.tsx | 6 ++ .../workspace/hook/persistence/rehydrate.ts | 9 ++- 5 files changed, 141 insertions(+), 7 deletions(-) create mode 100644 src/renderer/src/workspace/agentDisplayMode.proxy.test.ts diff --git a/src/renderer/src/workspace/agentDisplayMode.proxy.test.ts b/src/renderer/src/workspace/agentDisplayMode.proxy.test.ts new file mode 100644 index 000000000..93dde588b --- /dev/null +++ b/src/renderer/src/workspace/agentDisplayMode.proxy.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from 'vitest' + +import { shouldUseProxyForSession } from './agentDisplayMode' + +describe('shouldUseProxyForSession', () => { + it('returns undefined for non-agent session kinds', () => { + expect( + shouldUseProxyForSession({ + kind: 'terminal', + useProxyStreaming: true, + globalMode: 'agent', + }), + ).toBeUndefined() + }) + + it('returns false when useProxyStreaming setting is disabled', () => { + expect( + shouldUseProxyForSession({ + kind: 'claude', + useProxyStreaming: false, + globalMode: 'agent', + }), + ).toBe(false) + }) + + it('returns false for Claude and Codex panes in hard terminal mode (global or override)', () => { + expect( + shouldUseProxyForSession({ + kind: 'claude', + useProxyStreaming: true, + globalMode: 'terminal', + }), + ).toBe(false) + expect( + shouldUseProxyForSession({ + kind: 'codex', + useProxyStreaming: true, + globalMode: 'terminal', + }), + ).toBe(false) + expect( + shouldUseProxyForSession({ + kind: 'claude', + useProxyStreaming: true, + globalMode: 'agent', + override: 'terminal', + }), + ).toBe(false) + }) + + it('returns true for agent and hybrid modes, including per-pane override over global terminal', () => { + expect( + shouldUseProxyForSession({ + kind: 'claude', + useProxyStreaming: true, + globalMode: 'agent', + }), + ).toBe(true) + expect( + shouldUseProxyForSession({ + kind: 'codex', + useProxyStreaming: true, + globalMode: 'hybrid', + }), + ).toBe(true) + expect( + shouldUseProxyForSession({ + kind: 'claude', + useProxyStreaming: true, + globalMode: 'terminal', + override: 'agent', + }), + ).toBe(true) + }) +}) diff --git a/src/renderer/src/workspace/agentDisplayMode.ts b/src/renderer/src/workspace/agentDisplayMode.ts index 2bf22cb10..3db6a0c5c 100644 --- a/src/renderer/src/workspace/agentDisplayMode.ts +++ b/src/renderer/src/workspace/agentDisplayMode.ts @@ -1,6 +1,6 @@ import type { AgentViewMode } from '@renderer/app-state/settings/types' import type { AgentViewModeOverride, SessionKind } from '@renderer/workspace/types' -import { effectiveProviderRuntime, isAgentProviderKind, isChatSurfaceProviderKind, isStructuredOnlyProviderKind } from '@shared/types/providerKind' +import { effectiveProviderRuntime, isAgentProviderKind, isAgentSessionKind, isChatSurfaceProviderKind, isStructuredOnlyProviderKind } from '@shared/types/providerKind' import type { AgentProviderKind, AgentProviderRuntime } from '@shared/types/providerKind' import type { RenderedViewLeaseFeature, @@ -23,6 +23,31 @@ export function resolveConfiguredAgentViewMode( return override ?? globalMode } +/** + * Decide whether a spawned/recovered session should request local proxy + * streaming (#1552). + * + * WHY hard terminal mode forces `useProxy: false`: + * In hard `'terminal'` mode the pane renders the raw provider PTY directly + * and never mounts Agent Code's semantic feed. Skipping the local proxy + * avoids spinning up unnecessary mitmproxy / ResponsesProxy processes and + * eliminates proxy overhead and network-compatibility risk for terminal-mode + * panes. + */ +export function shouldUseProxyForSession(args: { + kind: SessionKind + useProxyStreaming: boolean + globalMode: AgentViewMode + override?: AgentViewModeOverride +}): boolean | undefined { + if (!isAgentSessionKind(args.kind)) return undefined + if (!args.useProxyStreaming) return false + if (resolveConfiguredAgentViewMode(args.globalMode, args.override) === 'terminal') { + return false + } + return true +} + // Delegates to the shared guard so a registered third provider is an // agent here automatically instead of being misclassified as a // terminal pane (#394 phase 1). diff --git a/src/renderer/src/workspace/hook/actions/session.ts b/src/renderer/src/workspace/hook/actions/session.ts index 0c0009869..e246e21cc 100644 --- a/src/renderer/src/workspace/hook/actions/session.ts +++ b/src/renderer/src/workspace/hook/actions/session.ts @@ -14,6 +14,9 @@ import type { AgentProviderRuntime } from '@shared/types/providerKind' import { SESSION_START_FAILED_MESSAGE, type SessionRecoverFailureCode } from '@shared/types/session' import { useCallback, useRef } from 'react' +import { useAppStore } from '@renderer/app-state/store' +import { shouldUseProxyForSession } from '@renderer/workspace/agentDisplayMode' + import { emptyRuntime } from '@renderer/session-runtime/state' import type { SessionRuntime } from '@renderer/session-runtime/state' import { clearLiveEntryWindowSession } from '@renderer/session-runtime/liveEntryWindow' @@ -450,9 +453,17 @@ export function useSessionActions( (isAgentSessionKind(kind) ? refs.dangerousAgentsRef.current : undefined) // Agent providers both accept `useProxy`; terminals ignore it. // Claude uses MITM proxy streaming, Codex uses a local Responses - // proxy via `openai_base_url`. - const useProxy = - isAgentSessionKind(kind) ? refs.useProxyStreamingRef.current : undefined + // proxy via `openai_base_url`. Hard terminal-mode panes skip the proxy + // because they render the raw provider PTY directly (#1552). + const predecessorOverride = opts?.predecessorSessionId + ? refs.stateRef.current.sessions[opts.predecessorSessionId]?.agentViewModeOverride + : undefined + const useProxy = shouldUseProxyForSession({ + kind, + useProxyStreaming: refs.useProxyStreamingRef.current, + globalMode: useAppStore.getState().settings.agentViewMode, + override: predecessorOverride, + }) const builtInMcpOverrides = spawnMcpOverrides(opts) const builtInMcpDomains = isAgentProviderKind(kind) @@ -786,7 +797,12 @@ export function useSessionActions( ...(meta.hermesLaneKey ? { hermesLaneKey: meta.hermesLaneKey } : {}), recoverTmuxName: kind === 'terminal' ? meta.tmuxName : undefined, dangerousMode: isAgentSessionKind(kind) ? refs.dangerousAgentsRef.current : undefined, - useProxy: isAgentSessionKind(kind) ? refs.useProxyStreamingRef.current : undefined, + useProxy: shouldUseProxyForSession({ + kind, + useProxyStreaming: refs.useProxyStreamingRef.current, + globalMode: useAppStore.getState().settings.agentViewMode, + override: meta.agentViewModeOverride, + }), }) if (!recovery.ok) { readyError = new Error(recovery.message) @@ -1773,7 +1789,12 @@ export function useSessionActions( cwd: meta.cwd, resumeSessionId, dangerousMode, - useProxy: isAgentSessionKind(kind) ? refs.useProxyStreamingRef.current : undefined, + useProxy: shouldUseProxyForSession({ + kind, + useProxyStreaming: refs.useProxyStreamingRef.current, + globalMode: useAppStore.getState().settings.agentViewMode, + override: meta.agentViewModeOverride, + }), builtInMcpDomains, ...(isAgentProviderKind(kind) ? { userMcpOverrides: userMcpOverridesFrom(builtInMcpOverrides) } : {}), ...(meta.remoteConnectionId ? { remoteConnectionId: meta.remoteConnectionId } : {}), diff --git a/src/renderer/src/workspace/hook/actions/sessionReplacementHandoff.renderer.test.tsx b/src/renderer/src/workspace/hook/actions/sessionReplacementHandoff.renderer.test.tsx index 14151d937..db7dad0ad 100644 --- a/src/renderer/src/workspace/hook/actions/sessionReplacementHandoff.renderer.test.tsx +++ b/src/renderer/src/workspace/hook/actions/sessionReplacementHandoff.renderer.test.tsx @@ -2,6 +2,7 @@ import { act, renderHook } from '@testing-library/react' import type { MutableRefObject } from 'react' import { afterEach, describe, expect, it, vi } from 'vitest' +import { useAppStore } from '@renderer/app-state/store' import { UndoCloseStack } from '@renderer/lib/undoClose' import { emptyRuntime } from '@renderer/session-runtime/state' import type { SessionRuntime } from '@renderer/session-runtime/state' @@ -16,9 +17,11 @@ vi.mock('@renderer/workspace/hook/actions/initialHistory', () => ({ })) const originalApiDescriptor = Object.getOwnPropertyDescriptor(window, 'api') +const originalStore = useAppStore.getState() afterEach(() => { vi.useRealTimers() + useAppStore.setState(originalStore, true) if (originalApiDescriptor) { Object.defineProperty(window, 'api', originalApiDescriptor) } else { @@ -33,6 +36,9 @@ function ref(current: T): MutableRefObject { describe('renderer session replacement handoff', () => { it.each(['claude', 'codex', 'terminal'] as const)('preserves current text and destination-supported images when replacing with %s', async (destination) => { vi.useFakeTimers() + // Seed 'agent' mode explicitly because default 'terminal' mode skips local + // proxy streaming (#1552), whereas this test verifies useProxy forwarding. + useAppStore.setState({ settings: { ...originalStore.settings, agentViewMode: 'agent' } }) const image = { id: 'draft-image', mediaType: 'image/png', base64Data: 'eA==', previewUrl: 'blob:draft', filename: 'draft.png' } const predecessorId = 'local-predecessor' let state = { diff --git a/src/renderer/src/workspace/hook/persistence/rehydrate.ts b/src/renderer/src/workspace/hook/persistence/rehydrate.ts index bbb3db496..f07f2e7b4 100644 --- a/src/renderer/src/workspace/hook/persistence/rehydrate.ts +++ b/src/renderer/src/workspace/hook/persistence/rehydrate.ts @@ -1,4 +1,6 @@ import { tldrIdentityForSession } from '@renderer/features/tldr/identity' +import { useAppStore } from '@renderer/app-state/store' +import { shouldUseProxyForSession } from '@renderer/workspace/agentDisplayMode' import { DEFAULT_PROVIDER, isAgentProviderKind, @@ -697,7 +699,12 @@ export async function rehydrateWorkspace( cwd: meta.cwd, resumeSessionId, dangerousMode: isAgentSessionKind(kind) ? refs.dangerousAgentsRef.current : undefined, - useProxy: isAgentSessionKind(kind) ? refs.useProxyStreamingRef.current : undefined, + useProxy: shouldUseProxyForSession({ + kind, + useProxyStreaming: refs.useProxyStreamingRef.current, + globalMode: useAppStore.getState().settings.agentViewMode, + override: meta.agentViewModeOverride, + }), recoverTmuxName: kind === 'terminal' ? meta.tmuxName : undefined, builtInMcpDomains, // User MCP choices ride the same path as the built-in domains From 1353c026f1eb0ed61f4e6a3f5a4e37ba0d41c4a8 Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 15:57:08 -0800 Subject: [PATCH 4/4] fix(proxy): address PR review findings for Codex proxy cancellation and auth policy Guard CodexSession's proxy catch block against cancelled start attempts before mutating shared fields or falling through to ptySpawn, stop consulting env.OPENAI_BASE_URL/env.OPENAI_API_KEY that Codex TUI ignores, validate config.toml openai_base_url and skip profile/chatgpt_base_url/keyring configs, update ClaudeSession diagnostic comment, and record review disposition in the plan. Refs #1552 --- docs/plans/2026-11-27-proxy-resilience.md | 19 +++- src/providers/claude/runtime/claudeSession.ts | 5 +- .../codex/runtime/codexProxyPolicy.test.ts | 94 +++++++++++++++++-- .../codex/runtime/codexProxyPolicy.ts | 93 ++++++++++++++---- src/providers/codex/runtime/codexSession.ts | 31 ++++-- 5 files changed, 198 insertions(+), 44 deletions(-) diff --git a/docs/plans/2026-11-27-proxy-resilience.md b/docs/plans/2026-11-27-proxy-resilience.md index 925d96967..7cbcf227a 100644 --- a/docs/plans/2026-11-27-proxy-resilience.md +++ b/docs/plans/2026-11-27-proxy-resilience.md @@ -37,14 +37,14 @@ All changes live in the main `agent-code` repository (`src/`) so this lands as a ### 3. Codex fail-open & config/auth/env hygiene (`src/providers/codex/runtime/codexProxyPolicy.ts`, `codexSession.ts`) - `resolveCodexProxyDecision(cleanEnv)` inspects `cleanEnv`, `$CODEX_HOME/config.toml` (parsed via `@iarna/toml`), and `$CODEX_HOME/auth.json` before starting `ResponsesProxy`: - Skips if corporate proxy env vars are set. - - Skips if `config.toml` sets `model_provider` to anything other than `"openai"` (or if `config.toml` cannot be parsed). - - Uses `config.toml`'s `openai_base_url` or `cleanEnv.OPENAI_BASE_URL` as `upstreamBaseUrl` when present. - - Otherwise inspects `$CODEX_HOME/auth.json`: + - Skips if `config.toml` sets `model_provider` to anything other than `"openai"`, sets `profile`, sets `chatgpt_base_url`, sets `cli_auth_credentials_store = "keyring"`, or cannot be parsed. + - Uses `config.toml`'s `openai_base_url` as `upstreamBaseUrl` after validating it as an `http:`/`https:` URL (does NOT consult `env.OPENAI_BASE_URL`, which Codex CLI TUI ignores). + - Otherwise inspects `$CODEX_HOME/auth.json` only (does NOT infer `apikey` from `env.OPENAI_API_KEY`, which Codex CLI TUI ignores and which would misroute Keychain ChatGPT users): - ChatGPT-family `auth_mode` (`chatgpt`, `chatgptAuthTokens`, `headers`, `agentIdentity`, `personalAccessToken`) or `tokens` without `OPENAI_API_KEY` → `authMode: 'chatgpt'`. - - `auth_mode === 'apikey'` or `OPENAI_API_KEY` present in `auth.json` or `cleanEnv` → `authMode: 'apikey'`. + - `auth_mode === 'apikey'` or `OPENAI_API_KEY` present in `auth.json` → `authMode: 'apikey'`. - Otherwise (missing/indeterminate auth, e.g., Keychain/keyring or not logged in) → skip proxy. - When `ResponsesProxy` is used, merges `localhost,127.0.0.1,::1` into `cleanEnv.NO_PROXY` and `cleanEnv.no_proxy`. -- Wraps `resolveCodexProxyDecision`, `allocateProxyEventsFile`, and `ResponsesProxy.create` in `try/catch`; on any failure logs a warning, emits a non-fatal `transcript-diagnostic`, leaves `this.proxyServer = null`, omits `--config openai_base_url=...`, and spawns Codex directly. +- Wraps `resolveCodexProxyDecision`, `allocateProxyEventsFile`, and `ResponsesProxy.create` in `try/catch`; on any failure stops any locally created proxy, re-checks `isStartAttemptActive(attempt)` before mutating shared fields or falling through to `ptySpawn`, logs a warning, emits a non-fatal `transcript-diagnostic`, omits `--config openai_base_url=...`, and spawns Codex directly. ### 4. Skip proxy for Terminal-mode panes (`agentDisplayMode.ts`, `session.ts`, `rehydrate.ts`) - Add `shouldUseProxyForSession({ kind, useProxyStreaming, globalMode, override })` in `src/renderer/src/workspace/agentDisplayMode.ts`: returns `false` when `resolveConfiguredAgentViewMode(globalMode, override) === 'terminal'`. @@ -57,3 +57,12 @@ All changes live in the main `agent-code` repository (`src/`) so this lands as a - `codexProxyPolicy.ts` (corporate proxy, `config.toml` `model_provider` & `openai_base_url`, `OPENAI_BASE_URL`, `auth.json` modes, indeterminate auth skip) and `CodexSession` fail-open direct spawn - `shouldUseProxyForSession` and terminal-mode proxy suppression in renderer session actions / rehydrate - `npm run typecheck` and targeted vitest suites. + +## Review Disposition + +| Finding | Severity | Disposition | Resolution | +| --- | --- | --- | --- | +| Cancelled `CodexSession` start attempt could clear a newer generation's `proxyServer` or fall through to `ptySpawn` in the proxy `catch` block | Blocking | Fixed | Stop any locally created proxy, return early when `!this.isStartAttemptActive(attempt)` before touching `this.proxyServer` / emitting `codex-proxy-fallback` / spawning PTY, and clear `this.proxyServer` only by identity match (`codexSession.ts`). Added regression test. | +| `codexProxyPolicy` consulted `env.OPENAI_BASE_URL` and `env.OPENAI_API_KEY`, which Codex CLI TUI ignores (risking 401s for Keychain ChatGPT users who export `OPENAI_API_KEY` for other tools) | Blocking | Fixed | Removed `env.OPENAI_BASE_URL` and `env.OPENAI_API_KEY` inference from `resolveCodexProxyDecision` (`codexProxyPolicy.ts`). Updated unit tests. | +| Validate `config.toml` `openai_base_url` and skip proxy on `profile`, `chatgpt_base_url`, or `cli_auth_credentials_store = "keyring"` | Non-blocking | Fixed | Added `http:`/`https:` URL validation and conservative skips for `profile`, `chatgpt_base_url`, and `keyring` store (`codexProxyPolicy.ts`). Added unit tests. | +| Stale comment on `ClaudeSessionEvents['transcript-diagnostic']` claiming Claude never emits diagnostics | Non-blocking | Fixed | Updated comment in `claudeSession.ts` to document non-fatal proxy skip/fallback diagnostics. | diff --git a/src/providers/claude/runtime/claudeSession.ts b/src/providers/claude/runtime/claudeSession.ts index 63623690c..133aee2b5 100644 --- a/src/providers/claude/runtime/claudeSession.ts +++ b/src/providers/claude/runtime/claudeSession.ts @@ -99,8 +99,9 @@ export type ClaudeSessionEvents = { screen: [ScreenSnapshot] 'jsonl-entry': [JsonlEntry, string] 'jsonl-error': [Error] - // Declared for the provider-neutral AgentSession contract. Claude currently - // emits no transcript-discovery diagnostics, so this event never fires. + // Non-fatal provider diagnostics on the AgentSession contract (e.g. local + // mitmproxy skipped due to incompatible env or fail-open fallback to direct + // spawn). Never used to mark the session or transcript unhealthy. 'transcript-diagnostic': [unknown] 'proxy-transport-gap': [TransportGap] // Optional status: the spinner verb ("Cogitating…", "Cascading…", diff --git a/src/providers/codex/runtime/codexProxyPolicy.test.ts b/src/providers/codex/runtime/codexProxyPolicy.test.ts index e2b8129cd..1192fd479 100644 --- a/src/providers/codex/runtime/codexProxyPolicy.test.ts +++ b/src/providers/codex/runtime/codexProxyPolicy.test.ts @@ -11,6 +11,7 @@ const harness = vi.hoisted(() => ({ ptySpawns: [] as Array<{ binary: string; args: string[]; env: Record }>, proxyCreateCalls: [] as Array>, proxyShouldThrow: false, + proxyCreateHook: null as null | (() => Promise), })) vi.mock('@main/storage/paths.js', async (importOriginal) => { @@ -66,6 +67,7 @@ vi.mock('codex-headless', async () => { } static async create(options: Record) { harness.proxyCreateCalls.push(options) + if (harness.proxyCreateHook) await harness.proxyCreateHook() if (harness.proxyShouldThrow) { throw new Error('EADDRINUSE: failed to bind local proxy') } @@ -106,7 +108,7 @@ describe('resolveCodexProxyDecision', () => { expect(decision).toMatchObject({ useProxy: false, reason: 'custom-model-provider' }) }) - it('uses config.toml openai_base_url or OPENAI_BASE_URL as upstreamBaseUrl', async () => { + it('uses valid config.toml openai_base_url and ignores env.OPENAI_BASE_URL', async () => { await writeFile( join(codexHome, 'config.toml'), 'model_provider = "openai"\nopenai_base_url = "https://gateway.example/v1"\n', @@ -117,15 +119,53 @@ describe('resolveCodexProxyDecision', () => { upstreamBaseUrl: 'https://gateway.example/v1', }) + // Codex CLI TUI does not read env.OPENAI_BASE_URL; with no auth.json, + // env.OPENAI_BASE_URL alone must NOT enable the proxy. await writeFile(join(codexHome, 'config.toml'), '', 'utf8') expect( await resolveCodexProxyDecision({ CODEX_HOME: codexHome, OPENAI_BASE_URL: 'https://env-gateway.example/v1', }), - ).toEqual({ - useProxy: true, - upstreamBaseUrl: 'https://env-gateway.example/v1', + ).toMatchObject({ + useProxy: false, + reason: 'indeterminate-auth-mode', + }) + }) + + it('skips proxy when config.toml sets invalid openai_base_url, profile, chatgpt_base_url, or keyring store', async () => { + await writeFile(join(codexHome, 'auth.json'), JSON.stringify({ auth_mode: 'chatgpt' }), 'utf8') + + await writeFile(join(codexHome, 'config.toml'), 'openai_base_url = "not-a-url"\n', 'utf8') + expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toMatchObject({ + useProxy: false, + reason: 'invalid-config', + }) + + await writeFile(join(codexHome, 'config.toml'), 'profile = "work"\n', 'utf8') + expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toMatchObject({ + useProxy: false, + reason: 'custom-config-profile', + }) + + await writeFile( + join(codexHome, 'config.toml'), + 'chatgpt_base_url = "https://enterprise.chatgpt.example"\n', + 'utf8', + ) + expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toMatchObject({ + useProxy: false, + reason: 'custom-chatgpt-base-url', + }) + + await writeFile( + join(codexHome, 'config.toml'), + 'cli_auth_credentials_store = "keyring"\n', + 'utf8', + ) + expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toMatchObject({ + useProxy: false, + reason: 'keyring-credential-store', }) }) @@ -152,7 +192,7 @@ describe('resolveCodexProxyDecision', () => { }) }) - it('detects apikey authMode from auth_mode or OPENAI_API_KEY in auth.json or env', async () => { + it('detects apikey authMode from auth.json but does NOT infer apikey from env.OPENAI_API_KEY alone', async () => { await writeFile(join(codexHome, 'auth.json'), JSON.stringify({ auth_mode: 'apikey' }), 'utf8') expect(await resolveCodexProxyDecision({ CODEX_HOME: codexHome })).toEqual({ useProxy: true, @@ -165,12 +205,14 @@ describe('resolveCodexProxyDecision', () => { authMode: 'apikey', }) + // Developers with Keychain ChatGPT auth often export OPENAI_API_KEY for + // other tools; absent auth.json must still skip rather than guess apikey. await rm(join(codexHome, 'auth.json')) expect( await resolveCodexProxyDecision({ CODEX_HOME: codexHome, OPENAI_API_KEY: 'sk-env' }), - ).toEqual({ - useProxy: true, - authMode: 'apikey', + ).toMatchObject({ + useProxy: false, + reason: 'indeterminate-auth-mode', }) }) @@ -190,6 +232,7 @@ describe('CodexSession proxy fail-open and NO_PROXY hygiene', () => { harness.ptySpawns = [] harness.proxyCreateCalls = [] harness.proxyShouldThrow = false + harness.proxyCreateHook = null }) afterEach(async () => { @@ -273,4 +316,39 @@ describe('CodexSession proxy fail-open and NO_PROXY hygiene', () => { expect(harness.ptySpawns).toHaveLength(1) expect(harness.ptySpawns[0].args.join(' ')).not.toContain('openai_base_url') }) + + it('does not emit fallback or spawn PTY when a cancelled start attempt fails in ResponsesProxy.create', async () => { + await writeFile(join(codexHome, 'auth.json'), JSON.stringify({ auth_mode: 'chatgpt' }), 'utf8') + let releaseCreate!: () => void + const createStarted = new Promise(resolve => { + harness.proxyCreateHook = async () => { + resolve() + await new Promise(r => { releaseCreate = r }) + } + }) + harness.proxyShouldThrow = true + + const session = new CodexSession({ + cwd: codexHome, + useProxy: true, + env: { + CODEX_HOME: codexHome, + HTTPS_PROXY: undefined, + https_proxy: undefined, + HTTP_PROXY: undefined, + http_proxy: undefined, + }, + }) + const diagnostics: unknown[] = [] + session.on('transcript-diagnostic', d => diagnostics.push(d)) + + const startPromise = session.start() + await createStarted + const stopPromise = session.stop() + releaseCreate() + await Promise.all([startPromise, stopPromise]) + + expect(harness.ptySpawns).toHaveLength(0) + expect(diagnostics.some(d => (d as { type?: string }).type === 'codex-proxy-fallback')).toBe(false) + }) }) diff --git a/src/providers/codex/runtime/codexProxyPolicy.ts b/src/providers/codex/runtime/codexProxyPolicy.ts index 33f496ba1..7beaa3fe5 100644 --- a/src/providers/codex/runtime/codexProxyPolicy.ts +++ b/src/providers/codex/runtime/codexProxyPolicy.ts @@ -18,15 +18,19 @@ import { hasCorporateProxyEnv } from '@providers/shared/runtime/proxyEnv.js' * own Rust HTTP client would have proxied cleanly. * 2. `CodexSession` injects `--config openai_base_url=...`, which only * redirects the built-in `openai` provider. If the user configured a - * custom `model_provider` in `$CODEX_HOME/config.toml`, spinning up - * `ResponsesProxy` is wasted work (and risks interfering with config). - * 3. `ResponsesProxy`'s default fallback when `~/.codex/auth.json` is absent - * is `apikey` → `https://api.openai.com/v1`. On macOS Keychain / keyring / - * `auto` credential stores (or before a user has logged in), `auth.json` - * does not exist even for ChatGPT-authenticated users — guessing - * `api.openai.com` sends a ChatGPT JWT to the wrong host and causes 401s. - * When we cannot prove the upstream/auth mode, skipping the proxy is - * strictly safer than guessing. + * custom `model_provider`, a named `profile`, or a custom + * `chatgpt_base_url` in `$CODEX_HOME/config.toml`, we cannot safely + * predict the effective upstream and skip the proxy. + * 3. Vendored Codex CLI (`codex-rs/core/src/config/mod.rs` and + * `login/src/auth/manager.rs`) does NOT read `env.OPENAI_BASE_URL` or + * `env.OPENAI_API_KEY` for TUI auth. Inferring `apikey` from + * `env.OPENAI_API_KEY` when `auth.json` is absent would misroute + * developers who authenticate Codex via macOS Keychain (ChatGPT) while + * exporting `OPENAI_API_KEY` for unrelated tools, causing 401s against + * `api.openai.com`. Similarly, `cli_auth_credentials_store = "keyring"` + * means any `auth.json` on disk may be stale. When we cannot prove the + * upstream/auth mode from Codex's own config/auth files, skipping the + * proxy is strictly safer than guessing. */ export type CodexProxyDecision = @@ -40,6 +44,9 @@ export type CodexProxyDecision = reason: | 'corporate-proxy-env' | 'custom-model-provider' + | 'custom-config-profile' + | 'custom-chatgpt-base-url' + | 'keyring-credential-store' | 'invalid-config' | 'indeterminate-auth-mode' detail: string @@ -58,6 +65,15 @@ function resolveCodexHome(env: Readonly>): st return configured ? configured : join(homedir(), '.codex') } +function isValidHttpUrl(raw: string): boolean { + try { + const parsed = new URL(raw) + return parsed.protocol === 'http:' || parsed.protocol === 'https:' + } catch { + return false + } +} + async function readOptionalFile(path: string): Promise<{ exists: boolean; content: string | null }> { try { const content = await readFile(path, 'utf8') @@ -82,12 +98,22 @@ export async function resolveCodexProxyDecision( const codexHome = resolveCodexHome(env) - // 1. Inspect $CODEX_HOME/config.toml for model_provider and openai_base_url. + // 1. Inspect $CODEX_HOME/config.toml for provider/profile/store overrides and + // explicit openai_base_url. let configBaseUrl: string | undefined try { const configFile = await readOptionalFile(join(codexHome, 'config.toml')) if (configFile.exists && configFile.content !== null) { const parsed = parseToml(configFile.content) as Record + + if (typeof parsed.profile === 'string' && parsed.profile.trim().length > 0) { + return { + useProxy: false, + reason: 'custom-config-profile', + detail: `Codex config.toml selects profile=${JSON.stringify(parsed.profile.trim())}; skipping local ResponsesProxy.`, + } + } + const modelProvider = parsed.model_provider if ( typeof modelProvider === 'string' && @@ -100,8 +126,36 @@ export async function resolveCodexProxyDecision( detail: `Codex config.toml uses model_provider=${JSON.stringify(modelProvider.trim())}; skipping local ResponsesProxy.`, } } + + if (typeof parsed.chatgpt_base_url === 'string' && parsed.chatgpt_base_url.trim().length > 0) { + return { + useProxy: false, + reason: 'custom-chatgpt-base-url', + detail: 'Codex config.toml sets chatgpt_base_url; skipping local ResponsesProxy.', + } + } + + if ( + typeof parsed.cli_auth_credentials_store === 'string' && + parsed.cli_auth_credentials_store.trim().toLowerCase() === 'keyring' + ) { + return { + useProxy: false, + reason: 'keyring-credential-store', + detail: 'Codex config.toml sets cli_auth_credentials_store="keyring"; skipping local ResponsesProxy because auth.json may be stale.', + } + } + if (typeof parsed.openai_base_url === 'string' && parsed.openai_base_url.trim().length > 0) { - configBaseUrl = parsed.openai_base_url.trim() + const candidate = parsed.openai_base_url.trim() + if (!isValidHttpUrl(candidate)) { + return { + useProxy: false, + reason: 'invalid-config', + detail: `Codex config.toml openai_base_url is not a valid http(s) URL; skipping local ResponsesProxy.`, + } + } + configBaseUrl = candidate } } } catch (err) { @@ -112,17 +166,17 @@ export async function resolveCodexProxyDecision( } } - const envBaseUrl = env.OPENAI_BASE_URL?.trim() || undefined - const upstreamBaseUrl = configBaseUrl ?? envBaseUrl - if (upstreamBaseUrl) { + if (configBaseUrl) { return { useProxy: true, - upstreamBaseUrl, + upstreamBaseUrl: configBaseUrl, } } - // 2. No explicit upstream URL: inspect $CODEX_HOME/auth.json and OPENAI_API_KEY + // 2. No explicit config.toml openai_base_url: inspect $CODEX_HOME/auth.json // to determine whether traffic belongs on chatgpt.com or api.openai.com. + // Do NOT fall back to env.OPENAI_API_KEY: Codex TUI does not use it for + // auth, so consulting it would misroute Keychain ChatGPT users. let authData: Record | null = null try { const authFile = await readOptionalFile(join(codexHome, 'auth.json')) @@ -138,17 +192,16 @@ export async function resolveCodexProxyDecision( authData = null } - const envApiKey = typeof env.OPENAI_API_KEY === 'string' && env.OPENAI_API_KEY.trim().length > 0 const fileApiKey = typeof authData?.OPENAI_API_KEY === 'string' && authData.OPENAI_API_KEY.trim().length > 0 const authModeRaw = typeof authData?.auth_mode === 'string' ? authData.auth_mode.trim() : '' const hasTokens = Boolean(authData?.tokens) - if (CHATGPT_AUTH_MODES.has(authModeRaw) || (hasTokens && !fileApiKey && !envApiKey)) { + if (CHATGPT_AUTH_MODES.has(authModeRaw) || (hasTokens && !fileApiKey)) { return { useProxy: true, authMode: 'chatgpt' } } - if (authModeRaw === 'apikey' || fileApiKey || envApiKey) { + if (authModeRaw === 'apikey' || fileApiKey) { return { useProxy: true, authMode: 'apikey' } } @@ -156,6 +209,6 @@ export async function resolveCodexProxyDecision( useProxy: false, reason: 'indeterminate-auth-mode', detail: - 'Neither $CODEX_HOME/auth.json nor OPENAI_API_KEY indicates the Codex auth mode; skipping local ResponsesProxy to avoid misrouting.', + '$CODEX_HOME/auth.json does not indicate the Codex auth mode; skipping local ResponsesProxy to avoid misrouting.', } } diff --git a/src/providers/codex/runtime/codexSession.ts b/src/providers/codex/runtime/codexSession.ts index db37ef277..ca24ab579 100644 --- a/src/providers/codex/runtime/codexSession.ts +++ b/src/providers/codex/runtime/codexSession.ts @@ -382,9 +382,10 @@ export class CodexSession extends EventEmitter { // WHY proxy setup is pre-checked and fail-open (#1552): // ResponsesProxy is an observational enhancement; Codex's rollout // tailer and PTY work without it. Pre-checking corporate proxy env, - // config.toml model_provider/openai_base_url, and auth.json avoids - // misrouting ChatGPT/keyring/custom-provider users, and catching any - // startup error guarantees a proxy failure never aborts Codex spawn. + // config.toml settings, and auth.json avoids misrouting ChatGPT/ + // keyring/custom-provider users, and catching any startup error + // guarantees a proxy failure never aborts Codex spawn. + let createdProxy: ResponsesProxy | null = null try { const decision = await resolveCodexProxyDecision(cleanEnv) if (!this.isStartAttemptActive(attempt)) return @@ -410,7 +411,7 @@ export class CodexSession extends EventEmitter { : `shell-${new Date().toISOString().replace(/[:.]/g, '-')}`), }) if (!this.isStartAttemptActive(attempt)) return - const proxy = await ResponsesProxy.create({ + createdProxy = await ResponsesProxy.create({ eventsFile, ...(decision.upstreamBaseUrl ? { upstreamBaseUrl: decision.upstreamBaseUrl } : {}), ...(decision.authMode ? { authMode: decision.authMode } : {}), @@ -420,19 +421,31 @@ export class CodexSession extends EventEmitter { // returned proxy did not exist when stop snapshotted the attempt, so the // continuation that receives it must close it locally and must never // publish it into fields now owned by a later generation. - try { await proxy.stop() } catch { /* best-effort */ } + try { await createdProxy.stop() } catch { /* best-effort */ } return } - attempt.proxyServer = proxy - this.proxyServer = proxy + attempt.proxyServer = createdProxy + this.proxyServer = createdProxy const mergedNoProxy = mergeNoProxy(cleanEnv) cleanEnv.NO_PROXY = mergedNoProxy cleanEnv.no_proxy = mergedNoProxy - args.push('--config', `openai_base_url=${JSON.stringify(proxy.info.proxyBaseUrl)}`) + args.push('--config', `openai_base_url=${JSON.stringify(createdProxy.info.proxyBaseUrl)}`) } } catch (err) { + if (createdProxy) { + try { await createdProxy.stop() } catch { /* best-effort */ } + } + // WHY check generation liveness BEFORE touching shared fields or + // falling through to ptySpawn: stop() or a newer start() generation + // may have cancelled this attempt while allocateProxyEventsFile() or + // ResponsesProxy.create() was awaiting. Falling through would spawn + // an orphaned Codex PTY for a dead generation, and unconditional + // `this.proxyServer = null` would clobber the newer generation's proxy. + if (!this.isStartAttemptActive(attempt)) return + if (attempt.proxyServer && this.proxyServer === attempt.proxyServer) { + this.proxyServer = null + } attempt.proxyServer = null - this.proxyServer = null const detail = err instanceof Error ? err.message : String(err) console.warn( `[codexSession] proxy startup failed for session ${this.shellSessionId ?? ''}; falling back to direct spawn:`,