/** * devflow proxy — Enable, disable, and check status of external model routing * (GPT models via your OpenAI/Codex subscription). * * CLI-layer module; all core logic lives in src/core/proxy-state.ts * and src/core/agent-models.ts. * Never process.exit() inside a finally-guarded scope (it would skip the finally); * use return from the async action handler for all early-exit paths. * Hook output strings use fixed templates; port number interpolation * is acceptable (digit-validated integer, not user-controlled content). * * Branding note: "subswitch" must NEVER appear in user-visible strings. Internal * identifiers (SUBSWITCH_CONFIG env var, health body checks) are fine. */ import { Command } from 'commander'; import { promises as fs, readFileSync } from 'fs'; import { fileURLToPath } from 'url'; import * as path from 'path'; import * as net from 'net'; import * as http from 'http'; import * as https from 'https'; import { execFile, spawn as cpSpawn } from 'child_process'; import { promisify } from 'node:util'; import * as p from '@clack/prompts'; import color from 'picocolors'; import { readProxyState, writeProxyState, buildProxyState, buildRoutingConfigJson, proxyBaseUrl, classifyProxyBaseUrl, readProxyEnvState, proxyJsonExists, resolveProxyBin, DEFAULT_PROXY_PORT, } from '../../core/proxy-state.js'; import { CODE_MODE_READ_FAILURE, PROXY_ENABLE_REFUSAL, codeModeBlockers, codeModeManifestSignals, isCodeModeOn, isProxyOn, isTrafficOn, readCodeModeSignals, readSettingsEnv, } from '../../core/code-mode.js'; import { syncManifestFeature } from '../../core/manifest.js'; import { readGateManifest } from '../../core/gate-level.js'; import { writeSettingsFileAtomic } from '../../core/fs-atomic.js'; import { scrubChildEnv, openProxyLog, rotateProxyLogIfLarge } from '../../core/proxy-log.js'; import { inspectCodexAuth, classifyCodexAuthReadError, type CodexAuthState } from '../../core/codex-auth-inspect.js'; import { stripAnsi } from '../../hud/colors.js'; import { reapplyAgentMapping, revertExternalAgents, countExternalMappedAgents, readAgentMapping, } from '../../core/agent-models.js'; import { getExternalModelsCached, discoverExternalModels, type ExternalModelCatalog, } from '../../core/model-discovery.js'; import { modelCacheDir } from '../../core/cache.js'; import { formatLinksSummary } from './install-report.js'; import { getClaudeDirectory, getDevFlowDirectory, getHomeDirectory, } from '../../targets/claude-code/claude-paths.js'; import { devflowHookOwner, ensureHook, hasHook, removeHooks, runHookCommand, type Settings, } from '../../targets/claude-code/hooks.js'; export { readProxyEnvState } from '../../core/proxy-state.js'; // ─── Result type (local pattern) ────────────────────────────────────────────── type Result = { ok: true; value: T } | { ok: false; error: E }; function Ok(value: T): Result { return { ok: true, value }; } function Err(error: E): Result { return { ok: false, error }; } // ─── Constants ──────────────────────────────────────────────────────────────── /** The run-hook marker of the ensure-proxy hook. */ const PROXY_HOOK_MARKER = 'ensure-proxy'; /** * D-EXACT-HOOK-OWNER: the ensure-proxy hook is devflow's only when its command ends * in `/scripts/hooks/run-hook ensure-proxy` (hooks.ts), under any directory — the one * form it has ever been registered in. A user's hook that merely mentions the word * is theirs. */ const isProxyHook = devflowHookOwner([PROXY_HOOK_MARKER]); /** The events the ensure-proxy hook is registered on. */ const PROXY_HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit'] as const; /** Timeout for individual TCP connect probes and HTTP health checks (ms). */ const PROBE_TIMEOUT_MS = 2000; /** * Maximum length of the authMode field rendered by formatCodexAuthLine. * * Known values are 'chatgpt', 'apikey', 'unknown' (≤7 chars). A generous cap * of 32 accommodates any future mode strings while bounding hostile input from * the third-party ~/.codex/auth.json file. Matches the screenshot/bug-report * hygiene rationale applied to accountSuffix (6-char cap). */ const AUTH_MODE_MAX_LEN = 32; /** * Maximum response body accepted by realHttpGet before aborting (64 KB). * Prevents unbounded memory growth on slow-trickle or misconfigured endpoints * (e.g. an SSE stream on the same port that --disable probes). */ const BODY_CAP_BYTES = 64 * 1024; /** Bound the version probe without using a shell wrapper. */ const RELAY_VERSION_TIMEOUT_MS = 1500; /** Deadline for the detach launcher to report readiness. */ const RELAY_DETACH_DEADLINE_MS = 12_000; const execFileAsync = promisify(execFile); /** Timeout for the relay doctor subprocess (ms). */ const DOCTOR_TIMEOUT_MS = 10_000; /** * Maximum number of relay port probes during the CLI spawn wait (5s at 100ms each). * * The ensure-proxy hook uses a larger budget (80×0.1s = 8s) — this difference is * intentional: * - CLI (--enable): the user is waiting at an interactive terminal. 5s is the * maximum comfortable wait; a cold relay start typically completes in <2s. * - Hook (ensure-proxy): the hook fires inside a 15-second platform timeout. The * relay may be starting from a cold OS state (first session after reboot) where * 5s is too short. 8s gives a wider revival window while leaving 7s of headroom * before the platform kills the hook. */ const RELAY_SPAWN_MAX_PROBES = 50; /** Interval between relay port probes during the CLI spawn wait (ms). */ const RELAY_SPAWN_PROBE_INTERVAL_MS = 100; /** TCP connect timeout for each relay port probe during the CLI spawn wait (ms). */ const RELAY_SPAWN_PER_PROBE_TIMEOUT_MS = 500; // ─── Version helper ─────────────────────────────────────────────────────────── const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); let _cachedVersion: string | null | undefined; function getDevflowVersion(): string | null { if (_cachedVersion !== undefined) return _cachedVersion; try { // dist/cli/commands/ → ../../.. → repo root const pkg = JSON.parse(readFileSync(path.join(__dirname, '..', '..', '..', 'package.json'), 'utf-8')) as Record; _cachedVersion = typeof pkg.version === 'string' ? pkg.version : null; } catch { _cachedVersion = null; } return _cachedVersion; } // ─── Internal object helpers (used for single-pass atomic settings write) ──── /** * D-P4-1: Env var paired with ANTHROPIC_BASE_URL so Claude Code does not enforce * its conservative context-window limit on relay-routed (non-Claude-model) sessions. * Stripped together with the URL — always governed by URL ownership, never independently. */ const UNKNOWN_MODEL_WINDOW_ENV = 'CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT'; /** * Mutate a parsed Settings object in place: set ANTHROPIC_BASE_URL to our relay * and set UNKNOWN_MODEL_WINDOW_ENV to '1'. * * D-P4-1: Each condition is evaluated independently (no short-circuit that * skips the second write when the first reports no change). * * Returns true when the object was changed by either assignment. */ function _applyProxyEnvToObject(settings: Settings, port: number): boolean { const s = settings as Record; s.env = (s.env as Record | undefined) ?? {}; const env = s.env as Record; const newUrl = proxyBaseUrl(port); // D-P4-1: evaluate each condition independently before combining (no short-circuit) const urlChanged = env.ANTHROPIC_BASE_URL !== newUrl; const windowVarChanged = env[UNKNOWN_MODEL_WINDOW_ENV] !== '1'; env.ANTHROPIC_BASE_URL = newUrl; env[UNKNOWN_MODEL_WINDOW_ENV] = '1'; return urlChanged || windowVarChanged; } /** * Mutate a parsed Settings object in place: remove UNKNOWN_MODEL_WINDOW_ENV * unconditionally (Devflow is its only producer — there is no foreign value to protect), * and remove ANTHROPIC_BASE_URL only when it exactly matches our relay on the given * managed port. * * Scoped to `managedPort` so a user's own localhost gateway (LiteLLM, * local Ollama proxy, etc.) on ANY other port is never clobbered. * The caller is responsible for passing the port Devflow currently owns: * - disable path → proxy.json.port (or DEFAULT_PROXY_PORT) * - init path → proxy.json.port after the preflight block * - enable path → the new port being applied (followed immediately by _applyProxyEnvToObject) * - uninstall → proxy.json.port (or DEFAULT_PROXY_PORT) * * D-P4-1: URL ownership gates the URL delete only; the window var is always ours to * remove. Each outcome is evaluated into a local and OR-ed * afterwards — never short-circuit composed inline. * * Returns true when the object was changed by either deletion. */ function _stripProxyEnvFromObject(settings: Settings, managedPort: number): boolean { const s = settings as Record; const env = s.env as Record | undefined; if (!env) return false; // D-STRIP-1: every REMOVAL caller (init, uninstall, runDisable) first proves Devflow // managed the proxy — `proxyJsonExists()` — and the enable caller is taking ownership // of the key anyway, so reaching this line means the value is Devflow's to remove. // Removal is therefore unconditional: unlike ANTHROPIC_BASE_URL (port-scoped below), // this key has no foreign value to protect. const hadWindowVar = env[UNKNOWN_MODEL_WINDOW_ENV] !== undefined; delete env[UNKNOWN_MODEL_WINDOW_ENV]; let removedUrl = false; if ( typeof env.ANTHROPIC_BASE_URL === 'string' && env.ANTHROPIC_BASE_URL === proxyBaseUrl(managedPort) ) { delete env.ANTHROPIC_BASE_URL; removedUrl = true; } if (Object.keys(env).length === 0) delete s.env; return removedUrl || hadWindowVar; // OR the locals — never compose with || inline } // ─── Pure env functions (exported for testing and cross-module reuse) ───────── /** * Apply ANTHROPIC_BASE_URL=http://127.0.0.1: to settings JSON. * Returns new serialized settings string. Does not mutate input. * Idempotent — calling twice with the same port produces the same result. */ export function applyProxyEnv(settingsJson: string, port: number): string { const settings = JSON.parse(settingsJson) as Settings; _applyProxyEnvToObject(settings, port); return JSON.stringify(settings, null, 2) + '\n'; } /** * Remove ANTHROPIC_BASE_URL from settings JSON, but ONLY when its value exactly * matches our relay on `managedPort`. * * `managedPort` scopes the strip to the port Devflow owns — a user's own * localhost gateway on any other port is never touched. Pass `proxy.json.port` * (or `DEFAULT_PROXY_PORT` when the file is absent) at every call site. * * Returns new serialized settings string. Does not mutate input. * Cleans up an emptied env object. */ export function stripProxyEnv(settingsJson: string, managedPort: number): string { const settings = JSON.parse(settingsJson) as Settings; _stripProxyEnvFromObject(settings, managedPort); return JSON.stringify(settings, null, 2) + '\n'; } // ─── Pure hook helpers ────────────────────────────────────────────────────────── /** * Add ensure-proxy hooks to BOTH SessionStart and UserPromptSubmit events. * Idempotent — skips events that already have the hook. * Repairs partial state (one event present, other missing) by adding the missing one. * Mutates settings in place. Returns true when any hook was added. */ export function addProxyHooks(settings: Settings, devflowDir: string): boolean { const command = runHookCommand(devflowDir, PROXY_HOOK_MARKER); // Evaluate each event into its own local — never short-circuit. const [addedSession, addedPrompt] = PROXY_HOOK_EVENTS.map((event) => ensureHook(settings, event, isProxyHook, { hooks: [{ type: 'command', command, timeout: 15 }] }), ); return addedSession || addedPrompt; } /** * Remove ensure-proxy hooks from all events. * Idempotent — no-op when hooks are not present. * Removes single hooks, so the other hooks of a shared matcher group stay in place * (D-EXACT-HOOK-OWNER). Cleans empty arrays/objects. * Mutates settings in place. Returns true when any hook was removed. */ export function removeProxyHooks(settings: Settings): boolean { // Evaluate each event into its own local — never short-circuit. const [removedSession, removedPrompt] = PROXY_HOOK_EVENTS.map((event) => removeHooks(settings, event, isProxyHook), ); return removedSession || removedPrompt; } /** * Apply the disable settings-pass: remove proxy hooks AND strip ANTHROPIC_BASE_URL. * * Both operations always run unconditionally — never short-circuited with ||. * A full enabled state (hooks present AND ANTHROPIC_BASE_URL set) requires * both calls to be evaluated; short-circuiting left ANTHROPIC_BASE_URL in * settings when hooks were present, keeping new sessions pointed at a disabled * relay. * * `managedPort` scopes the URL strip to the port Devflow owns — pass * `proxy.json.port` (or `DEFAULT_PROXY_PORT`) at the call site. * * Mutates settings in place. Returns true when any change was made. */ export function applyDisableToSettings(settings: Settings, managedPort: number): boolean { const removedHooks = removeProxyHooks(settings); const strippedEnv = _stripProxyEnvFromObject(settings, managedPort); return removedHooks || strippedEnv; } /** * Settings teardown for every path that turns the proxy off: `devflow proxy --disable` * and `devflow uninstall`. * * D-STRIP-1: the two removals answer to different evidence, so they are gated * separately. * - Hooks are Devflow's own artifacts — removed unconditionally. Leaving them behind * points later sessions at a hook script that no longer exists, and makes a re-run * of an interrupted uninstall unable to clean up. * - The env vars (ANTHROPIC_BASE_URL, CLAUDE_CODE_DISABLE_UNKNOWN_MODEL_WINDOW_ENFORCEMENT) * are stripped only against `managedPort`, which the caller supplies from an existing * `proxy.json` — the one piece of evidence that Devflow ever wrote them. Pass * `undefined` when that file is absent: the values then belong to a gateway Devflow * never managed (a user's own LiteLLM on 4141, say) and must survive untouched. * * When `managedPort` is defined this delegates to `applyDisableToSettings`, so the * both-operations invariant documented there still holds. * * Mutates settings in place. Returns true when any change was made. */ export function applyProxyTeardownToSettings( settings: Settings, managedPort: number | undefined, ): boolean { if (managedPort === undefined) return removeProxyHooks(settings); return applyDisableToSettings(settings, managedPort); } /** * Check whether the ensure-proxy hook is registered on at least one event. * Returns true if present on either SessionStart or UserPromptSubmit. * Partial state (one event present, other missing) returns true — * addProxyHooks will repair it on next enable. */ export function hasProxyHooks(input: string | Settings): boolean { const settings: Settings = typeof input === 'string' ? JSON.parse(input) as Settings : input; return PROXY_HOOK_EVENTS.some((event) => hasHook(settings, event, isProxyHook)); } // ─── Health-check identity helper ──────────────────────────────────────────── /** * Return true when the raw health-check response body identifies our relay. * * The internal check `parsed['name'] === 'subswitch'` is correct here — 'subswitch' * is the internal package name (fine in code, not in user-facing output — see branding * note at the top of this file). Returns false on JSON parse failure, empty body, or a * mismatched name field. * * Note: the ensure-proxy shell hook has its own inline copy of this check — it is a * different language and cannot share the TypeScript module. */ export function isOurRelayBody(body: string): boolean { try { const parsed = JSON.parse(body) as Record; return parsed['name'] === 'subswitch'; } catch { return false; } } // ─── Dependency injection interface for runProxyPreflight ───────────────────── /** * Injectable dependencies for runProxyPreflight. * All I/O is behind this interface so every preflight branch is unit-testable. */ export interface ProxyPreflightDeps { /** Resolve the routing runtime bin path and (when validated) version. */ resolveProxyBin: () => Promise>; /** Check if a file exists at the given path. */ fileExists: (p: string) => Promise; /** Attempt a TCP connect to 127.0.0.1:port; true = accepted, false = refused/timeout. */ tcpConnectable: (port: number, timeoutMs: number) => Promise; /** HTTP GET with timeout. Ok(body) = success; Err(reason) = failure or timeout. */ httpGet: (url: string, timeoutMs: number) => Promise>; /** Read settings.json content; throws on I/O error. */ readSettingsJson: () => Promise; /** * Spawn `node doctor` with the given env; append stdout+stderr to logFile. * Resolves with the exit code (1 on timeout). */ spawnDoctor: ( binPath: string, env: Record, timeoutMs: number, logFile: string, ) => Promise; /** Called when a non-fatal warning is detected (e.g. ANTHROPIC_API_KEY present). */ onWarn?: (msg: string) => void; } export interface PreflightResult { binPath: string; npxWarning: boolean; /** True when the port is already hosting our relay — skip spawn, adopt. */ adopted: boolean; } /** * Preflight check ④ — settings.json readable and parseable, no foreign * ANTHROPIC_BASE_URL, plus the non-fatal ANTHROPIC_API_KEY warning. * * Extracted so the adopted-relay path and the free-port path run the identical * check (D-EFR-5): a healthy relay on the port must not buy an exemption from the * foreign-gateway refusal. Keeping it in one function is what stops the two paths * from drifting on which sub-checks they apply or which message they return. * * `swallowSettingsReadError` semantics are preserved by the caller-supplied dep: * when that flag is set (init), readSettingsJson() resolves to '{}' on I/O failure * instead of rejecting, so the read-failure branch is reachable only from runEnable. */ async function checkSettingsEnv( deps: ProxyPreflightDeps, port: number, ): Promise> { let settingsJson: string; try { settingsJson = await deps.readSettingsJson(); } catch { return Err('Could not read settings.json — check file permissions'); } let parsedSettings: Record; try { parsedSettings = JSON.parse(settingsJson) as Record; } catch { return Err('settings.json is malformed — fix it before enabling the proxy'); } if (readProxyEnvState(settingsJson, port) === 'foreign') { return Err( 'An existing ANTHROPIC_BASE_URL in settings.json points to a different gateway — Devflow will not overwrite it', ); } // API key warning (non-fatal) const envBlock = parsedSettings.env; if ( typeof envBlock === 'object' && envBlock !== null && !Array.isArray(envBlock) && typeof (envBlock as Record).ANTHROPIC_API_KEY === 'string' ) { deps.onWarn?.( 'ANTHROPIC_API_KEY is set in settings.json — requests will use that key through the local relay', ); } return Ok(undefined); } /** * Run preflight checks before enabling the Devflow proxy. * * Checks (in order): * ① Routing runtime bin resolvable. * ② ~/.codex/auth.json exists. * ③ Port probe: free → OK; accepting → health check → adopt or fail. * ④ settings.json parseable; ANTHROPIC_BASE_URL not pointing elsewhere; API key warn. * Runs on BOTH outcomes of ③ that can proceed — adopted relay and free port * (D-EFR-5) — via the shared `checkSettingsEnv` helper. * * Doctor is deliberately excluded from preflight: the relay's doctor subcommand * probes the relay port — a not-yet-started relay makes that probe fail (exit 1). A * pre-spawn gate is therefore always unsatisfiable on a cold path. Doctor now runs in * runPostSpawnVerification, after the relay is confirmed up. See D-EFR-2. * * Returns Ok(PreflightResult) on success, Err(message) on any check failure. */ export async function runProxyPreflight( port: number, codexAuthPath: string, configPath: string, logPath: string, deps: ProxyPreflightDeps, ): Promise> { // ① Routing runtime bin const binResult = await deps.resolveProxyBin(); if (!binResult.ok) return Err(binResult.error); const { binPath, npxWarning } = binResult.value; // ② Codex auth const codexAuthExists = await deps.fileExists(codexAuthPath); if (!codexAuthExists) { return Err('Sign in to the Codex CLI first (codex login)'); } // ③ Port probe const portAccepting = await deps.tcpConnectable(port, PROBE_TIMEOUT_MS); if (portAccepting) { // Port is up — check health identity const healthResult = await deps.httpGet( `${proxyBaseUrl(port)}/__subswitch/health`, PROBE_TIMEOUT_MS, ); if (healthResult.ok && isOurRelayBody(healthResult.value)) { // D-EFR-5: run check ④ BEFORE the adopted early-return. The old order // (adopted-return first, settings check only when the port was free) let a // healthy relay on the port silently skip the foreign-gateway refusal entirely. const settingsCheck = await checkSettingsEnv(deps, port); if (!settingsCheck.ok) return Err(settingsCheck.error); return Ok({ binPath, npxWarning, adopted: true }); } // Port accepting but health timed out, failed, or not our relay return Err( `port ${port} is in use by another application — pick a different port with \`devflow proxy --enable --port \``, ); } // Port refused — free to proceed // ④ Settings.json check const settingsCheck = await checkSettingsEnv(deps, port); if (!settingsCheck.ok) return Err(settingsCheck.error); return Ok({ binPath, npxWarning, adopted: false }); } // ─── Production dependency implementations ──────────────────────────────────── /** Production TCP connect implementation. */ async function realTcpConnectable(port: number, timeoutMs: number): Promise { return new Promise((resolve) => { const socket = net.createConnection({ host: '127.0.0.1', port, timeout: timeoutMs }); socket.on('connect', () => { socket.destroy(); resolve(true); }); socket.on('error', () => { socket.destroy(); resolve(false); }); socket.on('timeout', () => { socket.destroy(); resolve(false); }); }); } /** * Production HTTP/HTTPS GET implementation — selects module from URL scheme. * * Three resource bounds: * • Wall-clock total deadline: fires when 'end' never arrives (SSE / trickle server). * `--disable` probes precisely the port Devflow no longer owns, so any local * service that trickles bytes could pin the CLI forever without this bound. * • 64 KB body cap: aborts before accumulating unbounded memory. * • res.on('error') listener: response-stream errors are caught, not ignored. * * Exported for reliability tests. */ export async function realHttpGet(url: string, timeoutMs: number): Promise> { const mod = url.startsWith('https://') ? https : http; return new Promise((resolve) => { let settled = false; const settle = (r: Result): void => { if (settled) return; settled = true; resolve(r); }; // Wall-clock deadline — independent of the per-chunk socket idle timeout below. const wallClock = setTimeout(() => { req.destroy(); settle(Err('deadline exceeded')); }, timeoutMs); wallClock.unref(); const req = mod.get(url, { timeout: timeoutMs }, (res) => { let bodyBytes = 0; let body = ''; res.on('data', (chunk: Buffer) => { bodyBytes += chunk.length; if (bodyBytes > BODY_CAP_BYTES) { res.destroy(); req.destroy(); clearTimeout(wallClock); settle(Err('response too large')); return; } body += chunk.toString(); }); res.on('end', () => { clearTimeout(wallClock); settle(Ok(body)); }); res.on('error', (err: Error) => { clearTimeout(wallClock); settle(Err(err.message)); }); }); req.on('error', (err: Error) => { clearTimeout(wallClock); settle(Err(err.message)); }); req.on('timeout', () => { req.destroy(); clearTimeout(wallClock); settle(Err('timeout')); }); }); } /** Production doctor subprocess implementation. */ async function realSpawnDoctor( binPath: string, env: Record, timeoutMs: number, logFile: string, ): Promise { // openProxyLog: 0700 parent dir + 0600 file creation + best-effort chmod for // pre-existing wider modes (SEC-2). Non-fatal on chmod failure. const logFd = await openProxyLog(logFile); try { return await new Promise((resolve) => { const proc = cpSpawn(process.execPath, [binPath, 'doctor'], { env, stdio: ['ignore', logFd.fd, logFd.fd], }); let resolved = false; const timer = setTimeout(() => { if (!resolved) { resolved = true; proc.kill(); // SIGTERM — ask the process to terminate gracefully // A SIGTERM-trapping child keeps the event loop alive (no unref on // proc here, since we are awaiting the promise). Schedule a SIGKILL escalation // after a short grace period. The escalation timer is unref()'d so it never // prevents the CLI from exiting on its own if the process exits first. const sigkillTimer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* already dead — ignore */ } }, 2000); sigkillTimer.unref(); resolve(1); } }, timeoutMs); proc.on('close', (code) => { if (!resolved) { resolved = true; clearTimeout(timer); resolve(code ?? 1); } }); // OS-level spawn failure (EMFILE, ENOMEM, EAGAIN) must be handled — an // unhandled 'error' event becomes an uncaught exception. Resolve(1) so the // finally block closes logFd and callers get a clean failure path. proc.on('error', () => { if (!resolved) { resolved = true; clearTimeout(timer); resolve(1); } }); }); } finally { await logFd.close(); } } // ─── Production preflight deps factory ─────────────────────────────────────── /** * Options for buildRealPreflightDeps. * Captures the deliberate caller-specific difference in readSettingsJson behaviour. */ export interface BuildRealPreflightDepsOptions { /** Absolute path to ~/.claude/settings.json. */ settingsPath: string; /** Called on non-fatal preflight warnings (e.g. ANTHROPIC_API_KEY present). */ onWarn?: (msg: string) => void; /** * When true, readSettingsJson swallows I/O errors and returns '{}' instead of * throwing. Set to true for init.ts (which writes settings.json itself and should * tolerate an absent file); leave false (default) for runEnable where a read error * is surfaced to the user. */ swallowSettingsReadError?: boolean; } /** * Build the real (production) ProxyPreflightDeps from the given options. * Centralises the three private implementations so both runEnable and init.ts * can consume them without byte-identical inline copies. * * Pure configuration factory; I/O implementations factored once. */ export function buildRealPreflightDeps(opts: BuildRealPreflightDepsOptions): ProxyPreflightDeps { const { settingsPath, onWarn, swallowSettingsReadError = false } = opts; return { resolveProxyBin, fileExists: async (filePath: string) => { try { await fs.access(filePath); return true; } catch { return false; } }, tcpConnectable: realTcpConnectable, httpGet: realHttpGet, readSettingsJson: swallowSettingsReadError ? async () => { try { return await fs.readFile(settingsPath, 'utf-8'); } catch { return '{}'; } } : () => fs.readFile(settingsPath, 'utf-8'), spawnDoctor: realSpawnDoctor, onWarn, }; } // ─── Injectable spawn-and-wait helper ──────────────────────────────────────── /** * Injectable dependencies for spawnRelayAndWaitForPort. * All I/O is behind this interface so every relay spawn path is unit-testable. */ export interface SpawnAndWaitDeps { /** Ask the installed relay to detach. Undefined means it cannot detach. */ tryDetach?: (binPath: string, port: number, env: Record) => Promise; /** Open logPath for appending. Returns fd + close function. */ openLog: (logPath: string) => Promise<{ fd: number; close: () => Promise }>; /** * Spawn the relay process as a detached background process. * The implementation MUST attach `onError` via `proc.on('error', onError)` before * returning — this is a required invariant. Returns the spawned process pid. */ spawnProcess: (opts: { execPath: string; args: string[]; env: Record; stdioFd: number; /** Called on OS-level spawn failure (EMFILE, ENOMEM, EAGAIN). */ onError: (err: Error) => void; }) => { pid?: number }; /** Write pid to file. Failures are non-fatal (caller treats as best-effort). */ writePid: (pidPath: string, pid: number) => Promise; /** Sleep ms milliseconds. */ sleep: (ms: number) => Promise; /** * Check if a process is alive via signal 0. Returns false when dead. * Production: wraps process.kill(pid, 0); never throws. */ isProcessAlive: (pid: number) => boolean; /** Attempt a TCP connect to 127.0.0.1:port. True = accepted. */ tcpConnectable: (port: number, timeoutMs: number) => Promise; } type RelayStartFailure = { ok: false; reason: string }; type DetachedRelayResult = { ok: true; reportedPid?: number } | RelayStartFailure; /** Only a relay started by Devflow itself can have a spawnedPid. */ export type SpawnRelayResult = { ok: true; spawnedPid?: number } | RelayStartFailure; /** * Spawn the relay (unless adopted) and wait up to 50×100ms for TCP accept. * * When `adopted` is true, the relay is already running — skip spawn entirely. * * Returns `{ ok: true }` when the port accepts connections. * Returns `{ ok: false }` when: * - relay never accepted after 50 probes (caller should rollback proxy.json) * - relay process died before the port came up * - OS-level spawn error (EMFILE, ENOMEM, EAGAIN) — always handled via the * injected onError callback, never an uncaught exception * * No process.exit() — returns Result; caller decides error handling. */ export async function spawnRelayAndWaitForPort( port: number, binPath: string, configPath: string, logPath: string, pidPath: string, adopted: boolean, deps: SpawnAndWaitDeps, ): Promise { if (adopted) { // Port already hosting our relay — skip spawn entirely, proceed to settings pass. return { ok: true }; } // Share the allowlisted environment across the version probe and both starts. const env = { ...scrubChildEnv(), SUBSWITCH_CONFIG: configPath }; const detached = await deps.tryDetach?.(binPath, port, env); if (detached !== undefined) { if (!detached.ok) return detached; // The launcher can report a relay that already owns the port. Record its PID only for status. if (detached.reportedPid !== undefined) await deps.writePid(pidPath, detached.reportedPid); return await deps.tcpConnectable(port, RELAY_SPAWN_PER_PROBE_TIMEOUT_MS) ? { ok: true } : { ok: false, reason: 'relay-not-started' }; } const logHandle = await deps.openLog(logPath); let spawnError: Error | undefined; const { pid } = deps.spawnProcess({ execPath: process.execPath, args: [binPath, 'serve'], env, stdioFd: logHandle.fd, // Captured here; breaks the wait loop on the next iteration onError: (err) => { spawnError = err; }, }); // Parent closes its copy; the spawned child retains the fd through the OS await logHandle.close(); if (pid !== undefined) { // Non-fatal: best-effort pid record for devflow proxy --status await deps.writePid(pidPath, pid); } // Bounded wait: ≤RELAY_SPAWN_MAX_PROBES×100ms (5s max) for TCP accept let portUp = false; for (let i = 0; i < RELAY_SPAWN_MAX_PROBES; i++) { await deps.sleep(RELAY_SPAWN_PROBE_INTERVAL_MS); if (spawnError !== undefined) { // OS-level error fired — no point waiting; relay will never start break; } if (pid !== undefined && !deps.isProcessAlive(pid)) { // Process died before port came up — check for EADDRINUSE race // (another session may have started and already owns the port) if (await deps.tcpConnectable(port, RELAY_SPAWN_PER_PROBE_TIMEOUT_MS)) { portUp = true; } break; } if (await deps.tcpConnectable(port, RELAY_SPAWN_PER_PROBE_TIMEOUT_MS)) { portUp = true; break; } } if (!portUp) { return { ok: false, reason: 'relay-not-started' }; } return { ok: true, spawnedPid: pid }; } async function tryDetachedRelayStart( binPath: string, port: number, env: Record, cwd: string, ): Promise { if (process.platform !== 'darwin' && process.platform !== 'linux') return undefined; const version = await execFileAsync(process.execPath, [binPath, '--version'], { env, timeout: RELAY_VERSION_TIMEOUT_MS, killSignal: 'SIGKILL', maxBuffer: 2048, }).catch(() => undefined); const match = version?.stdout.match(/([0-9]+)\.([0-9]+)\.[0-9]+/); if (!match || (Number(match[1]) === 0 && Number(match[2]) < 9)) return undefined; // The launcher owns the readiness wait and the relay owns its logs. return new Promise((resolve) => { const proc = cpSpawn(process.execPath, [binPath, 'serve', '--detach', '--port', String(port)], { cwd, env, stdio: ['ignore', 'pipe', 'ignore'], }); let stdout: string | undefined = ''; proc.stdout.on('data', (chunk: Buffer) => { if (stdout !== undefined) { stdout = stdout.length + chunk.length <= 32 ? stdout + chunk.toString() : undefined; } }); const failed: RelayStartFailure = { ok: false, reason: 'relay-not-started' }; const timer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* best effort */ } proc.stdout.destroy(); proc.unref(); resolve(failed); }, RELAY_DETACH_DEADLINE_MS); const finish = (result: DetachedRelayResult): void => { clearTimeout(timer); resolve(result); }; proc.once('error', () => finish(failed)); proc.once('close', (code) => { if (code !== 0) { finish(failed); return; } const pid = stdout !== undefined && /^[0-9]+\n?$/.test(stdout) ? Number(stdout) : 0; finish({ ok: true, reportedPid: pid > 0 && pid <= 0x7fffffff ? pid : undefined }); }); }); } /** Build the real (production) SpawnAndWaitDeps. Not exported — internal to runEnable. */ function buildRealSpawnAndWaitDeps(devflowDir: string): SpawnAndWaitDeps { return { tryDetach: (binPath, port, env) => tryDetachedRelayStart(binPath, port, env, devflowDir), openLog: async (logPath) => { // Rotate only before legacy start, before the relay holds an append fd. await rotateProxyLogIfLarge(logPath); // openProxyLog: 0700 parent dir + 0600 file creation + best-effort chmod (SEC-2). const handle = await openProxyLog(logPath); return { fd: handle.fd, close: () => handle.close() }; }, spawnProcess: ({ execPath, args, env, stdioFd, onError }) => { const proc = cpSpawn(execPath, args, { detached: true, stdio: ['ignore', stdioFd, stdioFd], env, }); // Attach error handler before unref so OS-level failures are caught proc.on('error', onError); proc.unref(); return { pid: proc.pid }; }, writePid: async (pidPath, pid) => { // Non-fatal: failure is inconvenient (--status loses pid) but not blocking try { await fs.writeFile(pidPath, String(pid), 'utf-8'); } catch { /* non-fatal */ } }, sleep: (ms) => new Promise((r) => setTimeout(r, ms)), isProcessAlive: (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } }, tcpConnectable: realTcpConnectable, }; } // ─── Post-spawn doctor verification ────────────────────────────────────────── /** * Injectable dependencies for runPostSpawnVerification. * All I/O is behind this interface so every doctor-gate branch is unit-testable. */ export interface PostSpawnDoctorDeps { /** * Spawn `node doctor` with the given env; append stdout+stderr to logFile. * Resolves with the exit code (1 on timeout). */ spawnDoctor: ( binPath: string, env: Record, timeoutMs: number, logFile: string, ) => Promise; /** * Kill the relay process by pid via SIGTERM. Must not throw — implementation wraps in try/catch. * Called only when spawnedPid is defined and doctor exits non-zero (self-spawned rollback only). */ killProcess: (pid: number) => void; /** * Write proxy.json with enabled:false for rollback. Called when doctor exits non-zero. * Best-effort — a write failure is non-fatal (secondary to the verification failure). */ writeDisabledProxyState: () => Promise; } /** * Run `node doctor` against the live relay and handle failure. * * @D-EFR-2 Doctor gates post-spawn, not pre-spawn: the relay's doctor subcommand * probes the relay port to confirm it is running — a not-yet-started relay makes * that probe fail (exit 1), so a pre-spawn gate is always unsatisfiable on a cold * path (the port is down by definition before spawn). Moving the gate post-spawn * means doctor runs against an already-live relay, turning "running: NO" into * "running: YES" on the healthy path, validating codex auth and TLS reachability. * * Kill-on-rollback is restricted to self-spawned relays (spawnedPid defined): an * adopted relay may be serving other live Claude Code sessions, so we must never * kill it. A just-spawned relay predates the settings pass, so no session is * routing through it — SIGTERM is safe (with a SIGKILL escalation in the caller). * * @param spawnedPid Pid of the relay we spawned; undefined when the relay was adopted. * @returns Ok(undefined) when doctor exits 0; Err(message) on failure. On failure the * rollback (writeDisabledProxyState) and conditional kill are applied before * returning — the caller does not need to do additional rollback. */ export async function runPostSpawnVerification( binPath: string, configPath: string, logPath: string, spawnedPid: number | undefined, deps: PostSpawnDoctorDeps, ): Promise> { // SEC-2: allowlist env for doctor — matches the relay spawn composition. const doctorEnv = { ...scrubChildEnv(), SUBSWITCH_CONFIG: configPath }; const doctorExit = await deps.spawnDoctor(binPath, doctorEnv, DOCTOR_TIMEOUT_MS, logPath); if (doctorExit === 0) return Ok(undefined); // Doctor failed — rollback proxy state and conditionally kill the relay. // Both are best-effort: write failure is secondary; kill failure means process already exited. await deps.writeDisabledProxyState(); if (spawnedPid !== undefined) { deps.killProcess(spawnedPid); } return Err(`Routing verification failed — see ${logPath}`); } // ─── Atomic settings mutation for enable ───────────────────────────────────── /** * Perform the single atomic settings.json pass for enable: * strip old hooks + env, then apply new hooks + env in one write. * * The writeSettingsFileAtomic call is guarded — ENOSPC/EACCES returns Err * instead of crashing with an unhandled rejection. * * Returns Ok(undefined) on success, Err(reason) on hard failure. */ async function applyEnableSettingsPass( settingsPath: string, devflowDir: string, port: number, ): Promise> { let settingsContent: string; try { settingsContent = await fs.readFile(settingsPath, 'utf-8'); } catch { // Missing settings.json is fine — start from an empty object settingsContent = '{}'; } let parsedSettings: Settings; try { parsedSettings = JSON.parse(settingsContent) as Settings; } catch { return Err('settings.json is malformed — fix it before enabling the proxy'); } // Atomic 4-call settings mutation: strip stale entries, then apply fresh ones. // Strip is scoped to `port` (the new port being applied). The apply // call below always overwrites ANTHROPIC_BASE_URL regardless, so the strip // here primarily removes any exact-port match before the write-set cycle. removeProxyHooks(parsedSettings); _stripProxyEnvFromObject(parsedSettings, port); addProxyHooks(parsedSettings, devflowDir); _applyProxyEnvToObject(parsedSettings, port); try { await writeSettingsFileAtomic(settingsPath, JSON.stringify(parsedSettings, null, 2) + '\n'); } catch (err) { return Err( `Could not write settings.json: ${err instanceof Error ? err.message : String(err)}`, ); } return Ok(undefined); } // ─── PID-to-port identity binding ───────────────────────────────────────────── /** * Resolve the PID of the process currently listening on the given TCP port. * * @D-EFR-5 PID-port identity gate: signal 0 proves a PID exists; a health * check proves some process on the port is our relay. Neither alone proves * the pid-file PID *is* the listening process. A recycled PID can fool both * checks simultaneously. The fix: use lsof to resolve the listening PID * directly and require it to equal the pid-file PID before any signal. * * lsof is the canonical tool on darwin and is commonly available on linux. * On unsupported platforms or when lsof is absent/restricted, returns null * so the caller fails safe (identity-unconfirmed) rather than throwing. * * On darwin and linux: `lsof -nP -iTCP: -sTCP:LISTEN -t` * -n no host-name resolution -P no port-name resolution * -sTCP:LISTEN only LISTEN-state sockets -t PIDs only * * Fixed argument array — port is validated as a safe integer * by the caller before this function is invoked; it is never interpolated * into a shell string. * * Returns null when: * • Platform is not darwin or linux * • lsof is not on PATH or returns a non-zero exit code (EPERM, etc.) * • Zero processes are listening on the port * • More than one PID is returned (ambiguous — fail safe) * • The single returned value is not a valid positive integer */ async function realResolveListeningPid(port: number): Promise { if (process.platform !== 'darwin' && process.platform !== 'linux') { return null; } return new Promise((resolve) => { // SEC: fixed argument list — port is a validated integer (1-65535). const proc = cpSpawn('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-t'], { stdio: ['ignore', 'pipe', 'ignore'], }); let stdout = ''; proc.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString(); }); // Spawn failure (ENOENT = lsof absent, EPERM = restricted) → degrade to null proc.on('error', () => resolve(null)); proc.on('close', () => { const lines = stdout.trim().split('\n').filter(Boolean); // Zero or more-than-one result: ambiguous → fail safe if (lines.length !== 1) { resolve(null); return; } const parsed = parseInt(lines[0].trim(), 10); resolve(Number.isInteger(parsed) && parsed > 0 ? parsed : null); }); }); } /** * Injectable dependencies for terminateRelay. * Separates the platform I/O (lsof) from the decision logic so tests can * exercise every branch without requiring a real lsof binary. */ export interface TerminateRelayDeps { /** * Return the PID of the process listening on the given TCP port, or null * when the platform is unsupported, lsof is absent, or the result is * ambiguous. Caller treats null as "identity cannot be confirmed". */ resolveListeningPid: (port: number) => Promise; } // ─── Shared status/disable helpers ─────────────────────────────────────────── /** Relay process state as observed by TCP probe + health check. */ type ProcessState = 'down' | 'running-ours' | 'port-squatted'; /** * Read and parse the relay PID file. Returns null on ENOENT, parse failure, or * invalid value — callers treat null as "no pid available". */ async function readPidFile(pidPath: string): Promise { try { const pidStr = await fs.readFile(pidPath, 'utf-8'); const pid = parseInt(pidStr.trim(), 10); return !isNaN(pid) && pid > 0 ? pid : null; } catch { return null; } } /** * Terminate the relay process recorded in the pid file, with identity confirmation. * * Protocol: * 1. Read the pid file — skip silently if absent. * 2. Check liveness (signal 0). * 3. Confirm identity — three signals, ALL must pass before signalling: * a. TCP probe: port is accepting connections. * b. Health check: the process on the port is our relay (`isOurRelayBody`). * c. PID-port binding (D-EFR-5): lsof confirms the pid-file PID is the * process listening on the port. If lsof is unavailable or ambiguous, * fail safe — return 'identity-unconfirmed' without signalling. * 4. SIGTERM → poll for death every 250 ms for up to 2 s (8 checks). * 5. SIGKILL → poll for death every 250 ms for up to 2 s (8 checks). * 6. Remove the pid file when the process is gone. * 7. Best-effort rmdir of .proxy-spawn.lock when stale. * * applies D-EFR-5: signal 0 and health check are independent facts; lsof * binds the pid-file PID to the port owner before any signal is sent. * All sub-operations are non-fatal; a kill failure never aborts disable. * Never process.exit() inside a finally-guarded scope (it would skip the finally). * * @param deps Optional injectable dependencies (default: real lsof implementation). * Provide a stub in tests to exercise every branch without a real binary. * * @returns 'killed' — relay stopped successfully. * 'not-running' — pid file absent or process already dead. * 'identity-unconfirmed' — pid alive but identity not positively established * (health or lsof mismatch); no signal sent. * 'kill-failed' — SIGTERM + SIGKILL sent but process still alive after grace. */ export async function terminateRelay( pidPath: string, spawnLockPath: string, port: number, deps: TerminateRelayDeps = { resolveListeningPid: realResolveListeningPid }, ): Promise<'killed' | 'not-running' | 'identity-unconfirmed' | 'kill-failed'> { // Step 1: read pid file const pid = await readPidFile(pidPath); if (pid === null) return 'not-running'; // Step 2: check liveness try { process.kill(pid, 0); } catch { // Process already dead try { await fs.unlink(pidPath); } catch { /* best-effort */ } return 'not-running'; } // Step 3: confirm identity — all three signals must pass (D-EFR-5) // // Signal (a): TCP probe — confirms the port is accepting connections at all. const portUp = await realTcpConnectable(port, PROBE_TIMEOUT_MS); let identityConfirmed = false; if (portUp) { // Signal (b): health check — confirms the process on the port is our relay. const healthResult = await realHttpGet( `${proxyBaseUrl(port)}/__subswitch/health`, PROBE_TIMEOUT_MS, ); const healthOk = healthResult.ok && isOurRelayBody(healthResult.value); if (healthOk) { // Signal (c): PID-port binding — lsof confirms the pid-file PID owns the port. // If lsof is absent, returns null → null !== pid → identityConfirmed stays false. // Failing safe is strictly better than signalling the wrong process. const listeningPid = await deps.resolveListeningPid(port); identityConfirmed = listeningPid === pid; } } if (!identityConfirmed) { return 'identity-unconfirmed'; } // Bounded poll helper: check if PID is alive every 250 ms, up to maxChecks iterations. // Returns true when the process is gone within the polling window. const pollDead = async (maxChecks: number): Promise => { for (let i = 0; i < maxChecks; i++) { await new Promise((resolve) => setTimeout(resolve, 250)); try { process.kill(pid, 0); } catch { return true; } } return false; }; // Step 4: SIGTERM → bounded 2 s wait (8 × 250 ms) try { process.kill(pid, 'SIGTERM'); } catch { /* already exited — race */ } const deadAfterTerm = await pollDead(8); if (!deadAfterTerm) { // Step 5: SIGKILL → bounded 2 s wait (8 × 250 ms) try { process.kill(pid, 'SIGKILL'); } catch { /* already exited — race */ } const deadAfterKill = await pollDead(8); if (!deadAfterKill) { return 'kill-failed'; } } // Step 6: remove pid file try { await fs.unlink(pidPath); } catch { /* best-effort */ } // Step 7: best-effort rmdir of spawn lock when stale try { await fs.rmdir(spawnLockPath); } catch { /* held by another session or absent — ignore */ } return 'killed'; } /** * Probe relay process state via TCP connect + health identity check. * Always probes — does not short-circuit when the feature is disabled. * This ensures `--status` surfaces the divergence case where the feature is * disabled but the relay process is still listening (the relay is not killed on * `--disable` for live-session continuity; it may outlive the disable operation). */ async function resolveProcessState(port: number): Promise { const portUp = await realTcpConnectable(port, PROBE_TIMEOUT_MS); if (!portUp) return 'down'; const healthResult = await realHttpGet( `${proxyBaseUrl(port)}/__subswitch/health`, PROBE_TIMEOUT_MS, ); // Uses shared isOurRelayBody helper (same logic as runProxyPreflight) if (healthResult.ok && isOurRelayBody(healthResult.value)) { return 'running-ours'; } // Port accepting but health timed out, failed, or not our relay return 'port-squatted'; } /** * Pure: compute the process log line from resolved state. * Returns null when no line should be emitted (dead pid + non-down processState). */ function formatProcessLine( processState: ProcessState, pidAlive: boolean, pidFromFile: number | null, port: number, ): { level: 'info' | 'warn'; msg: string } | null { if (pidFromFile !== null) { if (pidAlive) { if (processState === 'running-ours') { return { level: 'info', msg: `Process: ${color.green('running')} (pid ${pidFromFile}) — stop manually with: kill ${pidFromFile}`, }; } else if (processState === 'port-squatted') { return { level: 'warn', msg: `Process: ${color.yellow('port squatted by another app')} (pid ${pidFromFile} alive but port ${port} is not our relay)`, }; } else { return { level: 'info', msg: `Process: ${color.yellow('pid alive but port not responding')} (pid ${pidFromFile})`, }; } } // Pid dead if (processState === 'down') { return { level: 'info', msg: `Process: ${color.dim('down')} (last pid ${pidFromFile}, no longer running)`, }; } return null; // pid dead but port squatted/running — unusual, no line } // No pid file if (processState === 'running-ours') { return { level: 'info', msg: `Process: ${color.green('running')} (no pid file)` }; } else if (processState === 'port-squatted') { return { level: 'warn', msg: `Process: ${color.yellow('port squatted')} — port ${port} is in use by another application`, }; } else { return { level: 'info', msg: `Process: ${color.dim('down')}` }; } } // ─── Status formatters ──────────────────────────────────────────────────────── /** * Pure formatter for the external models status line shown by `devflow proxy --status`. * * Extracted to enable isolated testing without clack I/O. (AC-F6) */ export function formatExternalModelsLine(catalog: ExternalModelCatalog, logPath: string): string { if (catalog.known) { return `External models: ${color.cyan(catalog.selectableNames.join(', '))}`; } return `External models: ${color.dim('unavailable')} — see ${logPath}`; } /** * Pure formatter for the Codex auth status line shown by `devflow proxy --status`. * * Returns `{level, msg}` — level encodes the warn-on-unreadable rule so callers * need not re-derive it from `state.kind`. `unreadable` is the only state the user * must act on (the relay rejects requests at that point while a bare file-existence * check still reported success). Expiry is informational: the relay refreshes the * access token on its own, so an expired stamp on a healthy install is normal. * * @param now Injected for deterministic tests; pass `new Date()` in production. */ export function formatCodexAuthLine( state: CodexAuthState, authPath: string, now: Date, ): { level: 'info' | 'warn'; msg: string } { switch (state.kind) { case 'absent': return { level: 'info', msg: `Codex auth: ${color.dim('absent')} — run codex login` }; case 'unreadable': return { level: 'warn', msg: `Codex auth: ${color.red(`unreadable (${state.reason})`)} at ${authPath} — run codex login`, }; case 'present': { // authMode comes from the third-party ~/.codex/auth.json; strip // ANSI escapes and cap length before embedding in terminal output. const safeAuthMode = stripAnsi(state.authMode).slice(0, AUTH_MODE_MAX_LEN); const identity = `${safeAuthMode}, ${state.accountSuffix}`; const present = `Codex auth: ${color.green('present')} (${identity})`; if (state.expiresAt === undefined) return { level: 'info', msg: present }; const stamp = state.expiresAt.toISOString().slice(0, 10); const msg = state.expiresAt.getTime() <= now.getTime() ? `${present} — access token expired ${stamp}, refreshes on next request` : `${present} — access token valid through ${stamp}`; return { level: 'info', msg }; } default: { const exhaustive: never = state; void exhaustive; return { level: 'info', msg: '' }; } } } // ─── Port resolution ────────────────────────────────────────────────────────── /** * Resolve the effective port for enable. * * When portOption is undefined (--port flag not provided by the user), falls back to * priorPort from proxy.json. This is the remembered-port path: a user who enabled on * port 5000, disabled, then re-enables without --port correctly reuses 5000. * * @param portOption Commander --port value; undefined when flag not provided * @param priorPort Last-used port from proxy.json (or DEFAULT_PROXY_PORT) */ export function resolvePort( portOption: string | undefined, priorPort: number, ): Result { if (portOption === undefined) return Ok(priorPort); const parsed = parseInt(portOption, 10); if (isNaN(parsed) || parsed < 1 || parsed > 65535) { return Err(`Invalid port: ${portOption}`); } return Ok(parsed); } // ─── Command ────────────────────────────────────────────────────────────────── interface ProxyOptions { enable?: boolean; disable?: boolean; status?: boolean; port?: string; } export const proxyCommand = new Command('proxy') .description('Enable or disable external model routing (GPT models via your OpenAI/Codex subscription)') .option('--enable', 'Enable external model routing via the Devflow proxy') .option('--disable', 'Disable external model routing') .option('--status', 'Show proxy status') .option('--port ', 'Port for the local relay (default: remembered or 4141)') .action(async (options: ProxyOptions) => { // No flag → show status const hasFlag = options.enable || options.disable || options.status; if (!hasFlag) { await runStatus(); return; } if (options.status) { await runStatus(); return; } if (options.enable) { await runEnable(options.port); return; } if (options.disable) { await runDisable(); return; } }); // ─── Status ─────────────────────────────────────────────────────────────────── async function runStatus(): Promise { const devflowDir = getDevFlowDirectory(); const claudeDir = getClaudeDirectory(); const settingsPath = path.join(claudeDir, 'settings.json'); const home = getHomeDirectory(); const logPath = path.join(devflowDir, 'logs', 'proxy.log'); const pidPath = path.join(devflowDir, 'proxy.pid'); const codexAuthPath = path.join(home, '.codex', 'auth.json'); p.intro(color.bgBlue(color.white(' Devflow Proxy Status '))); // Feature state: manifest + proxy.json const manifest = await readGateManifest(devflowDir); const { record, manifestProxy } = codeModeManifestSignals(manifest); const proxyStateResult = await readProxyState(devflowDir); const proxyState = proxyStateResult.ok ? proxyStateResult.value : null; const manifestEnabled = manifest.kind === 'object' && manifestProxy; const stateEnabled = proxyState?.enabled ?? false; if (manifestEnabled !== stateEnabled) { p.log.warn( `Feature state drift: manifest says ${manifestEnabled ? color.green('enabled') : color.dim('disabled')}, ` + `proxy.json says ${stateEnabled ? color.green('enabled') : color.dim('disabled')} — run devflow proxy --enable or --disable to repair`, ); } const featureEnabled = manifestEnabled && stateEnabled; p.log.info( `Feature: ${featureEnabled ? color.green('enabled') : color.dim('disabled')}` + (proxyState?.port ? ` (port ${proxyState.port})` : ''), ); // Process state — always probe regardless of featureEnabled so that the // divergence case (feature disabled but relay still running) is visible. const port = proxyState?.port ?? DEFAULT_PROXY_PORT; const processState = await resolveProcessState(port); // Divergence: feature is disabled but the relay is still responding. // This is the expected state immediately after `--disable` — the relay // keeps serving any live Claude Code sessions whose env captured the URL. if (!stateEnabled && processState === 'running-ours') { p.log.warn( `Relay is still running on port ${port} even though external model routing is disabled. ` + `Live Claude Code sessions whose env captured the relay URL continue routing through it. ` + `Run ${color.cyan('devflow proxy --disable')} again to stop the relay, ` + `or restart Claude Code to clear the routed session.`, ); } const pidFromFile = await readPidFile(pidPath); let pidAlive = false; if (pidFromFile !== null) { try { process.kill(pidFromFile, 0); pidAlive = true; } catch { /* dead */ } } const processLine = formatProcessLine(processState, pidAlive, pidFromFile, port); if (processLine !== null) { if (processLine.level === 'warn') { p.log.warn(processLine.msg); } else { p.log.info(processLine.msg); } } // Env state const env = await readSettingsEnv(settingsPath); const envState = classifyProxyBaseUrl(env?.ANTHROPIC_BASE_URL, port); const envStateLabels: Record = { 'ours': color.green('set (our relay)'), 'ours-other-port': color.yellow('set (our relay, different port)'), 'foreign': color.red('set (foreign gateway — Devflow will not overwrite)'), 'absent': color.dim('not set'), }; p.log.info(`ANTHROPIC_BASE_URL: ${envStateLabels[envState]}`); for (const line of codeModeBlockers({ codeModeOn: isCodeModeOn(record, env), proxyOn: isProxyOn({ proxyJsonOn: !proxyStateResult.ok || stateEnabled, manifestProxy, urlState: envState }), trafficOn: isTrafficOn(record, env), })) p.log.warn(line); // Codex auth — inspect contents, not just existence. A file the relay would // reject (bad JSON, no account id) 401s every request while an existence check // still reports "present"; that gap is what this check closes. let codexAuth: CodexAuthState; try { codexAuth = inspectCodexAuth(await fs.readFile(codexAuthPath, 'utf-8')); } catch (err) { codexAuth = classifyCodexAuthReadError(err); } const codexAuthLine = formatCodexAuthLine(codexAuth, codexAuthPath, new Date()); if (codexAuthLine.level === 'warn') { p.log.warn(codexAuthLine.msg); } else { p.log.info(codexAuthLine.msg); } // Agent mapping count const mappingResult = await readAgentMapping(devflowDir); if (mappingResult.ok) { const count = countExternalMappedAgents(mappingResult.value); if (count > 0) { p.log.info(`External-mapped agents: ${color.cyan(String(count))}`); } else { p.log.info('External-mapped agents: none — use devflow agents to configure'); } } // External models registry (cache-only, zero spawns — avoids multi-second silent pause in --status) const cacheDir = modelCacheDir(devflowDir); // authoritative path from cache.ts const catalog = getExternalModelsCached(cacheDir); p.log.info(formatExternalModelsLine(catalog, logPath)); // Log path p.log.info(`Proxy log: ${color.dim(logPath)}`); if (featureEnabled && processState === 'running-ours') { p.note( `${color.cyan('devflow proxy --disable')} Disable external model routing\n` + `${color.cyan('devflow proxy --status')} Refresh status`, 'Management', ); } else { p.note( `${color.cyan('devflow proxy --enable')} Enable external model routing\n` + `${color.cyan('devflow proxy --status')} Refresh status`, 'Management', ); } } // ─── Enable ─────────────────────────────────────────────────────────────────── async function runEnable(portOption: string | undefined): Promise { const devflowDir = getDevFlowDirectory(); const claudeDir = getClaudeDirectory(); const settingsPath = path.join(claudeDir, 'settings.json'); const installDir = path.join(claudeDir, 'agents', 'devflow'); const home = getHomeDirectory(); const codexAuthPath = path.join(home, '.codex', 'auth.json'); const configPath = path.join(devflowDir, 'proxy-routing.json'); const logPath = path.join(devflowDir, 'logs', 'proxy.log'); const pidPath = path.join(devflowDir, 'proxy.pid'); const cacheDir = modelCacheDir(devflowDir); // authoritative path from cache.ts // Step 1: Read prior proxy.json (remembered port); --port flag overrides const priorStateResult = await readProxyState(devflowDir); const priorPort = priorStateResult.ok ? priorStateResult.value.port : DEFAULT_PROXY_PORT; const portResult = resolvePort(portOption, priorPort); if (!portResult.ok) { p.log.error(portResult.error); process.exitCode = 1; return; } const port = portResult.value; const signals = await readCodeModeSignals(claudeDir, devflowDir); if (!signals.ok || signals.value.env === undefined) { p.log.error(CODE_MODE_READ_FAILURE); process.exitCode = 1; return; } if (isCodeModeOn(signals.value.record, signals.value.env)) { p.log.error(PROXY_ENABLE_REFUSAL); process.exitCode = 1; return; } const s = p.spinner(); s.start('Running preflight checks...'); // Step 2: Write routing config await fs.mkdir(devflowDir, { recursive: true }); // SEC-2: mode 0o700 for the logs directory (new directories only; pre-existing // dirs are unaffected by mkdir). openProxyLog handles individual file mode. await fs.mkdir(path.join(devflowDir, 'logs'), { recursive: true, mode: 0o700 }); // Read existing routing config to preserve user-added anthropic/limits/logLevel/providers // blocks. A missing or malformed file falls back to clean defaults inside // buildRoutingConfigJson (non-fatal). let existingRoutingContent: string | undefined; try { existingRoutingContent = await fs.readFile(configPath, 'utf-8'); } catch { /* ENOENT or EACCES — fall through to clean defaults */ } try { await fs.writeFile(configPath, buildRoutingConfigJson(port, existingRoutingContent), 'utf-8'); } catch (err) { s.stop(color.red('Failed to write routing config')); p.log.error(`Could not write routing config: ${err instanceof Error ? err.message : String(err)}`); process.exitCode = 1; return; } // Step 3: Preflight checks (①–④: bin, codex auth, port probe, settings) // preflightDeps is saved so spawnDoctor can be reused in step 6 (post-spawn verification). const preflightDeps = buildRealPreflightDeps({ settingsPath, // runEnable propagates settings read errors (init.ts swallows — see swallowSettingsReadError) swallowSettingsReadError: false, onWarn: (msg) => { s.stop(''); p.log.warn(msg); s.start(''); }, }); const preflightResult = await runProxyPreflight( port, codexAuthPath, configPath, logPath, preflightDeps, ); if (!preflightResult.ok) { s.stop(color.red('Preflight failed')); p.log.error(preflightResult.error); process.exitCode = 1; return; } const { binPath, npxWarning, adopted } = preflightResult.value; // Shared best-effort rollback for steps 5–7: write proxy.json enabled:false so a // subsequent --enable attempt does not believe the relay is running. A write failure // here is always secondary to the primary failure — never surfaced to the user. // All captured variables (binPath, configPath, port, devflowDir) are resolved by // this point. const rollbackProxyState = async (): Promise => { await writeProxyState(devflowDir, buildProxyState({ enabled: false, port, binPath, configPath, devflowVersion: getDevflowVersion(), })); }; s.message('Writing proxy state...'); // Step 4: Write proxy.json enabled:true const newState = buildProxyState({ enabled: true, port, binPath, configPath, devflowVersion: getDevflowVersion(), }); const writeStateResult = await writeProxyState(devflowDir, newState); if (!writeStateResult.ok) { s.stop(color.red('Failed to write proxy state')); p.log.error(writeStateResult.error); process.exitCode = 1; return; } // Step 5: Spawn relay and wait for port if (!adopted) { s.message('Starting relay...'); } const spawnResult = await spawnRelayAndWaitForPort( port, binPath, configPath, logPath, pidPath, adopted, buildRealSpawnAndWaitDeps(devflowDir), ); if (!spawnResult.ok) { await rollbackProxyState(); s.stop(color.red('Relay failed to start')); p.log.error(`Proxy failed to start — check ${logPath}`); process.exitCode = 1; return; } const { spawnedPid } = spawnResult; // Step 6: Post-spawn doctor verification — runs against the live relay (see D-EFR-2). // Relay is confirmed up before this runs, so "running: YES" is the expected outcome. s.message('Verifying routing connection...'); const verifyResult = await runPostSpawnVerification( binPath, configPath, logPath, spawnedPid, { spawnDoctor: preflightDeps.spawnDoctor, // Best-effort SIGTERM + SIGKILL escalation after 2s grace period. // Only called when we spawned the relay (spawnedPid defined) — see D-EFR-2. killProcess: (pid) => { try { process.kill(pid, 'SIGTERM'); } catch { /* already exited — ignore */ } const sigkillTimer = setTimeout(() => { try { process.kill(pid, 'SIGKILL'); } catch { /* already exited — ignore */ } }, 2000); sigkillTimer.unref(); }, writeDisabledProxyState: rollbackProxyState, }, ); if (!verifyResult.ok) { // Rollback and conditional kill already applied inside runPostSpawnVerification s.stop(color.red('Routing verification failed')); p.log.error(verifyResult.error); process.exitCode = 1; return; } s.message('Updating settings...'); // Step 7: Atomic settings mutation const settingsResult = await applyEnableSettingsPass(settingsPath, devflowDir, port); if (!settingsResult.ok) { await rollbackProxyState(); s.stop(color.red('Cannot update settings')); p.log.error(settingsResult.error); process.exitCode = 1; return; } // Step 8: Sync manifest await syncManifestFeature(devflowDir, 'proxy', true); // Step 9: Reapply agent mapping const reapplyResult = await reapplyAgentMapping({ proxyEnabled: true, installDir, devflowDir, }); const mappedCount = reapplyResult.updated.length; // Warm the model cache UNDER the spinner so the wait is visible and // attributed. Strictly non-fatal — a cache failure must never affect the // enable result. The promise is awaited so Node can exit cleanly after // s.stop, instead of being held open ~200-600ms. s.message('Warming model cache...'); await discoverExternalModels(cacheDir, logPath).catch(() => { /* non-fatal */ }); s.stop(color.green('External model routing enabled')); for (const { message } of formatLinksSummary(reapplyResult)) p.log.warn(message); // D-P4-1: applies-on-restart — env var takes effect only for new sessions p.log.info(color.dim('Context-window enforcement disabled for relay-routed models — applies to new Claude Code sessions')); if (adopted) { p.log.info(`Relay already running on port ${port} — adopted`); } else { p.log.success(`Relay started on port ${port}`); } if (npxWarning) { p.log.warn('Relay binary resolved from npx cache — may not persist across reboots; run devflow init to reinstall'); } if (mappedCount > 0) { p.log.info(`Restored external model mapping for ${mappedCount} agent(s)`); } p.log.info(color.dim('Takes effect in new Claude Code sessions. Use devflow agents to configure per-agent models.')); } // ─── Disable ────────────────────────────────────────────────────────────────── async function runDisable(): Promise { const devflowDir = getDevFlowDirectory(); const claudeDir = getClaudeDirectory(); const settingsPath = path.join(claudeDir, 'settings.json'); const installDir = path.join(claudeDir, 'agents', 'devflow'); const pidPath = path.join(devflowDir, 'proxy.pid'); // Read prior state FIRST (before settings pass) to determine managed port. // applyDisableToSettings strips ANTHROPIC_BASE_URL only when the URL // port matches the port Devflow manages — callers must supply it. Reading // proxy.json here also consolidates state for Step 2 below. // // D-STRIP-1: readProxyState() cannot distinguish "file absent" from "file present // with the default port", so the env strip is gated on the file's existence — the // only evidence that Devflow ever wrote those vars. Must be read before Step 2 // creates the file. Hook removal is NOT gated: our hooks are ours to remove on // every path. const proxyManaged = await proxyJsonExists(devflowDir); const priorStateResult = await readProxyState(devflowDir); const priorState = priorStateResult.ok ? priorStateResult.value : null; const managedPort = priorState?.port ?? DEFAULT_PROXY_PORT; // Step 1: Settings pass (removeProxyHooks + stripProxyEnv, single atomic write) let settingsContent: string; try { settingsContent = await fs.readFile(settingsPath, 'utf-8'); } catch { settingsContent = '{}'; } let parsedSettings: Settings; try { parsedSettings = JSON.parse(settingsContent) as Settings; } catch { p.log.error('settings.json is malformed — fix it before disabling the proxy'); process.exitCode = 1; return; } const changed = applyProxyTeardownToSettings( parsedSettings, proxyManaged ? managedPort : undefined, ); if (changed) { // Guard ENOSPC/EACCES — unhandled rejection leaves proxy in partial state try { await writeSettingsFileAtomic(settingsPath, JSON.stringify(parsedSettings, null, 2) + '\n'); } catch (err) { p.log.error( `Could not write settings.json: ${err instanceof Error ? err.message : String(err)}`, ); process.exitCode = 1; return; } } // Step 2: Write proxy.json enabled:false (keep port/binPath/configPath) const disabledState = buildProxyState({ enabled: false, port: priorState?.port ?? DEFAULT_PROXY_PORT, binPath: priorState?.binPath ?? null, configPath: priorState?.configPath ?? null, devflowVersion: getDevflowVersion(), }); const writeDisabledResult = await writeProxyState(devflowDir, disabledState); if (!writeDisabledResult.ok) { p.log.error(`Could not write proxy state: ${writeDisabledResult.error}`); process.exitCode = 1; return; } // Step 3: Sync manifest await syncManifestFeature(devflowDir, 'proxy', false); // Step 4: Revert external agents to shipped defaults const revertResult = await revertExternalAgents({ installDir, devflowDir }); for (const { message } of formatLinksSummary(revertResult)) p.log.warn(message); p.log.success('External model routing disabled'); // Step 5: Terminate the relay process. // Identity is confirmed via TCP + health before signalling — a recycled PID // must never be killed. All sub-operations are non-fatal. const spawnLockPath = path.join(devflowDir, '.proxy-spawn.lock'); const terminateResult = await terminateRelay(pidPath, spawnLockPath, managedPort); switch (terminateResult) { case 'killed': p.log.info('Relay process stopped.'); break; case 'not-running': p.log.info(color.dim('Relay process was not running.')); break; case 'identity-unconfirmed': p.log.warn( `PID from proxy.pid is alive but the relay identity could not be confirmed ` + `(port ${managedPort} is not responding as our relay). ` + `Inspect the process before stopping it manually.`, ); break; case 'kill-failed': p.log.warn( `Relay process (pid recorded in proxy.pid) did not stop after SIGTERM + SIGKILL. ` + `It may still be running — check with: kill -0 `, ); break; } // Always-print warning: already-running Claude Code sessions captured // ANTHROPIC_BASE_URL in their process env before the disable. The env var // is now stripped from settings.json so NEW sessions will not route, but // any session that was open during enable continues routing until restarted. p.log.warn( 'Already-running Claude Code sessions remain routed through the relay until they are restarted. ' + 'Restart Claude Code to fully stop routing in those sessions.', ); }