diff --git a/.github/scripts/check-proxy-port-fallbacks.sh b/.github/scripts/check-proxy-port-fallbacks.sh index 7b0d6a1b1e..f76348da9b 100755 --- a/.github/scripts/check-proxy-port-fallbacks.sh +++ b/.github/scripts/check-proxy-port-fallbacks.sh @@ -49,11 +49,15 @@ # opencode.jsonc door shell), so its row is gone from the table below, # same pattern as the 2026-10-30 retirements; bin/design-code-proxy.mjs # remained as history until the 2026-11-06 proxy-infra decommission -# removed it. The codex door program (:18744) is NOT retired — -# only its opencode.jsonc provider was (1dad07b4a re-seated the -# openai-codex routes onto openai-plan) — so the CODEX row keeps its -# let and bin/ fallback checks with has_config "no": there is no -# baseURL left in opencode.jsonc for it to match. +# removed it. The codex door +# (:18744) was retired 2026-11-06 (Drew, proxy-infra +# decommission) the same way -- let, units, session var, bin +# program, launcher and its row below removed in one change. +# The fork's native openai provider replaced the bridge: its +# opencode.jsonc providers were deleted 2026-11-03 (1dad07b4a +# re-seated the openai-codex routes onto openai-plan) and the +# door's credential sync was re-homed into the fork +# (opencode#1468), leaving the door with no consumers. # # Retired 2026-11-06 (Drew, proxy-infra decommission): the # commandcode door (:18748) and the claude-code door (:18749) are @@ -70,7 +74,6 @@ config_file="$repo_root/.opencode/opencode.jsonc" # var | let binding | proxy script | has an opencode.jsonc baseURL proxies=( - "CODEX_PROXY_PORT|codexProxyPort|bin/codex-proxy.mjs|no" "MUSE_PROXY_PORT|museProxyPort|bin/muse-proxy.mjs|yes" ) diff --git a/.github/workflows/bin-tests.yml b/.github/workflows/bin-tests.yml index ade54b18f3..2fe0f43167 100644 --- a/.github/workflows/bin-tests.yml +++ b/.github/workflows/bin-tests.yml @@ -4,8 +4,8 @@ name: bin tests # # Test verification for the bin/ provider proxies (#6081). # -# 13 of the 14 bin/*.test.mjs suites — the regression tests for the -# live provider proxies in bin/ (muse-proxy, codex-proxy, +# 12 of the 13 bin/*.test.mjs suites — the regression tests for the +# live provider proxies in bin/ (muse-proxy, # proxy-supervise, ...) — were run by # no workflow; only bin/check-opencode-metered-providers.test.mjs # had wiring (opencode-config-guard). The rest executed only when a diff --git a/.opencode/opencode.jsonc b/.opencode/opencode.jsonc index 885d480582..c6ad7bb322 100644 --- a/.opencode/opencode.jsonc +++ b/.opencode/opencode.jsonc @@ -527,8 +527,9 @@ // "openai": model catalog maintained by sync-models in the runtime overlay (~/.local/state/opencode/opencode-runtime.jsonc) — see code#4544. // "openai-codex": retired 2026-11-03 -- definition deleted after its // route legs were re-seated onto openai-plan (see the note at - // disabled_providers). The codex door program (:18744) is untouched; - // its own retirement stays with the #1154 cutover. + // disabled_providers). The codex door program (:18744) was retired + // 2026-11-06 in the proxy-infra decommission, completing the + // #1154 cutover. // "open-design" (the design-code door shell, :18746): the commented-out // proxy block preserved here since 2026-10-25 was DELETED 2026-11-03 // (Drew, direct order) together with the door's persona routes below. diff --git a/bin/codex-proxy.mjs b/bin/codex-proxy.mjs deleted file mode 100755 index 8027b668b4..0000000000 --- a/bin/codex-proxy.mjs +++ /dev/null @@ -1,1435 +0,0 @@ -#!/usr/bin/env node -import http from 'node:http'; -import net from 'node:net'; -import { spawn, execFile } from 'node:child_process'; -import { createRequire } from 'node:module'; -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import path from 'node:path'; -import os from 'node:os'; -import { parseProxyPort } from './proxy-port.mjs'; -import { listenTarget } from './socket-activation.mjs'; -import { createRequestBodyCollector } from './request-body.mjs'; -import { createStreamDecoder } from './stream-decode.mjs'; - -const PORT = parseProxyPort('CODEX_PROXY_PORT', 18744); -const HOST = process.env.CODEX_PROXY_HOST || '127.0.0.1'; -const DEFAULT_EXEC_TURN_TIMEOUT_MS = 300 * 1000; -const EXEC_TURN_KILL_GRACE_MS = 3000; -const MAX_TIMER_DELAY_MS = 2 ** 31 - 1; -const EXEC_TURN_TIMEOUT_MS = (() => { - const raw = process.env.CODEX_PROXY_EXEC_TURN_TIMEOUT_MS; - if (raw === undefined) return DEFAULT_EXEC_TURN_TIMEOUT_MS; - - const parsed = Number(raw); - if ( - !/^\d+$/.test(raw) || - !Number.isSafeInteger(parsed) || - parsed <= 0 || - parsed > MAX_TIMER_DELAY_MS - ) { - console.warn( - `[codex-proxy] invalid CODEX_PROXY_EXEC_TURN_TIMEOUT_MS; using ${DEFAULT_EXEC_TURN_TIMEOUT_MS}ms` - ); - return DEFAULT_EXEC_TURN_TIMEOUT_MS; - } - return parsed; -})(); - -// Publish the bound endpoint so other tools can find this proxy without -// knowing its port in advance: $XDG_STATE_HOME//endpoint.json -// (default ~/.local/state//endpoint.json), written on listen, -// removed on exit. -const publishEndpoint = () => { - try { - const stateHome = - process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'); - const dir = path.join(stateHome, 'codex-proxy'); - fs.mkdirSync(dir, { recursive: true }); - const file = path.join(dir, 'endpoint.json'); - fs.writeFileSync( - `${file}.tmp`, - JSON.stringify({ host: HOST, port: PORT, pid: process.pid, url: `http://${HOST}:${PORT}` }) + '\n', - ); - fs.renameSync(`${file}.tmp`, file); - const cleanup = () => { - try { - fs.unlinkSync(file); - } catch {} - }; - process.on('exit', cleanup); - process.on('SIGTERM', () => { - cleanup(); - process.exit(0); - }); - process.on('SIGINT', () => { - cleanup(); - process.exit(0); - }); - } catch {} -}; - -// Synchronize freshly refreshed ChatGPT OAuth tokens from Codex to OpenCode SQLite DB. -// This sync was silently dead from the day it shipped, for two independent -// reasons (#2533): -// 1. It built its Python child as a shell string, `python3 -c` + -// JSON.stringify(script). JSON.stringify encodes newlines as literal -// backslash-n, which the shell does not expand inside double quotes, so -// Python received one line full of literal \n and died with a SyntaxError -// on every call; stdio:'ignore' plus an empty catch swallowed it. -// 2. In the deployed service environment there is no python3 on PATH at all -// (NixOS: python3 lives in the user profile, which the proxy unit's PATH -// does not include), so the child could not even have spawned. -// The sync therefore runs in-process via node:sqlite — no shell, no child -// process, no interpreter on PATH, no token interpolation. Only the ACTIVE -// base `openai` credential row is ever touched (never the inactive second -// row, never `openai.alternate`), and both outcomes are logged: a failed sync -// must never again be indistinguishable from a successful one. -const syncCodexTokensToOpenCode = () => { - // Cutover switch for opencode#1154: the fork's in-server credential sync - // (credential/codex-sync) replaces this sync as the credential store's - // writer. CODEX_PROXY_TOKEN_SYNC=0 turns this door's sync off so the two - // never write the openai credential row in alternation; the listen callback - // logs the disabled state once at startup. - if (process.env.CODEX_PROXY_TOKEN_SYNC === '0') return; - let db = null; - try { - const codexAuthPath = `${process.env.HOME}/.codex/auth.json`; - const dbPath = `${process.env.HOME}/.local/share/opencode/opencode.db`; - if (!fs.existsSync(codexAuthPath) || !fs.existsSync(dbPath)) return; - - const codexAuth = JSON.parse(fs.readFileSync(codexAuthPath, 'utf-8')); - const tokens = codexAuth.tokens; - if (!tokens || !tokens.access_token) return; - - // Lazy require: if node:sqlite is ever unavailable, the sync logs a - // visible failure instead of taking the whole proxy down at import time. - const { DatabaseSync } = createRequire(import.meta.url)('node:sqlite'); - db = new DatabaseSync(dbPath, { timeout: 5000 }); - const rows = db - .prepare("SELECT id, value FROM credential WHERE integration_id = 'openai' AND active = 1") - .all(); - const update = db.prepare('UPDATE credential SET value = ?, time_updated = ? WHERE id = ?'); - const now = Date.now(); - let updated = 0; - for (const row of rows) { - let val; - try { - val = JSON.parse(row.value); - } catch { - continue; - } - if (!val || val.type !== 'oauth') continue; - val.access = tokens.access_token; - if (tokens.refresh_token) val.refresh = tokens.refresh_token; - if (tokens.account_id) { - val.metadata = val.metadata || {}; - val.metadata.accountID = tokens.account_id; - } - val.expires = now + 30 * 86400 * 1000; - update.run(JSON.stringify(val), now, row.id); - updated += 1; - } - console.log(`[codex-proxy] codex-token-sync: updated ${updated} credential row(s)`); - } catch (err) { - console.error(`[codex-proxy] codex-token-sync FAILED: ${(err && err.message) || err}`); - } finally { - try { - if (db) db.close(); - } catch {} - } -}; - -// Static floor for the served model list (live-model rule, 2026-10-28): -// only the last-resort fallback. The served list is pulled LIVE from -// `codex debug models` (the CLI's own rendering of the upstream catalog; -// see refreshLiveModels below) with a 60s TTL cache and last-known-good -// fallback. All slugs the CLI reports are served, including -// visibility:"hide" ones (gpt-reserve, codex-auto-review) — this floor -// deliberately served them too. -const STATIC_MODELS = [ - { id: 'gpt-6.1-sol', name: 'GPT-6.1 Sol (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'], defaultEffort: 'medium' }, - { id: 'gpt-6-astra', name: 'GPT-6 Astra (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'], defaultEffort: 'medium' }, - { id: 'gpt-6-sol', name: 'GPT-6 Sol (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'], defaultEffort: 'medium' }, - { id: 'gpt-6-luna', name: 'GPT-6 Luna (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'low' }, - { id: 'gpt-5.6-sol', name: 'GPT-5.6 Sol (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'], defaultEffort: 'medium' }, - { id: 'gpt-5.6-terra', name: 'GPT-5.6 Terra (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'], defaultEffort: 'medium' }, - { id: 'gpt-5.6-luna', name: 'GPT-5.6 Luna (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'low' }, - { id: 'gpt-5.5', name: 'GPT-5.5 (codex)', efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'low' }, - { id: 'gpt-reserve', name: 'GPT Reserve (codex)', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'low' }, - { id: 'codex-auto-review', name: 'Codex Auto Review', efforts: ['low', 'medium', 'high', 'xhigh', 'max'], defaultEffort: 'medium' } -]; - -const findCodexBinary = () => { - // Explicit override first: the test suite points this at its stub so - // a host-installed codex can never shadow it (#694). - if (process.env.CODEX_PROXY_CODEX_BIN) return process.env.CODEX_PROXY_CODEX_BIN; - const candidates = [ - '/run/current-system/sw/bin/codex', - `${process.env.HOME}/.local/bin/codex`, - 'codex' - ]; - for (const c of candidates) { - if (c === 'codex' || fs.existsSync(c)) { - return c; - } - } - return 'codex'; -}; - -const CODEX_BIN = findCodexBinary(); - -// --- Live model list ------------------------------------------------------- -// `codex debug models` prints the CLI's current upstream catalog as JSON -// ({models:[{slug, display_name, supported_reasoning_levels:[{effort}], -// default_reasoning_level, visibility}]}). It answers in ~1s from the -// CLI's own fetch/cache, so the TTL is short (60s) and a stale read is -// refreshed inline; any failure serves the last-known-good (or floor). -const MODEL_LIST_TTL_MS = 60 * 1000; -let liveModelCache = { at: 0, models: null }; -let liveModelRefresh = null; - -const parseDebugModels = (text) => { - const parsed = JSON.parse(text); - const arr = Array.isArray(parsed) ? parsed : parsed.models; - if (!Array.isArray(arr)) throw new Error('debug models: no models array'); - const models = []; - for (const m of arr) { - if (!m || typeof m.slug !== 'string' || !m.slug) continue; - const efforts = (m.supported_reasoning_levels || []).map(r => r && r.effort).filter(Boolean); - if (efforts.length === 0) continue; - models.push({ - id: m.slug, - name: `${m.display_name || m.slug} (codex)`, - efforts, - defaultEffort: efforts.includes(m.default_reasoning_level) ? m.default_reasoning_level : efforts[0] - }); - } - if (models.length < 3) throw new Error(`debug models: only ${models.length} usable models`); - return models; -}; - -const refreshLiveModels = () => { - if (liveModelRefresh) return liveModelRefresh; - liveModelRefresh = new Promise((resolve) => { - execFile(CODEX_BIN, ['debug', 'models'], { - timeout: 30000, maxBuffer: 16 * 1024 * 1024, input: '' - }, (err, stdout) => { - liveModelRefresh = null; - if (!err) { - try { - liveModelCache = { at: Date.now(), models: parseDebugModels(stdout) }; - } catch (parseErr) { - console.warn(`[codex-proxy] live model parse failed (${parseErr.message}); serving last-known-good`); - } - } else { - console.warn(`[codex-proxy] \`codex debug models\` failed (${err.message}); serving last-known-good`); - } - resolve(liveModelCache.models); - }); - }); - return liveModelRefresh; -}; - -const getModelCatalog = async () => { - if (liveModelCache.models && Date.now() - liveModelCache.at <= MODEL_LIST_TTL_MS) { - return liveModelCache.models; - } - await refreshLiveModels(); - return liveModelCache.models || STATIC_MODELS; -}; - -// Synchronous view for code paths that cannot await: last-known-good or -// the static floor, with a background refresh triggered when stale. -const getModelCatalogSync = () => { - if (!liveModelCache.models || Date.now() - liveModelCache.at > MODEL_LIST_TTL_MS) { - refreshLiveModels(); - } - return liveModelCache.models || STATIC_MODELS; -}; - -// Transport selection (#480): 'app-server' (default) talks JSON-RPC to the -// long-running codex app-server daemon over its WebSocket-over-Unix control -// socket — no per-request CLI boot. 'exec-resume' is the previous warm -// path (per-turn `codex exec resume`); 'exec' is the original cold path. -// Any app-server failure before the response is committed falls back to -// exec-resume, then exec — a request never fails because the warm route did. -const TRANSPORT = (() => { - const t = (process.env.CODEX_PROXY_TRANSPORT || 'app-server').trim().toLowerCase(); - return ['app-server', 'exec-resume', 'exec'].includes(t) ? t : 'app-server'; -})(); - -const appServerSocketPath = () => - process.env.CODEX_APP_SERVER_SOCKET || - path.join(os.homedir(), '.codex', 'app-server-control', 'app-server-control.sock'); - -const resolveModelAndEffort = (requestedModel, requestedEffort, catalog = getModelCatalogSync()) => { - let rawModel = (requestedModel || '').trim(); - // Strip any provider prefix before '/' (e.g. 'openai-codex/', 'codex/', 'openai/', 'chatgpt/') - let modelStr = rawModel.replace(/^.*\//, '').toLowerCase().trim(); - let effort = requestedEffort ? requestedEffort.toLowerCase().trim() : null; - - // Check if model string ends with effort suffix - const possibleSuffixes = ['-ultra', '-xhigh', '-high', '-medium', '-low', '-max']; - for (const suffix of possibleSuffixes) { - if (modelStr.endsWith(suffix)) { - effort = suffix.slice(1); - modelStr = modelStr.slice(0, -suffix.length); - break; - } - } - - // Find base model config in the live (or last-known-good/floor) catalog. - // No requested model at all -> the catalog's first entry is the default. - // An explicitly requested but unknown id returns null: the caller answers - // a clean 400. It must NEVER silently fall back to a default model (a - // fleet proxy once served a different model than requested with HTTP 200). - const modelConfig = !modelStr - ? catalog[0] - : catalog.find(m => m.id === modelStr || m.id.replace(/-/g, '') === modelStr.replace(/-/g, '')); - if (!modelConfig) return null; - - // Resolve effort - if (!effort || !modelConfig.efforts.includes(effort)) { - effort = modelConfig.defaultEffort; - } - - return { - baseModel: modelConfig.id, - effort, - fullName: `${modelConfig.id}-${effort}` - }; -}; - -const formatPrompt = (messages) => { - if (!Array.isArray(messages) || messages.length === 0) return ''; - if (messages.length === 1 && messages[0].role === 'user' && typeof messages[0].content === 'string') { - return messages[0].content; - } - - const parts = []; - const systemMessages = messages.filter(m => m.role === 'system'); - const convoMessages = messages.filter(m => m.role !== 'system'); - - if (systemMessages.length > 0) { - const sysText = systemMessages.map(m => - typeof m.content === 'string' ? m.content : JSON.stringify(m.content) - ).join('\n\n'); - parts.push(`[System Instructions]\n${sysText}`); - } - - if (convoMessages.length > 0) { - const convoText = convoMessages.map(m => { - let role = m.role === 'assistant' ? 'Assistant' : (m.role === 'user' ? 'User' : m.role); - let text = ''; - if (typeof m.content === 'string') { - text = m.content; - } else if (Array.isArray(m.content)) { - text = m.content.map(c => c.text || JSON.stringify(c)).join('\n'); - } else if (m.content) { - text = JSON.stringify(m.content); - } - - if (m.tool_calls && Array.isArray(m.tool_calls)) { - const tcStr = m.tool_calls.map(tc => `[Tool Call: ${tc.function?.name || 'function'}(${tc.function?.arguments || ''})]`).join('\n'); - text = text ? `${text}\n${tcStr}` : tcStr; - } - if (m.role === 'tool') { - role = `Tool Result (${m.tool_call_id || 'result'})`; - } - - return `${role}: ${text}`; - }).join('\n\n'); - parts.push(convoText); - } - - return parts.join('\n\n'); -}; - -// --------------------------------------------------------------------------- -// Warm sessions (#480): conversation-keyed resumable `codex exec` sessions. -// -// Before this, every request spawned a fresh `codex exec --ephemeral` and -// re-flattened the whole conversation, so the model re-read the entire -// history on every turn. Now the first turn of a conversation runs WITHOUT -// --ephemeral (an ephemeral session leaves no rollout on disk and can -// never be resumed), captures the session id from the CLI's JSON event -// stream, and later turns of the same conversation run -// `codex exec resume ` with only the new tail. -// -// Conversations are keyed by sha256(resolved model/effort + system prompt -// + first user message): the proxy is stateless per request and that is -// all it can stably recognise a conversation by. The map is persisted next -// to endpoint.json (sessions.json in the same state dir) so a proxy -// restart does not cold-start every conversation, LRU-bounded to 64 -// entries with a 2h TTL. Any resume failure falls back to a full-history -// fresh run and re-keys the entry — a request never fails because resume -// failed. -// --------------------------------------------------------------------------- -const SESSION_TTL_MS = 2 * 60 * 60 * 1000; -const SESSION_MAX_ENTRIES = 64; - -const sessionStateDir = () => - path.join( - process.env.XDG_STATE_HOME || path.join(os.homedir(), '.local', 'state'), - 'codex-proxy' - ); - -let sessionMap = null; // Map - -const loadSessions = () => { - if (sessionMap) return sessionMap; - sessionMap = new Map(); - try { - const raw = JSON.parse( - fs.readFileSync(path.join(sessionStateDir(), 'sessions.json'), 'utf-8') - ); - const now = Date.now(); - for (const [key, entry] of Object.entries(raw)) { - if ( - entry && - (typeof entry.sessionId === 'string' || typeof entry.threadId === 'string') && - Array.isArray(entry.fedHashes) && - now - (entry.lastUsed || 0) <= SESSION_TTL_MS - ) { - sessionMap.set(key, entry); - } - } - } catch { - // No state yet — cold start. - } - return sessionMap; -}; - -const saveSessions = () => { - try { - const entries = [...loadSessions().entries()] - .sort((a, b) => (b[1].lastUsed || 0) - (a[1].lastUsed || 0)) - .slice(0, SESSION_MAX_ENTRIES); - sessionMap = new Map(entries); - const dir = sessionStateDir(); - fs.mkdirSync(dir, { recursive: true }); - const file = path.join(dir, 'sessions.json'); - fs.writeFileSync(`${file}.tmp`, JSON.stringify(Object.fromEntries(entries)) + '\n'); - fs.renameSync(`${file}.tmp`, file); - } catch { - // Persistence is best-effort; the in-memory map still works. - } -}; - -const messageText = (m) => { - if (typeof m.content === 'string') return m.content; - if (Array.isArray(m.content)) { - return m.content.map(c => c.text || JSON.stringify(c)).join('\n'); - } - return m.content ? JSON.stringify(m.content) : ''; -}; - -const messageHash = (m) => - crypto - .createHash('sha256') - .update( - `${m.role}\n${messageText(m)}\n${m.tool_calls ? JSON.stringify(m.tool_calls) : ''}\n${m.tool_call_id || ''}` - ) - .digest('hex'); - -const conversationKey = (messages, fullName) => { - const systemText = messages - .filter(m => m.role === 'system') - .map(messageText) - .join('\n\n'); - const firstUser = messages.find(m => m.role === 'user'); - return crypto - .createHash('sha256') - .update(`${fullName}\n${systemText}\n${firstUser ? messageText(firstUser) : ''}`) - .digest('hex'); -}; - -// Decide whether this request can resume a warm session. Returns -// { key, entry, tailMessages } or null for a full-history fresh run. -const planResume = (messages, fullName) => { - if (!Array.isArray(messages) || messages.length === 0) return null; - const key = conversationKey(messages, fullName); - const entry = loadSessions().get(key); - if (!entry) return null; - if (Date.now() - (entry.lastUsed || 0) > SESSION_TTL_MS) { - loadSessions().delete(key); - saveSessions(); - return null; - } - // The request must extend exactly what the session was fed: every - // previously fed message still present, unchanged, at the same index. - // A changed system prompt (or any edited/truncated history) fails here - // and falls back to a full run. - if (messages.length <= entry.fedCount || entry.fedHashes.length !== entry.fedCount) { - return null; - } - for (let i = 0; i < entry.fedCount; i++) { - if (messageHash(messages[i]) !== entry.fedHashes[i]) return null; - } - // The session already holds its own assistant replies, so the tail fed - // to `exec resume` is only the new non-assistant turns. - const tailMessages = messages.slice(entry.fedCount).filter(m => m.role !== 'assistant'); - if (!tailMessages.some(m => m.role === 'user' || m.role === 'tool')) return null; - return { key, entry, tailMessages }; -}; - -const recordSession = (key, sessionId, messages, threadId) => { - if (!key || (!sessionId && !threadId)) return; - const prev = loadSessions().get(key) || {}; - loadSessions().set(key, { - // An app-server thread id is a codex session id in the same rollout - // store, so either transport can warm the other: keep both fields - // pointing at the newest known id for the conversation. - sessionId: sessionId || threadId || prev.sessionId, - threadId: threadId || prev.threadId, - fedCount: messages.length, - fedHashes: messages.map(messageHash), - lastUsed: Date.now() - }); - saveSessions(); -}; - -const forgetThread = (key) => { - const entry = key && loadSessions().get(key); - if (entry && entry.threadId) { - delete entry.threadId; - saveSessions(); - } -}; - -const forgetSession = (key) => { - if (key && loadSessions().delete(key)) saveSessions(); -}; - -// --------------------------------------------------------------------------- -// App-server transport (#480): one persistent WebSocket-over-Unix-socket -// connection to the managed codex app-server daemon -// (~/.codex/app-server-control/app-server-control.sock, proven on the -// laptop's daemon 0.164.0: HTTP Upgrade handshake at any path, then plain -// JSON-RPC 2.0 in text frames; client frames must be masked). The daemon -// owns the ChatGPT login and stays warm, so a keyed follow-up turn is a -// single turn/start RPC — turn 2 measured 2.15s for gpt-5.6-luna against -// ~40-55s for a per-call `codex exec resume` boot. The stdio bridge -// (`codex app-server proxy`) was tried first and never answered an -// initialize in 180s against this daemon; the direct socket works and -// needs no child process at all. Node stdlib only (net + crypto). -// --------------------------------------------------------------------------- -const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; - -const wsAccept = (key) => - crypto.createHash('sha1').update(key + WS_GUID).digest('base64'); - -const wsEncodeFrame = (payload, opcode = 0x1) => { - const data = Buffer.isBuffer(payload) ? payload : Buffer.from(payload); - const mask = crypto.randomBytes(4); - let header; - if (data.length < 126) { - header = Buffer.from([0x80 | opcode, 0x80 | data.length]); - } else if (data.length < 65536) { - header = Buffer.alloc(4); - header[0] = 0x80 | opcode; - header[1] = 0x80 | 126; - header.writeUInt16BE(data.length, 2); - } else { - header = Buffer.alloc(10); - header[0] = 0x80 | opcode; - header[1] = 0x80 | 127; - header.writeBigUInt64BE(BigInt(data.length), 2); - } - const masked = Buffer.alloc(data.length); - for (let i = 0; i < data.length; i++) masked[i] = data[i] ^ mask[i % 4]; - return Buffer.concat([header, mask, masked]); -}; - -class AppServerClient { - constructor(socketPath) { - this.socketPath = socketPath; - this.sock = null; - this.ready = false; - this.nextId = 1; - this.pending = new Map(); // rpc id -> {resolve, reject} - this.turnStates = new Map(); // threadId -> turn state - this.loadedThreads = new Set(); - this.buffer = Buffer.alloc(0); - this.fragments = []; - this.handshaked = false; - } - - connect(timeoutMs = 10000) { - return new Promise((resolve, reject) => { - let settled = false; - const fail = (err) => { - if (!settled) { - settled = true; - try { this.sock && this.sock.destroy(); } catch {} - reject(err); - } - }; - const timer = setTimeout(() => fail(new Error('app-server connect timed out')), timeoutMs); - this.sock = net.createConnection(this.socketPath); - this.sock.on('error', (err) => { - if (!this.ready) fail(err); - else this.handleClose(err); - }); - this.sock.on('close', () => this.handleClose(new Error('app-server connection closed'))); - this.sock.on('connect', () => { - this.wsKey = crypto.randomBytes(16).toString('base64'); - this.sock.write( - `GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${this.wsKey}\r\nSec-WebSocket-Version: 13\r\n\r\n` - ); - }); - this.sock.on('data', (chunk) => { - this.buffer = Buffer.concat([this.buffer, chunk]); - if (!this.headersDone) { - const idx = this.buffer.indexOf('\r\n\r\n'); - if (idx === -1) return; - const head = this.buffer.subarray(0, idx).toString('utf-8'); - this.buffer = this.buffer.subarray(idx + 4); - if (!/^HTTP\/1\.1 101/.test(head) || !head.includes(wsAccept(this.wsKey))) { - clearTimeout(timer); - fail(new Error(`app-server handshake refused: ${head.split('\r\n')[0]}`)); - return; - } - this.headersDone = true; - this.handshaked = true; - // Drain any frames that arrived with the handshake response, - // then the initialize handshake + 'initialized' notification. - this.rpc('initialize', { - clientInfo: { name: 'codex-proxy', version: '1.0.0' }, - capabilities: { experimentalApi: true } - }).then(() => { - this.send({ method: 'initialized' }); - this.ready = true; - clearTimeout(timer); - settled = true; - resolve(this); - }, (err) => { clearTimeout(timer); fail(err); }); - this.drainFrames(); - return; - } - this.drainFrames(); - }); - }); - } - - handleClose(err) { - if (this.dead) return; - this.dead = true; - this.ready = false; - this.loadedThreads.clear(); - for (const { reject } of this.pending.values()) reject(err); - this.pending.clear(); - for (const st of this.turnStates.values()) st.fail(err); - this.turnStates.clear(); - if (appServerClient === this) appServerClient = null; - } - - send(obj) { - if (!this.sock || this.dead) throw new Error('app-server not connected'); - this.sock.write(wsEncodeFrame(JSON.stringify(obj))); - } - - drainFrames() { - for (;;) { - if (this.buffer.length < 2) return; - const b0 = this.buffer[0]; - const b1 = this.buffer[1]; - const fin = (b0 & 0x80) !== 0; - const opcode = b0 & 0x0f; - let len = b1 & 0x7f; - let off = 2; - if (len === 126) { - if (this.buffer.length < off + 2) return; - len = this.buffer.readUInt16BE(off); off += 2; - } else if (len === 127) { - if (this.buffer.length < off + 8) return; - len = Number(this.buffer.readBigUInt64BE(off)); off += 8; - } - if (b1 & 0x80) off += 4; // server frames are unmasked; skip mask if set - if (this.buffer.length < off + len) return; - const payload = this.buffer.subarray(off, off + len); - this.buffer = this.buffer.subarray(off + len); - if (opcode === 0x9) { // ping -> pong - try { this.sock.write(wsEncodeFrame(payload, 0xA)); } catch {} - continue; - } - if (opcode === 0x8) { - this.handleClose(new Error('app-server sent close frame')); - try { this.sock.destroy(); } catch {} - return; - } - this.fragments.push(payload); - if (!fin) continue; - const text = Buffer.concat(this.fragments).toString('utf-8'); - this.fragments = []; - this.onMessage(text); - } - } - - onMessage(text) { - let msg; - try { msg = JSON.parse(text); } catch { return; } - if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) { - const p = this.pending.get(msg.id); - if (p) { - this.pending.delete(msg.id); - if (msg.error) p.reject(new Error(msg.error.message || `RPC error ${msg.error.code}`)); - else p.resolve(msg.result); - } - return; - } - if (msg.id !== undefined && msg.method) { - // Server-initiated request (approvals, elicitations). The proxy runs - // threads with approvalPolicy 'never', so these should not occur; - // refuse politely instead of stalling the turn. - try { - this.sock.write(wsEncodeFrame(JSON.stringify({ - id: msg.id, - error: { code: -32601, message: 'unsupported by codex-proxy' } - }))); - } catch {} - return; - } - // Notification: route to the active turn on its thread. - const params = msg.params || {}; - const st = params.threadId && this.turnStates.get(params.threadId); - if (st) st.onNotification(msg.method, params); - } - - rpc(method, params, timeoutMs = 30000) { - return new Promise((resolve, reject) => { - const id = this.nextId++; - const timer = setTimeout(() => { - this.pending.delete(id); - reject(new Error(`app-server RPC ${method} timed out`)); - }, timeoutMs); - this.pending.set(id, { - resolve: (v) => { clearTimeout(timer); resolve(v); }, - reject: (e) => { clearTimeout(timer); reject(e); } - }); - try { - this.send({ id, method, params }); - } catch (err) { - clearTimeout(timer); - this.pending.delete(id); - reject(err); - } - }); - } -} - -let appServerClient = null; -let appServerConnecting = null; - -const ensureAppServer = async () => { - if (appServerClient && appServerClient.ready) return appServerClient; - if (appServerConnecting) return appServerConnecting; - appServerConnecting = (async () => { - const client = new AppServerClient(appServerSocketPath()); - await client.connect(); - console.log(`[codex-proxy] app-server connected: ${client.socketPath}`); - appServerClient = client; - return client; - })().finally(() => { appServerConnecting = null; }); - return appServerConnecting; -}; - -const resetAppServer = () => { - if (appServerClient) { - try { appServerClient.sock && appServerClient.sock.destroy(); } catch {} - appServerClient.handleClose(new Error('app-server reset')); - appServerClient = null; - } -}; - -// One turn on a daemon thread. Resolves (never rejects) like runCodexOnce. -const runAppServerTurn = (client, { threadId, text, baseModel, effort, prompt, emit }) => - new Promise((resolve) => { - let settled = false; - const done = (r) => { if (!settled) { settled = true; resolve(r); } }; - const state = { - content: '', - promptTokens: Math.max(1, Math.ceil((prompt || text).length / 4)), - completionTokens: 0, - cacheReadTokens: 0, - fail: (err) => { - client.turnStates.delete(threadId); - done({ ok: false, content: state.content, promptTokens: state.promptTokens, completionTokens: state.completionTokens, cacheReadTokens: state.cacheReadTokens, detail: err.message }); - }, - onNotification: (method, params) => { - if (method === 'item/agentMessage/delta' && typeof params.delta === 'string') { - state.content += params.delta; - if (emit) emit(params.delta); - } else if (method === 'item/completed' && params.item && params.item.type === 'agentMessage') { - if (!state.content && typeof params.item.text === 'string') state.content = params.item.text; - } else if (method === 'thread/tokenUsage/updated' && params.tokenUsage && params.tokenUsage.last) { - if (typeof params.tokenUsage.last.inputTokens === 'number') state.promptTokens = params.tokenUsage.last.inputTokens; - if (typeof params.tokenUsage.last.outputTokens === 'number') state.completionTokens = params.tokenUsage.last.outputTokens; - if (typeof params.tokenUsage.last.cachedInputTokens === 'number') state.cacheReadTokens = params.tokenUsage.last.cachedInputTokens; - } else if (method === 'turn/completed' && params.turn) { - client.turnStates.delete(threadId); - if (params.turn.status === 'failed') { - const detail = - (params.turn.error && (params.turn.error.message || params.turn.error.codexErrorInfo)) || - 'app-server turn failed'; - done({ ok: false, content: state.content, promptTokens: state.promptTokens, completionTokens: state.completionTokens, cacheReadTokens: state.cacheReadTokens, detail: String(detail) }); - } else { - if (state.completionTokens === 0 && state.content) { - state.completionTokens = Math.max(1, Math.ceil(state.content.length / 4)); - } - done({ ok: true, content: state.content, promptTokens: state.promptTokens, completionTokens: state.completionTokens, cacheReadTokens: state.cacheReadTokens, detail: null }); - } - } - } - }; - client.turnStates.set(threadId, state); - client.rpc('turn/start', { - threadId, - input: [{ type: 'text', text }], - model: baseModel, - effort - }, 60000).catch((err) => state.fail(err)); - }); - -const threadConfig = (effort) => ({ model_reasoning_effort: effort }); - -// A full app-server attempt for one chat request. Resolves (never rejects) -// to a runCodexOnce-shaped result plus { threadId, key } on success. -// Throws only for connection-level failures (caller retries once, then -// falls back to the exec transports). -const runAppServerOnce = async ({ messages, fullName, baseModel, effort, prompt, emit }) => { - const client = await ensureAppServer(); - const plan = planResume(messages, fullName); - - // Warm path: the conversation already owns a daemon thread and the - // request extends exactly what that thread was fed. - if (plan && plan.entry.threadId) { - const threadId = plan.entry.threadId; - try { - if (!client.loadedThreads.has(threadId)) { - await client.rpc('thread/resume', { - threadId, - model: baseModel, - cwd: '/tmp', - approvalPolicy: 'never', - sandbox: 'danger-full-access', - config: threadConfig(effort) - }); - client.loadedThreads.add(threadId); - } - } catch (err) { - console.warn(`[codex-proxy] app-server thread/resume failed (${err.message}); starting a fresh thread`); - forgetThread(plan.key); - // fall through to the cold thread below - } - if (client.loadedThreads.has(threadId)) { - const tailText = formatPrompt(plan.tailMessages); - const attempt = await runAppServerTurn(client, { - threadId, text: tailText, baseModel, effort, prompt, emit - }); - if (attempt.ok) { - recordSession(plan.key, plan.entry.sessionId, messages, threadId); - console.log(`[codex-proxy] app-server warm turn: key=${plan.key.slice(0, 8)} thread=${threadId} fed=${plan.entry.fedCount}->${messages.length}`); - } - return { ...attempt, threadId, key: plan.key }; - } - } - - // Cold path: a new daemon thread. System text becomes the thread's - // developer instructions; the rest of the history is flattened into - // the first turn exactly like the exec path flattens it. - const systemText = messages.filter(m => m.role === 'system').map(messageText).join('\n\n'); - const nonSystem = messages.filter(m => m.role !== 'system'); - const firstText = nonSystem.length > 0 ? formatPrompt(nonSystem) : prompt; - const startParams = { - model: baseModel, - cwd: '/tmp', - approvalPolicy: 'never', - sandbox: 'danger-full-access', - config: threadConfig(effort) - }; - if (systemText) startParams.developerInstructions = systemText; - const started = await client.rpc('thread/start', startParams, 120000); - const threadId = started && started.thread && started.thread.id; - if (!threadId) throw new Error('app-server thread/start returned no thread id'); - client.loadedThreads.add(threadId); - const attempt = await runAppServerTurn(client, { - threadId, text: firstText, baseModel, effort, prompt, emit - }); - const key = conversationKey(messages, fullName); - if (attempt.ok) recordSession(key, null, messages, threadId); - return { ...attempt, threadId, key }; -}; - -// Terminate one exec child at most once, escalating if SIGTERM does not -// close it. The close listener prevents a stale SIGKILL timer after exit. -const createExecChildKiller = (child) => { - let killStarted = false; - let closed = false; - let killTimer = null; - - child.once('close', () => { - closed = true; - if (killTimer) { - clearTimeout(killTimer); - killTimer = null; - } - }); - - return () => { - if (killStarted || closed) return; - killStarted = true; - try { child.kill('SIGTERM'); } catch (_) {} - killTimer = setTimeout(() => { - killTimer = null; - if (!closed) { - try { child.kill('SIGKILL'); } catch (_) {} - } - }, EXEC_TURN_KILL_GRACE_MS); - killTimer.unref?.(); - }; -}; - -// Run one `codex exec` child to completion. Resolves (never rejects) to -// { ok, content, promptTokens, completionTokens, sessionId, detail }. -// `emit(text)` is called live for each completed agent message when -// given; pass null to buffer instead (resume attempts buffer, so a failed -// resume can fall back to a full run without duplicating streamed text). -const runCodexOnce = ({ args, prompt, emit, onSpawn }) => - new Promise((resolve) => { - let settled = false; - let timeoutTimer = null; - let timedOut = false; - const done = (result) => { - if (!settled) { - settled = true; - if (timeoutTimer) clearTimeout(timeoutTimer); - resolve(result); - } - }; - - let child; - try { - child = spawn(CODEX_BIN, args, { - cwd: '/tmp', - env: { - ...process.env, - PATH: `/run/current-system/sw/bin:${process.env.PATH || ''}` - }, - stdio: ['pipe', 'pipe', 'pipe'] - }); - } catch (err) { - done({ ok: false, content: '', sessionId: null, detail: err.message }); - return; - } - const killChild = createExecChildKiller(child); - if (onSpawn) onSpawn(child, killChild); - - timeoutTimer = setTimeout(() => { - timeoutTimer = null; - timedOut = true; - killChild(); - }, EXEC_TURN_TIMEOUT_MS); - timeoutTimer.unref?.(); - - console.log(`[codex-proxy] Spawning: ${CODEX_BIN} ${args.join(' ')}`); - - let lineBuffer = ''; - const stdoutDecoder = createStreamDecoder(); - const stderrDecoder = createStreamDecoder(); - let fullContent = ''; - let promptTokens = Math.max(1, Math.ceil(prompt.length / 4)); - let completionTokens = 0; - let cacheReadTokens = 0; - let stderrTail = ''; - let spawnError = null; - // In-band failure state: `codex exec --json` can report a fatal - // turn failure as a turn.failed event on a run that still exits 0 - // (#680). null = no turn.failed seen; otherwise its error message - // ('' when the event carried none). - let turnFailedMessage = null; - let sessionId = null; - - // A child killed at the deadline may have stopped reading a large - // prompt. Consume the resulting EPIPE as this request's child failure - // instead of allowing an unhandled stream error to crash the proxy. - child.stdin.on('error', (err) => { - spawnError = err; - }); - - // Write prompt to stdin and close stdin - try { - child.stdin.write(prompt); - child.stdin.end(); - } catch (err) { - spawnError = err; - } - - const processJsonLine = (line) => { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('{')) return; - - try { - const event = JSON.parse(trimmed); - - // Session id for warm resume (#480): `codex exec --json` opens - // with {"type":"thread.started","thread_id":""} (verified - // against codex-cli 0.160.0). Accept the session_id spellings - // other CLI versions have used too; first one wins. - if (!sessionId) { - const candidate = - event.thread_id || - event.session_id || - (event.thread && event.thread.id) || - (event.session && event.session.id); - if (typeof candidate === 'string' && candidate) sessionId = candidate; - } - - // Agent message completed - if ( - event.type === 'item.completed' && - event.item && - event.item.type === 'agent_message' && - typeof event.item.text === 'string' - ) { - fullContent += event.item.text; - if (emit) emit(event.item.text); - } - - // Turn failed in-band: a fatal error during the turn. The - // exit code cannot be trusted to reflect it (#680). - if (event.type === 'turn.failed') { - turnFailedMessage = - typeof event.error === 'string' - ? event.error - : event.error && typeof event.error.message === 'string' - ? event.error.message - : ''; - } - - // Turn completed with usage metrics - if (event.type === 'turn.completed' && event.usage) { - if (typeof event.usage.input_tokens === 'number') { - promptTokens = event.usage.input_tokens; - } - if (typeof event.usage.output_tokens === 'number') { - completionTokens = event.usage.output_tokens; - } - if (typeof event.usage.cached_input_tokens === 'number') { - cacheReadTokens = event.usage.cached_input_tokens; - } - } - } catch (err) { - // Non-JSON line or parser error ignored - } - }; - - child.stdout.on('data', (chunk) => { - lineBuffer += stdoutDecoder.push(chunk); - const lines = lineBuffer.split('\n'); - lineBuffer = lines.pop(); // remainder - for (const line of lines) { - processJsonLine(line); - } - }); - - child.stderr.on('data', (chunk) => { - const msg = stderrDecoder.push(chunk); - stderrTail = (stderrTail + msg).slice(-2000); - if (msg.trim().length > 0) { - console.warn(`[codex-proxy stderr] ${msg.trim()}`); - } - }); - - child.on('close', (code, signal) => { - if (lineBuffer.trim().length > 0) { - processJsonLine(lineBuffer); - lineBuffer = ''; - } - - if (completionTokens === 0 && fullContent.length > 0) { - completionTokens = Math.max(1, Math.ceil(fullContent.length / 4)); - } - - // The timeout initiated the shutdown, so its verdict takes precedence - // over the SIGTERM/SIGKILL close event and any partial/in-band result. - if (timedOut) { - done({ - ok: false, - timedOut: true, - content: fullContent, - promptTokens, - completionTokens, - cacheReadTokens, - sessionId, - detail: `codex exec timed out after ${EXEC_TURN_TIMEOUT_MS}ms` - }); - return; - } - - // Failure is judged by the run's authoritative signals: a - // turn.failed event (#680), or failing that the child's exit — - // a non-zero code or a killing signal means the run failed, - // however much content was already produced (#676). Partial - // content must not mask a failure. - if (code !== 0 || turnFailedMessage !== null) { - const stderrLine = stderrTail.trim().split('\n').pop(); - const fallback = spawnError - ? spawnError.message - : signal - ? `codex exec terminated by signal ${signal}` - : turnFailedMessage !== null && code === 0 - ? 'codex turn failed (turn.failed event carried no error message)' - : `codex exec exited with code ${code}`; - const detail = (turnFailedMessage || stderrLine || fallback).trim(); - done({ - ok: false, - content: fullContent, - promptTokens, - completionTokens, - cacheReadTokens, - sessionId, - detail - }); - return; - } - - done({ - ok: true, - content: fullContent, - promptTokens, - completionTokens, - cacheReadTokens, - sessionId, - detail: null - }); - }); - - child.on('error', (err) => { - console.error(`[codex-proxy child error] ${err.message}`); - spawnError = err; - }); - }); - -const server = http.createServer(async (req, res) => { - res.setHeader('Access-Control-Allow-Origin', '*'); - res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); - res.setHeader('Access-Control-Allow-Headers', '*'); - if (req.method === 'OPTIONS') { - res.writeHead(204); - res.end(); - return; - } - - const url = new URL(req.url, `http://${req.headers.host || HOST}`); - const pathname = url.pathname.replace(/\/+$/, '') || '/'; - - // Health & Root - if (req.method === 'GET' && (pathname === '/health' || pathname === '/')) { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - status: 'ok', - service: 'openai-codex-proxy', - port: PORT, - binary: CODEX_BIN, - transport: TRANSPORT, - defaultModel: 'gpt-5.6-luna-low' - }, null, 2)); - return; - } - - // Models catalog (live: `codex debug models`, TTL-cached with - // last-known-good/static-floor fallback — see refreshLiveModels) - if (req.method === 'GET' && (pathname === '/v1/models' || pathname === '/models')) { - const now = Math.floor(Date.now() / 1000); - const data = []; - - for (const m of await getModelCatalog()) { - data.push({ - id: m.id, - object: 'model', - created: now, - owned_by: 'openai-codex' - }); - for (const eff of m.efforts) { - data.push({ - id: `${m.id}-${eff}`, - object: 'model', - created: now, - owned_by: 'openai-codex' - }); - } - } - - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ object: 'list', data }, null, 2)); - return; - } - - // Chat completions - if (req.method === 'POST' && (pathname === '/v1/chat/completions' || pathname === '/chat/completions')) { - const bodyCollector = createRequestBodyCollector(50 * 1024 * 1024); - req.on('data', chunk => { - if (bodyCollector.tooLarge) return; - if (!bodyCollector.push(chunk)) { - res.writeHead(413, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Request payload too large' } })); - req.destroy(); - } - }); - - req.on('end', async () => { - if (bodyCollector.tooLarge) return; - const bodyText = bodyCollector.text(); - let body; - try { - body = JSON.parse(bodyText); - } catch (err) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Invalid JSON body: ${err.message}` } })); - return; - } - - if (typeof body !== 'object' || body === null || Array.isArray(body)) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Invalid JSON body: expected an object' } })); - return; - } - - const stream = Boolean(body.stream); - const reqReasoningEffort = body.reasoning_effort || (body.options && body.options.reasoning_effort); - const resolvedModel = resolveModelAndEffort(body.model, reqReasoningEffort, await getModelCatalog()); - if (!resolvedModel) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Unknown model "${body.model}": not in the live Codex catalog (see GET /v1/models)` } })); - return; - } - const { baseModel, effort, fullName } = resolvedModel; - const prompt = formatPrompt(body.messages); - - if (!prompt || prompt.trim().length === 0) { - res.writeHead(400, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: 'Messages cannot be empty' } })); - return; - } - - const chatId = `chatcmpl-codex-${crypto.randomUUID()}`; - const created = Math.floor(Date.now() / 1000); - - // Spawn arguments for codex exec. Fresh runs deliberately omit - // --ephemeral: an ephemeral session leaves no rollout on disk, so - // it could never be resumed by a later turn (#480). - const commonArgs = [ - '--json', - '--skip-git-repo-check', - '--dangerously-bypass-approvals-and-sandbox', - '--disable', 'shell_tool', - '-m', baseModel, - '-c', `model_reasoning_effort="${effort}"`, - '-c', 'model_context_window=1000000', - '-c', 'model_auto_compact_token_limit=950000' - ]; - const freshArgs = ['exec', ...commonArgs, '--color', 'never', '-']; - // `exec resume` has no --color flag in codex-cli 0.160.0 (passing - // it is a usage error, exit 2 — verified on amd); the rest of the - // option set is shared with `exec`. - const resumeArgs = (sessionId) => ['exec', 'resume', ...commonArgs, sessionId, '-']; - - // Refresh OpenCode tokens in background - syncCodexTokensToOpenCode(); - - if (stream) { - res.writeHead(200, { - 'Content-Type': 'text/event-stream; charset=utf-8', - 'Cache-Control': 'no-cache, no-transform', - 'Connection': 'keep-alive', - 'X-Accel-Buffering': 'no' - }); - } - - const writeChunk = (delta) => { - if (res.writableEnded) return; - const chunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model: fullName, - choices: [{ index: 0, delta, finish_reason: null }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - }; - - const sendSuccess = (result, replay) => { - if (res.writableEnded) return; - const usage = { - prompt_tokens: result.promptTokens, - completion_tokens: result.completionTokens, - total_tokens: result.promptTokens + result.completionTokens, - ...(result.cacheReadTokens > 0 ? { prompt_tokens_details: { cached_tokens: result.cacheReadTokens } } : {}) - }; - if (stream) { - // Buffered (resumed) runs replay their content as one chunk; - // live runs already streamed each item as it completed. - if (replay && result.content) writeChunk({ content: result.content }); - const endChunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model: fullName, - choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], - usage - }; - res.write(`data: ${JSON.stringify(endChunk)}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - } else { - res.writeHead(200, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - id: chatId, - object: 'chat.completion', - created, - model: fullName, - choices: [{ - index: 0, - message: { role: 'assistant', content: result.content }, - finish_reason: 'stop' - }], - usage - }, null, 2)); - } - }; - - const sendFailure = (detail) => { - if (res.writableEnded) return; - const errorBody = { error: { message: `Codex execution failed: ${detail}` } }; - if (stream) { - // The 200 + text/event-stream headers are already on the - // wire, so frame the error as an SSE event and close the - // stream with [DONE] (mirrors muse-proxy #670). - res.write(`data: ${JSON.stringify(errorBody)}\n\n`); - res.write('data: [DONE]\n\n'); - res.end(); - return; - } - if (!res.headersSent) { - res.writeHead(500, { 'Content-Type': 'application/json' }); - } - res.end(JSON.stringify(errorBody)); - }; - - (async () => { - let currentKillChild = null; - res.on('close', () => { - if (!res.writableEnded && currentKillChild) currentKillChild(); - }); - const onSpawn = (_child, killChild) => { currentKillChild = killChild; }; - - // Lead transport (#480): the warm app-server daemon. Live deltas - // stream as they arrive; a failure before anything was emitted - // falls through to the exec transports below, and a connection - // failure gets exactly one reconnect before that fallback. - if (TRANSPORT === 'app-server') { - let emitted = false; - const emitLive = stream - ? (text) => { emitted = true; writeChunk({ content: text }); } - : null; - for (let attemptNo = 0; attemptNo < 2; attemptNo++) { - let attempt; - try { - attempt = await runAppServerOnce({ - messages: body.messages, fullName, baseModel, effort, prompt, emit: emitLive - }); - } catch (err) { - if (emitted) { sendFailure(err.message); return; } - console.warn( - `[codex-proxy] app-server attempt failed (${err.message}); ` + - (attemptNo === 0 ? 'reconnecting once' : 'falling back to exec transports') - ); - resetAppServer(); - continue; - } - if (attempt.ok) { - sendSuccess(attempt, stream && !emitted); - return; - } - if (emitted) { sendFailure(attempt.detail || 'app-server turn failed'); return; } - console.warn( - `[codex-proxy] app-server turn failed (${attempt.detail}); falling back to exec transports` - ); - break; - } - } - - // Warm path (#480): resume the conversation's codex session - // with only the new tail. Buffered, so a failed resume can fall - // back to a full-history fresh run without duplicating text. - const plan = TRANSPORT === 'exec' ? null : planResume(body.messages, fullName); - if (plan) { - const tailPrompt = formatPrompt(plan.tailMessages); - const attempt = await runCodexOnce({ - args: resumeArgs(plan.entry.sessionId), - prompt: tailPrompt, - emit: null, - onSpawn - }); - if (attempt.ok) { - recordSession(plan.key, attempt.sessionId || plan.entry.sessionId, body.messages); - console.log( - `[codex-proxy] warm resume: key=${plan.key.slice(0, 8)} session=${plan.entry.sessionId} fed=${plan.entry.fedCount}->${body.messages.length}` - ); - sendSuccess(attempt, true); - return; - } - if (attempt.timedOut) { - forgetSession(plan.key); - sendFailure(attempt.detail); - return; - } - console.warn( - `[codex-proxy] warm resume failed (${attempt.detail}); falling back to full-history run` - ); - forgetSession(plan.key); - } - - // Cold path: full flattened history, exactly as before — except - // the session is now persisted and recorded for warm resume. - const key = conversationKey(body.messages, fullName); - const result = await runCodexOnce({ - args: freshArgs, - prompt, - emit: stream ? (text) => writeChunk({ content: text }) : null, - onSpawn - }); - if (!result.ok) { - sendFailure(result.detail); - return; - } - recordSession(key, result.sessionId, body.messages); - sendSuccess(result, false); - })().catch((err) => { - console.error(`[codex-proxy] request handler error: ${err && err.message}`); - sendFailure(err && err.message ? err.message : 'internal error'); - }); - }); - return; - } - - // Fallthrough 404 - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Route not found: ${req.method} ${pathname}` } })); -}); - -// Socket activation (#1821): under systemd the listener arrives as fd 3 -// and systemd owns the bind; a manual launch binds PORT/HOST directly. -server.listen(listenTarget({ port: PORT, host: HOST }), () => { - publishEndpoint(); - console.log(`[codex-proxy] OpenAI-compatible bridge listening on http://${HOST}:${PORT}`); - console.log(`[codex-proxy] Resolved codex binary: ${CODEX_BIN}`); - if (process.env.CODEX_PROXY_TOKEN_SYNC === '0') { - console.log('[codex-proxy] codex-token-sync: disabled by CODEX_PROXY_TOKEN_SYNC=0 (in-fork sync owns the credential store)'); - } else { - syncCodexTokensToOpenCode(); - } - setInterval(syncCodexTokensToOpenCode, 5 * 60 * 1000); -}); diff --git a/bin/codex-proxy.test.mjs b/bin/codex-proxy.test.mjs deleted file mode 100644 index bb42675dba..0000000000 --- a/bin/codex-proxy.test.mjs +++ /dev/null @@ -1,912 +0,0 @@ -// Tests for codex-proxy's failure detection (#676, #680). -// Run: node --test bin/codex-proxy.test.mjs -// -// The proxy spawns one `codex exec` child per request, with the prompt -// delivered on stdin. These tests put a stub `codex` at -// $HOME/.local/bin/codex (the proxy's binary resolution prefers it) -// whose behaviour is keyed on markers in the prompt: a run that exits -// non-zero used to be reported as a successful 'stop' — empty when it -// produced nothing, and carrying the truncated text when it produced -// (startProxy additionally pins the stub via CODEX_PROXY_CODEX_BIN so a -// host-installed codex can never shadow it, #694.) -// partial output. -import assert from 'node:assert/strict'; -import { spawn, execFile, execFileSync } from 'node:child_process'; -import crypto from 'node:crypto'; -import fs from 'node:fs'; -import net from 'node:net'; -import os from 'node:os'; -import path from 'node:path'; -import test from 'node:test'; -import { fileURLToPath } from 'node:url'; - -const binDir = path.dirname(fileURLToPath(import.meta.url)); - -const STUB = `#!/bin/sh -# The proxy runs this through execFile before accepting chat turns. Handle it -# before reading stdin: execFile leaves the child's stdin open, so cat would -# otherwise wait for the 30-second command timeout on every request. -if [ "$1" = "debug" ] && [ "$2" = "models" ]; then - printf '%s\\n' '{"models":[{"slug":"gpt-6.1-sol","display_name":"GPT-6.1 Sol","supported_reasoning_levels":[{"effort":"low"},{"effort":"medium"},{"effort":"high"}],"default_reasoning_level":"medium"},{"slug":"gpt-6-luna","display_name":"GPT-6 Luna","supported_reasoning_levels":[{"effort":"low"},{"effort":"medium"}],"default_reasoning_level":"low"},{"slug":"gpt-5.6-luna","display_name":"GPT-5.6 Luna","supported_reasoning_levels":[{"effort":"low"},{"effort":"medium"}],"default_reasoning_level":"low"}]}' - exit 0 -fi -if [ -n "$CODEX_PROXY_TEST_STDIN_DELAY_MS" ]; then - exec node -e 'setTimeout(() => { process.stdin.on("data", () => {}); process.stdin.resume(); }, Number(process.env.CODEX_PROXY_TEST_STDIN_DELAY_MS))' -fi -prompt="$(cat)" -resume=0 -for a in "$@"; do [ "$a" = "resume" ] && resume=1; done -{ - echo "ARGS:$*" - echo "RESUME:$resume" - echo "PROMPT:$prompt" - echo "===" -} >> "$HOME/invocations.log" -if [ "$resume" = "1" ]; then - case "$prompt" in - *RESUMETIMEOUT*) - exec node -e 'setInterval(() => {}, 1000)' ;; - *RESUMEFAIL*) - echo "stub codex: session not found" >&2 - exit 3 ;; - *) - printf '%s\\n' '{"type":"thread.started","thread_id":"stub-session-1"}' - printf '%s\\n' '{"type":"item.completed","item":{"type":"agent_message","text":"resumed answer"}}' - printf '%s\\n' '{"type":"turn.completed","usage":{"input_tokens":10,"output_tokens":3}}' - exit 0 ;; - esac -fi -case "$prompt" in - *FAILME*) - echo "stub codex: auth expired" >&2 - exit 3 ;; - *FAILPARTIAL*) - printf '%s\\n' '{"type":"item.completed","item":{"type":"agent_message","text":"partial answer"}}' - echo "stub codex: run failed midway" >&2 - exit 3 ;; - *INBANDPARTIAL*) - printf '%s\\n' '{"type":"item.completed","item":{"type":"agent_message","text":"partial answer"}}' - printf '%s\\n' '{"type":"turn.failed","error":{"message":"stub codex: run failed midway"}}' - exit 0 ;; - *INBANDFAIL*) - printf '%s\\n' '{"type":"turn.failed","error":{"message":"stub codex: model overloaded"}}' - exit 0 ;; - *INBANDSTR*) - printf '%s\\n' '{"type":"turn.failed","error":"stub codex: string overload"}' - exit 0 ;; - *INBANDNONE*) - printf '%s\\n' '{"type":"turn.failed"}' - exit 0 ;; - *INBANDOBJ*) - printf '%s\\n' '{"type":"turn.failed","error":{}}' - exit 0 ;; - *SIGKILLME*) - kill -9 $$ ;; - *TIMEOUT*) - exec node -e 'const fs = require("node:fs"); fs.writeFileSync(process.env.CODEX_PROXY_CHILD_PID_FILE, String(process.pid)); setInterval(() => {}, 1000)' ;; - *IGNORETERM*) - exec node -e 'const fs = require("node:fs"); fs.writeFileSync(process.env.CODEX_PROXY_CHILD_PID_FILE, String(process.pid)); process.on("SIGTERM", () => {}); setInterval(() => {}, 1000)' ;; - *) - printf '%s\\n' '{"type":"thread.started","thread_id":"stub-session-1"}' - printf '%s\\n' '{"type":"item.completed","item":{"type":"agent_message","text":"Hello world"}}' - printf '%s\\n' '{"type":"turn.completed","usage":{"input_tokens":100,"output_tokens":3,"cached_input_tokens":93}}' - exit 0 ;; -esac -`; - -test('Codex stub answers live model lookup without blocking on stdin', async (t) => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-proxy-stub-test-')); - t.after(() => fs.rmSync(tmp, { recursive: true, force: true })); - const stubPath = path.join(tmp, 'codex'); - fs.writeFileSync(stubPath, STUB, { mode: 0o755 }); - - const stdout = await new Promise((resolve, reject) => { - execFile(stubPath, ['debug', 'models'], { timeout: 1000 }, (err, out, stderr) => { - if (err) { - reject(new Error(`codex debug models stub failed: ${err.message}; stderr=${stderr}`)); - } else { - resolve(out); - } - }); - }); - const catalog = JSON.parse(stdout); - assert.ok(Array.isArray(catalog.models)); - assert.ok(catalog.models.length >= 3); - assert.ok(catalog.models.some((model) => model.slug === 'gpt-6.1-sol')); -}); - - -// --------------------------------------------------------------------------- -// Fake app-server daemon (#480): a real WebSocket-over-Unix-socket server -// speaking just enough of the codex app-server protocol for the proxy's -// transport tests — initialize, thread/start, thread/resume, turn/start, -// agentMessage deltas, token usage, turn/completed. Behaviour is keyed on -// markers in the turn text, mirroring the exec stub. -// --------------------------------------------------------------------------- -const wsServerFrame = (text) => { - const data = Buffer.from(text); - let header; - if (data.length < 126) { - header = Buffer.from([0x81, data.length]); - } else { - header = Buffer.alloc(4); - header[0] = 0x81; header[1] = 126; header.writeUInt16BE(data.length, 2); - } - return Buffer.concat([header, data]); -}; - -const createFakeAppServer = () => { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-as-test-')); - const socketPath = path.join(dir, 'app-server-control.sock'); - const requests = []; - const sockets = new Set(); - const server = net.createServer((sock) => { - sockets.add(sock); - sock.on('close', () => sockets.delete(sock)); - let buf = Buffer.alloc(0); - let headersDone = false; - let frags = []; - const sendObj = (obj) => sock.write(wsServerFrame(JSON.stringify(obj))); - const handle = (msg) => { - if (msg.method === 'initialize') { - requests.push({ method: 'initialize' }); - sendObj({ id: msg.id, result: { userAgent: 'stub-app-server', codexHome: dir, platformFamily: 'unix', platformOs: 'linux' } }); - } else if (msg.method === 'initialized') { - requests.push({ method: 'initialized' }); - } else if (msg.method === 'thread/start') { - requests.push({ method: 'thread/start', params: msg.params }); - sendObj({ id: msg.id, result: { thread: { id: 'stub-thread-1' }, model: 'gpt-5.6-luna' } }); - } else if (msg.method === 'thread/resume') { - requests.push({ method: 'thread/resume', params: msg.params }); - sendObj({ id: msg.id, result: { thread: { id: msg.params.threadId } } }); - } else if (msg.method === 'turn/start') { - const text = msg.params.input.map(i => i.text || '').join('\n'); - requests.push({ method: 'turn/start', params: msg.params, text }); - if (text.includes('ASRPCFAIL')) { - sendObj({ id: msg.id, error: { code: -32000, message: 'stub app-server: rpc exploded' } }); - return; - } - sendObj({ id: msg.id, result: { turn: { id: 'stub-turn-1' } } }); - if (text.includes('ASKILL')) { - // Daemon dies mid-turn: destroy the connection with no completion. - setTimeout(() => { for (const s2 of sockets) s2.destroy(); }, 20); - return; - } - const tid = msg.params.threadId; - if (text.includes('ASFAIL')) { - sendObj({ method: 'turn/completed', params: { threadId: tid, turn: { id: 'stub-turn-1', status: 'failed', error: { message: 'stub app-server: turn exploded' } } } }); - return; - } - sendObj({ method: 'item/agentMessage/delta', params: { threadId: tid, turnId: 'stub-turn-1', itemId: 'item-1', delta: 'app-' } }); - sendObj({ method: 'item/agentMessage/delta', params: { threadId: tid, turnId: 'stub-turn-1', itemId: 'item-1', delta: 'server answer' } }); - sendObj({ method: 'thread/tokenUsage/updated', params: { threadId: tid, turnId: 'stub-turn-1', tokenUsage: { last: { inputTokens: 42, outputTokens: 5, cachedInputTokens: 39 }, total: { inputTokens: 42, outputTokens: 5, cachedInputTokens: 39 } } } }); - sendObj({ method: 'turn/completed', params: { threadId: tid, turn: { id: 'stub-turn-1', status: 'completed' } } }); - } - }; - sock.on('data', (chunk) => { - buf = Buffer.concat([buf, chunk]); - if (!headersDone) { - const idx = buf.indexOf('\r\n\r\n'); - if (idx === -1) return; - const head = buf.subarray(0, idx).toString('utf-8'); - buf = buf.subarray(idx + 4); - const key = /Sec-WebSocket-Key: (\S+)/i.exec(head)[1]; - const accept = crypto.createHash('sha1').update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64'); - sock.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`); - headersDone = true; - } - for (;;) { - if (buf.length < 2) return; - const fin = (buf[0] & 0x80) !== 0; - const opcode = buf[0] & 0x0f; - let len = buf[1] & 0x7f; - let off = 2; - if (len === 126) { if (buf.length < 4) return; len = buf.readUInt16BE(2); off = 4; } - else if (len === 127) { if (buf.length < 10) return; len = Number(buf.readBigUInt64BE(2)); off = 10; } - const masked = (buf[1] & 0x80) !== 0; - const mask = masked ? buf.subarray(off, off + 4) : null; - if (masked) off += 4; - if (buf.length < off + len) return; - let payload = buf.subarray(off, off + len); - buf = buf.subarray(off + len); - if (masked) { - payload = Buffer.from(payload); - for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4]; - } - if (opcode === 0x8) { sock.end(); return; } - if (opcode === 0x9 || opcode === 0xA) continue; - frags.push(payload); - if (!fin) continue; - const text = Buffer.concat(frags).toString('utf-8'); - frags = []; - try { handle(JSON.parse(text)); } catch { /* ignore */ } - } - }); - }); - return new Promise((resolve) => { - server.listen(socketPath, () => resolve({ - socketPath, - requests, - close: () => { for (const s2 of sockets) s2.destroy(); server.close(); } - })); - }); -}; - -const freePort = () => new Promise((resolve, reject) => { - const srv = net.createServer(); - srv.once('error', reject); - srv.listen(0, '127.0.0.1', () => { - const { port } = srv.address(); - srv.close(() => resolve(port)); - }); -}); - -const startProxy = async (reuse, extraEnv = {}, seedHome = null) => { - const tmp = reuse ? reuse.tmp : fs.mkdtempSync(path.join(os.tmpdir(), 'codex-proxy-test-')); - const home = path.join(tmp, 'home'); - fs.mkdirSync(path.join(home, '.local', 'bin'), { recursive: true }); - fs.writeFileSync(path.join(home, '.local', 'bin', 'codex'), STUB, { mode: 0o755 }); - if (seedHome) seedHome(home); - const stateHome = path.join(tmp, 'state'); - const port = await freePort(); - const child = spawn(process.execPath, [path.join(binDir, 'codex-proxy.mjs')], { - env: { - ...process.env, - HOME: home, - XDG_STATE_HOME: stateHome, - CODEX_PROXY_PORT: String(port), - CODEX_PROXY_CODEX_BIN: path.join(home, '.local', 'bin', 'codex'), - ...extraEnv - }, - stdio: ['ignore', 'pipe', 'pipe'] - }); - let log = ''; - child.stdout.on('data', d => { log += d; }); - child.stderr.on('data', d => { log += d; }); - const deadline = Date.now() + 10000; - for (;;) { - try { - const res = await fetch(`http://127.0.0.1:${port}/health`); - if (res.ok) break; - } catch { /* not up yet */ } - if (Date.now() > deadline) throw new Error(`proxy did not start:\n${log}`); - await new Promise(r => setTimeout(r, 50)); - } - return { port, tmp, home, stateHome, stop: () => child.kill('SIGKILL'), log: () => log }; -}; - -const post = (port, body) => fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(body) -}); - -const waitFor = async (predicate, timeoutMs = 5000) => { - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - if (predicate()) return; - await new Promise((resolve) => setTimeout(resolve, 25)); - } - throw new Error(`condition not met within ${timeoutMs}ms`); -}; - -const isProcessAlive = (pid) => { - try { - process.kill(pid, 0); - return true; - } catch (err) { - if (err.code === 'ESRCH') return false; - throw err; - } -}; - -const readPid = (file) => Number(fs.readFileSync(file, 'utf-8')); - -const assertFailure = async (port, marker, detail) => { - const messages = [{ role: 'user', content: `please ${marker} now` }]; - - const plainRes = await post(port, { messages }); - assert.equal(plainRes.status, 500, `${marker}: non-stream must be a 500, not a 200 'stop'`); - const plainBody = JSON.parse(await plainRes.text()); - assert.match(plainBody.error.message, detail, `${marker}: non-stream detail must name the cause, got: ${plainBody.error.message}`); - assert.doesNotMatch(plainBody.error.message, /code (null|-2)\b/); - - const streamRes = await post(port, { messages, stream: true }); - assert.equal(streamRes.status, 200); - assert.match(streamRes.headers.get('content-type'), /text\/event-stream/); - const sse = await streamRes.text(); - const dataLines = sse.split('\n').filter(l => l.startsWith('data: ')); - assert.equal(dataLines[dataLines.length - 1], 'data: [DONE]', `${marker}: stream must end with [DONE]`); - const events = dataLines.slice(0, -1).map(l => JSON.parse(l.slice('data: '.length))); - const errorEvent = events.find(e => e.error); - assert.ok(errorEvent, `${marker}: stream must carry an error event, got: ${JSON.stringify(sse)}`); - assert.match(errorEvent.error.message, detail, `${marker}: stream detail must name the cause, got: ${errorEvent.error.message}`); - const stopChunk = events.find(e => e.choices && e.choices[0].finish_reason === 'stop'); - assert.equal(stopChunk, undefined, `${marker}: no chunk may claim finish_reason 'stop'`); -}; - -test('successful run is unchanged in both modes', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - const messages = [{ role: 'user', content: 'hi' }]; - - const plainRes = await post(port, { messages }); - assert.equal(plainRes.status, 200); - const plain = JSON.parse(await plainRes.text()); - assert.equal(plain.choices[0].message.content, 'Hello world'); - assert.equal(plain.choices[0].finish_reason, 'stop'); - - const streamRes = await post(port, { messages, stream: true }); - assert.equal(streamRes.status, 200); - const sse = await streamRes.text(); - assert.match(sse, /Hello world/); - assert.match(sse, /"finish_reason":"stop"/); - assert.ok(sse.trimEnd().endsWith('data: [DONE]')); -}); - -test('CLI transport: cached_input_tokens surfaces as prompt_tokens_details.cached_tokens (#3114)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - - // Non-stream: the exec stub's turn.completed carries cached_input_tokens 93. - const plainRes = await post(port, { messages: TURN1 }); - assert.equal(plainRes.status, 200); - const plain = JSON.parse(await plainRes.text()); - assert.equal(plain.usage.prompt_tokens_details.cached_tokens, 93, 'CLI transport must surface cached_input_tokens as prompt_tokens_details.cached_tokens (opencode #394)'); - - // The resumed turn's stub usage has NO cached_input_tokens: the detail - // object must be omitted entirely, not emitted as 0. - const r2 = await post(port, { messages: TURN2 }); - assert.equal(r2.status, 200); - const resumed = JSON.parse(await r2.text()); - assert.equal(resumed.choices[0].message.content, 'resumed answer'); - assert.equal(resumed.usage.prompt_tokens_details, undefined, 'absent cache value must omit prompt_tokens_details entirely'); - - // Stream: the end chunk carries the same cached_tokens for a fresh run. - const streamRes = await post(port, { messages: [{ role: 'user', content: 'gamma streaming question' }], stream: true }); - assert.equal(streamRes.status, 200); - const sse = await streamRes.text(); - const events = sse.split('\n').filter(l => l.startsWith('data: ') && !l.includes('[DONE]')).map(l => JSON.parse(l.slice('data: '.length))); - const endChunk = events.find(e => e.usage); - assert.ok(endChunk, 'stream end chunk must carry usage'); - assert.equal(endChunk.usage.prompt_tokens_details.cached_tokens, 93, 'streaming CLI transport must surface cached_tokens'); -}); - -test('execution failure with no output: 500 non-stream, SSE error + [DONE] stream (#676)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - await assertFailure(port, 'FAILME', /Codex execution failed: stub codex: auth expired/); -}); - -test('partial output then failure: masked success becomes an error in both modes (#676)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - await assertFailure(port, 'FAILPARTIAL', /Codex execution failed: stub codex: run failed midway/); -}); - -test('turn.failed with exit 0 and no output: 500 non-stream, SSE error + [DONE] stream (#680)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - await assertFailure(port, 'INBANDFAIL', /Codex execution failed: stub codex: model overloaded/); -}); - -test('partial output then turn.failed with exit 0: masked success becomes an error in both modes (#680)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - await assertFailure(port, 'INBANDPARTIAL', /Codex execution failed: stub codex: run failed midway/); -}); - -test('turn.failed with a bare-string error: the string is the detail on both transports (#694)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - await assertFailure(port, 'INBANDSTR', /Codex execution failed: stub codex: string overload/); -}); - -test('turn.failed with no error message: fallback names the in-band failure, not exit 0 (#694)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - await assertFailure(port, 'INBANDNONE', /Codex execution failed: codex turn failed \(turn\.failed event carried no error message\)/); - await assertFailure(port, 'INBANDOBJ', /Codex execution failed: codex turn failed \(turn\.failed event carried no error message\)/); - - const plainRes = await post(port, { messages: [{ role: 'user', content: 'please INBANDNONE now' }] }); - assert.equal(plainRes.status, 500); - const plainBody = JSON.parse(await plainRes.text()); - assert.doesNotMatch(plainBody.error.message, /exited with code 0/, 'message-less in-band failure must not blame a successful exit'); -}); - -test('empty-stderr fallback names the killing signal, not code null (#676)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - await assertFailure(port, 'SIGKILLME', /Codex execution failed: codex exec terminated by signal SIGKILL/); -}); - -test('exec turn deadline terminates a hung child and reports timeout', async (t) => { - const pidFile = path.join(os.tmpdir(), `codex-proxy-timeout-${process.pid}.pid`); - const { port, stop } = await startProxy(null, { - CODEX_PROXY_TRANSPORT: 'exec', - CODEX_PROXY_EXEC_TURN_TIMEOUT_MS: '1000', - CODEX_PROXY_CHILD_PID_FILE: pidFile - }); - t.after(() => { - stop(); - try { fs.unlinkSync(pidFile); } catch {} - }); - - const res = await post(port, { messages: [{ role: 'user', content: 'please TIMEOUT now' }] }); - assert.equal(res.status, 500); - const body = await res.json(); - assert.match(body.error.message, /codex exec timed out after 1000ms/); - const pid = readPid(pidFile); - await waitFor(() => !isProcessAlive(pid)); -}); - -test('warm-resume timeout invalidates its cached session without launching a cold fallback', async (t) => { - const { port, home, stateHome, stop } = await startProxy(null, { - CODEX_PROXY_TRANSPORT: 'exec-resume', - CODEX_PROXY_EXEC_TURN_TIMEOUT_MS: '1000' - }); - t.after(stop); - - const first = await post(port, { messages: TURN1 }); - assert.equal(first.status, 200); - await first.text(); - - const secondMessages = [ - ...TURN1, - { role: 'assistant', content: 'Hello world' }, - { role: 'user', content: 'please RESUMETIMEOUT now' } - ]; - const second = await post(port, { messages: secondMessages }); - assert.equal(second.status, 500); - assert.match((await second.json()).error.message, /codex exec timed out after 1000ms/); - assert.equal(readInvocations(home).length, 2, 'timed-out resume must not start a third cold run'); - const sessionsPath = path.join(stateHome, 'codex-proxy', 'sessions.json'); - assert.deepEqual(JSON.parse(fs.readFileSync(sessionsPath, 'utf-8')), {}, 'timed-out resume must invalidate the cached session'); -}); - -test('exec turn timeout escalates from SIGTERM to SIGKILL', async (t) => { - const pidFile = path.join(os.tmpdir(), `codex-proxy-timeout-ignore-${process.pid}.pid`); - const { port, stop } = await startProxy(null, { - CODEX_PROXY_TRANSPORT: 'exec', - CODEX_PROXY_EXEC_TURN_TIMEOUT_MS: '1000', - CODEX_PROXY_CHILD_PID_FILE: pidFile - }); - t.after(() => { - stop(); - try { - if (fs.existsSync(pidFile)) { - const pid = readPid(pidFile); - if (isProcessAlive(pid)) process.kill(pid, 'SIGKILL'); - fs.unlinkSync(pidFile); - } - } catch {} - }); - - const startedAt = Date.now(); - const res = await post(port, { messages: [{ role: 'user', content: 'please IGNORETERM now' }] }); - assert.equal(res.status, 500); - assert.match((await res.json()).error.message, /codex exec timed out after 1000ms/); - assert.ok(Date.now() - startedAt >= 3800, 'request should settle after the SIGKILL grace period'); - const pid = readPid(pidFile); - assert.equal(isProcessAlive(pid), false, 'SIGKILL escalation must leave no child process'); -}); - -test('client disconnect terminates the exec child with the shared kill helper', async (t) => { - const pidFile = path.join(os.tmpdir(), `codex-proxy-disconnect-${process.pid}.pid`); - const { port, stop } = await startProxy(null, { - CODEX_PROXY_TRANSPORT: 'exec', - CODEX_PROXY_EXEC_TURN_TIMEOUT_MS: '60000', - CODEX_PROXY_CHILD_PID_FILE: pidFile - }); - t.after(() => { - stop(); - try { - if (fs.existsSync(pidFile)) { - const pid = readPid(pidFile); - if (isProcessAlive(pid)) process.kill(pid, 'SIGKILL'); - fs.unlinkSync(pidFile); - } - } catch {} - }); - - const controller = new AbortController(); - const pending = fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ messages: [{ role: 'user', content: 'please IGNORETERM now' }] }), - signal: controller.signal - }); - await waitFor(() => fs.existsSync(pidFile)); - const pid = readPid(pidFile); - controller.abort(); - await assert.rejects(pending); - await waitFor(() => !isProcessAlive(pid), 5000); -}); - -test('invalid exec timeout override warns once and uses the default', async (t) => { - const { port, stop, log } = await startProxy(null, { - CODEX_PROXY_TRANSPORT: 'exec', - CODEX_PROXY_EXEC_TURN_TIMEOUT_MS: '0' - }); - t.after(stop); - - const res = await post(port, { messages: [{ role: 'user', content: 'normal run' }] }); - assert.equal(res.status, 200); - assert.equal((log().match(/invalid CODEX_PROXY_EXEC_TURN_TIMEOUT_MS/g) || []).length, 1); -}); - -test('exec timeout override beyond Node timer range warns and uses the default', async (t) => { - const { port, stop, log } = await startProxy(null, { - CODEX_PROXY_TRANSPORT: 'exec', - CODEX_PROXY_EXEC_TURN_TIMEOUT_MS: '2147483648' - }); - t.after(stop); - - const res = await post(port, { messages: [{ role: 'user', content: 'normal run' }] }); - assert.equal(res.status, 200); - assert.equal((log().match(/invalid CODEX_PROXY_EXEC_TURN_TIMEOUT_MS/g) || []).length, 1); - assert.doesNotMatch(log(), /TimeoutOverflowWarning/); -}); - -test('timed-out child with a pending large stdin write does not crash the proxy', async (t) => { - const { port, stop } = await startProxy(null, { - CODEX_PROXY_TRANSPORT: 'exec', - CODEX_PROXY_EXEC_TURN_TIMEOUT_MS: '100', - CODEX_PROXY_TEST_STDIN_DELAY_MS: '500' - }); - t.after(stop); - - const content = `please wait ${'x'.repeat(5 * 1024 * 1024)}`; - const res = await post(port, { messages: [{ role: 'user', content }] }); - assert.equal(res.status, 500); - assert.match((await res.json()).error.message, /codex exec timed out after 100ms/); - assert.equal((await fetch(`http://127.0.0.1:${port}/health`)).status, 200); -}); - -const readInvocations = (home) => { - const raw = fs.readFileSync(path.join(home, 'invocations.log'), 'utf-8'); - return raw - .split('===\n') - .filter(s => s.trim()) - .map(block => { - const resume = /RESUME:(\d)/.exec(block); - const prompt = /PROMPT:([\s\S]*)$/.exec(block); - return { resume: resume && resume[1] === '1', prompt: prompt ? prompt[1] : '' }; - }); -}; - -const TURN1 = [{ role: 'user', content: 'alpha first question' }]; -const TURN2 = [ - { role: 'user', content: 'alpha first question' }, - { role: 'assistant', content: 'Hello world' }, - { role: 'user', content: 'beta second question' } -]; - -test('second turn resumes the warm session with only the new tail (#480)', async (t) => { - const { port, home, stateHome, stop } = await startProxy(); - t.after(stop); - - const r1 = await post(port, { messages: TURN1 }); - assert.equal(r1.status, 200); - assert.equal(JSON.parse(await r1.text()).choices[0].message.content, 'Hello world'); - - // The captured session id is persisted next to endpoint.json. - const saved = JSON.parse( - fs.readFileSync(path.join(stateHome, 'codex-proxy', 'sessions.json'), 'utf-8') - ); - const entries = Object.values(saved); - assert.equal(entries.length, 1); - assert.equal(entries[0].sessionId, 'stub-session-1'); - assert.equal(entries[0].fedCount, 1); - - const r2 = await post(port, { messages: TURN2 }); - assert.equal(r2.status, 200); - assert.equal(JSON.parse(await r2.text()).choices[0].message.content, 'resumed answer'); - - const invocations = readInvocations(home); - assert.equal(invocations.length, 2); - assert.equal(invocations[0].resume, false); - assert.equal(invocations[1].resume, true, 'second turn must use exec resume'); - assert.match(invocations[1].prompt, /beta second question/); - assert.doesNotMatch(invocations[1].prompt, /alpha first question/); -}); - -test('resume failure falls back to a full-history run and still answers (#480)', async (t) => { - const { port, home, stop } = await startProxy(); - t.after(stop); - - const r1 = await post(port, { messages: TURN1 }); - assert.equal(r1.status, 200); - await r1.text(); - - const turn2Fail = [ - { role: 'user', content: 'alpha first question' }, - { role: 'assistant', content: 'Hello world' }, - { role: 'user', content: 'please RESUMEFAIL now' } - ]; - const r2 = await post(port, { messages: turn2Fail }); - assert.equal(r2.status, 200, 'a failed resume must not fail the request'); - assert.equal(JSON.parse(await r2.text()).choices[0].message.content, 'Hello world'); - - const invocations = readInvocations(home); - assert.equal(invocations.length, 3, 'expected fresh, resume, then full fallback'); - assert.equal(invocations[1].resume, true); - assert.equal(invocations[2].resume, false); - assert.match(invocations[2].prompt, /alpha first question/, 'fallback must feed the full history'); - assert.match(invocations[2].prompt, /RESUMEFAIL/); -}); - -test('changed system prompt does not resume; full run instead (#480)', async (t) => { - const { port, home, stop } = await startProxy(); - t.after(stop); - - const t1 = [ - { role: 'system', content: 'be terse' }, - { role: 'user', content: 'alpha first question' } - ]; - const r1 = await post(port, { messages: t1 }); - assert.equal(r1.status, 200); - await r1.text(); - - const t2 = [ - { role: 'system', content: 'be verbose' }, - { role: 'user', content: 'alpha first question' }, - { role: 'assistant', content: 'Hello world' }, - { role: 'user', content: 'beta second question' } - ]; - const r2 = await post(port, { messages: t2 }); - assert.equal(r2.status, 200); - assert.equal(JSON.parse(await r2.text()).choices[0].message.content, 'Hello world'); - - const invocations = readInvocations(home); - assert.equal(invocations.length, 2); - assert.equal(invocations[1].resume, false, 'system change must bypass resume'); -}); - -test('session map survives a proxy restart via sessions.json (#480)', async (t) => { - const first = await startProxy(); - const r1 = await post(first.port, { messages: TURN1 }); - assert.equal(r1.status, 200); - await r1.text(); - first.stop(); - - const second = await startProxy(first); - t.after(second.stop); - const r2 = await post(second.port, { messages: TURN2 }); - assert.equal(r2.status, 200); - assert.equal(JSON.parse(await r2.text()).choices[0].message.content, 'resumed answer'); - - const invocations = readInvocations(first.home); - assert.equal(invocations.length, 2); - assert.equal(invocations[1].resume, true, 'restarted proxy must still resume'); -}); - -const AS_ENV = (fake) => ({ - CODEX_PROXY_TRANSPORT: 'app-server', - CODEX_APP_SERVER_SOCKET: fake.socketPath -}); - -test('app-server transport: two turns on one daemon thread, tail only on turn 2 (#480)', async (t) => { - const fake = await createFakeAppServer(); - t.after(fake.close); - const { port, stateHome, stop } = await startProxy(null, AS_ENV(fake)); - t.after(stop); - - const r1 = await post(port, { messages: TURN1 }); - assert.equal(r1.status, 200); - const b1 = JSON.parse(await r1.text()); - assert.equal(b1.choices[0].message.content, 'app-server answer'); - assert.equal(b1.usage.prompt_tokens, 42, 'usage must map from thread/tokenUsage/updated last.inputTokens'); - assert.equal(b1.usage.completion_tokens, 5); - assert.equal(b1.usage.prompt_tokens_details.cached_tokens, 39, 'app-server cachedInputTokens must surface as prompt_tokens_details.cached_tokens (opencode #394)'); - - const saved = JSON.parse( - fs.readFileSync(path.join(stateHome, 'codex-proxy', 'sessions.json'), 'utf-8') - ); - assert.equal(Object.values(saved)[0].threadId, 'stub-thread-1'); - - const r2 = await post(port, { messages: TURN2 }); - assert.equal(r2.status, 200); - assert.equal(JSON.parse(await r2.text()).choices[0].message.content, 'app-server answer'); - - const starts = fake.requests.filter(r => r.method === 'thread/start'); - const turns = fake.requests.filter(r => r.method === 'turn/start'); - assert.equal(starts.length, 1, 'one daemon thread per conversation'); - assert.equal(turns.length, 2); - assert.match(turns[0].text, /alpha first question/); - assert.match(turns[1].text, /beta second question/); - assert.doesNotMatch(turns[1].text, /alpha first question/, 'keyed turn must send only the new tail'); -}); - -test('app-server transport: deltas stream as SSE chunks (#480)', async (t) => { - const fake = await createFakeAppServer(); - t.after(fake.close); - const { port, stop } = await startProxy(null, AS_ENV(fake)); - t.after(stop); - const res = await post(port, { messages: TURN1, stream: true }); - assert.equal(res.status, 200); - const sse = await res.text(); - assert.match(sse, /app-/); - assert.match(sse, /server answer/); - assert.match(sse, /"prompt_tokens":42/); - assert.ok(sse.trimEnd().endsWith('data: [DONE]')); -}); - -test('app-server thread is resumed after a proxy restart via sessions.json (#480)', async (t) => { - const fake = await createFakeAppServer(); - t.after(fake.close); - const first = await startProxy(null, AS_ENV(fake)); - const r1 = await post(first.port, { messages: TURN1 }); - assert.equal(r1.status, 200); - await r1.text(); - first.stop(); - - const second = await startProxy(first, AS_ENV(fake)); - t.after(second.stop); - const r2 = await post(second.port, { messages: TURN2 }); - assert.equal(r2.status, 200); - assert.equal(JSON.parse(await r2.text()).choices[0].message.content, 'app-server answer'); - const resumes = fake.requests.filter(r => r.method === 'thread/resume'); - assert.equal(resumes.length, 1, 'restarted proxy must thread/resume the persisted thread'); - assert.equal(resumes[0].params.threadId, 'stub-thread-1'); - assert.equal(fake.requests.filter(r => r.method === 'thread/start').length, 1); -}); - -test('app-server turn failure falls back to exec and still answers (#480)', async (t) => { - const fake = await createFakeAppServer(); - t.after(fake.close); - const { port, stop } = await startProxy(null, AS_ENV(fake)); - t.after(stop); - const res = await post(port, { messages: [{ role: 'user', content: 'please ASFAIL now' }] }); - assert.equal(res.status, 200, 'a failed app-server turn must not fail the request'); - assert.equal(JSON.parse(await res.text()).choices[0].message.content, 'Hello world'); -}); - -test('app-server RPC failure falls back to exec and still answers (#480)', async (t) => { - const fake = await createFakeAppServer(); - t.after(fake.close); - const { port, stop } = await startProxy(null, AS_ENV(fake)); - t.after(stop); - const res = await post(port, { messages: [{ role: 'user', content: 'please ASRPCFAIL now' }] }); - assert.equal(res.status, 200); - assert.equal(JSON.parse(await res.text()).choices[0].message.content, 'Hello world'); -}); - -test('daemon death mid-turn falls back to exec and still answers (#480)', async (t) => { - const fake = await createFakeAppServer(); - t.after(fake.close); - const { port, stop } = await startProxy(null, AS_ENV(fake)); - t.after(stop); - const res = await post(port, { messages: [{ role: 'user', content: 'please ASKILL now' }] }); - assert.equal(res.status, 200, 'daemon death mid-turn must not fail the request'); - assert.equal(JSON.parse(await res.text()).choices[0].message.content, 'Hello world'); -}); - -test('unreachable app-server socket falls back to exec and still answers (#480)', async (t) => { - const { port, stop } = await startProxy(null, { - CODEX_PROXY_TRANSPORT: 'app-server', - CODEX_APP_SERVER_SOCKET: '/nonexistent/codex-proxy-test/app-server.sock' - }); - t.after(stop); - const res = await post(port, { messages: TURN1 }); - assert.equal(res.status, 200); - assert.equal(JSON.parse(await res.text()).choices[0].message.content, 'Hello world'); -}); - -test('CODEX_PROXY_TRANSPORT=exec-resume bypasses the app-server entirely (#480)', async (t) => { - const fake = await createFakeAppServer(); - t.after(fake.close); - const { port, stop } = await startProxy(null, { - CODEX_PROXY_TRANSPORT: 'exec-resume', - CODEX_APP_SERVER_SOCKET: fake.socketPath - }); - t.after(stop); - const res = await post(port, { messages: TURN1 }); - assert.equal(res.status, 200); - assert.equal(JSON.parse(await res.text()).choices[0].message.content, 'Hello world'); - assert.equal(fake.requests.length, 0, 'exec-resume transport must not touch the daemon'); -}); - -// --------------------------------------------------------------------------- -// Codex -> OpenCode token sync (#2533). The proxy runs the sync at startup -// against $HOME: seed a fake ~/.codex/auth.json plus a scratch opencode.db -// (via python3's sqlite3, the same interpreter the sync shells out to) and -// assert what the sync did — and did not — touch. -// --------------------------------------------------------------------------- -const runPy = (script, env = {}) => - execFileSync('python3', ['-c', script], { encoding: 'utf-8', env: { ...process.env, ...env } }); - -const SEED_SYNC_DB = ` -import os, sqlite3, json -db = os.environ['SYNC_TEST_DB'] -os.makedirs(os.path.dirname(db), exist_ok=True) -conn = sqlite3.connect(db) -conn.execute("""CREATE TABLE credential ( - id text PRIMARY KEY, integration_id text, label text NOT NULL, value text NOT NULL, - connector_id text, method_id text, active integer, - time_created integer NOT NULL, time_updated integer NOT NULL)""") -rows = [ - ('cred-active', 'openai', 'OpenAI', {'type': 'oauth', 'access': 'OLD-ACCESS', 'refresh': 'OLD-REFRESH', 'expires': 1, 'metadata': {}}, 1, 111), - ('cred-inactive', 'openai', 'OpenAI 2', {'type': 'oauth', 'access': 'OLD2-ACCESS', 'refresh': 'OLD2-REFRESH', 'expires': 1, 'metadata': {}}, 0, 222), - ('cred-alt', 'openai.alternate', 'OpenAI Alternate', {'type': 'oauth', 'access': 'ALT-ACCESS', 'refresh': 'ALT-REFRESH', 'expires': 1, 'metadata': {}}, 1, 333), -] -for rid, integ, label, val, active, tu in rows: - conn.execute('INSERT INTO credential VALUES (?,?,?,?,NULL,NULL,?,?,?)', (rid, integ, label, json.dumps(val), active, tu, tu)) -conn.commit() -conn.close() -`; - -const READ_SYNC_DB = ` -import os, sqlite3, json -conn = sqlite3.connect(os.environ['SYNC_TEST_DB']) -out = {} -for rid, value, tu in conn.execute('SELECT id, value, time_updated FROM credential'): - out[rid] = {'value': json.loads(value), 'time_updated': tu} -print(json.dumps(out)) -`; - -const seedSyncHome = (home, { corruptDb = false } = {}) => { - fs.mkdirSync(path.join(home, '.codex'), { recursive: true }); - fs.writeFileSync(path.join(home, '.codex', 'auth.json'), JSON.stringify({ - tokens: { access_token: 'NEW-ACCESS', refresh_token: 'NEW-REFRESH', account_id: 'acct-new' } - })); - const dbPath = path.join(home, '.local', 'share', 'opencode', 'opencode.db'); - fs.mkdirSync(path.dirname(dbPath), { recursive: true }); - if (corruptDb) { - fs.writeFileSync(dbPath, 'this is not a sqlite database'); - } else { - runPy(SEED_SYNC_DB, { SYNC_TEST_DB: dbPath }); - } - return dbPath; -}; - -test('token sync updates only the active base openai row (#2533)', async (t) => { - let dbPath; - const started = await startProxy(null, {}, (home) => { dbPath = seedSyncHome(home); }); - t.after(started.stop); - const rows = JSON.parse(runPy(READ_SYNC_DB, { SYNC_TEST_DB: dbPath })); - assert.equal(rows['cred-active'].value.access, 'NEW-ACCESS'); - assert.equal(rows['cred-active'].value.refresh, 'NEW-REFRESH'); - assert.equal(rows['cred-active'].value.metadata.accountID, 'acct-new'); - assert.ok(rows['cred-active'].time_updated > 111, 'active row time_updated must advance'); - assert.ok(rows['cred-active'].value.expires > Date.now(), 'active row expiry must be pushed out'); - assert.equal(rows['cred-inactive'].value.access, 'OLD2-ACCESS', 'inactive openai row must not be touched'); - assert.equal(rows['cred-inactive'].time_updated, 222); - assert.equal(rows['cred-alt'].value.access, 'ALT-ACCESS', 'openai.alternate row must not be touched'); - assert.equal(rows['cred-alt'].time_updated, 333); - assert.match(started.log(), /codex-token-sync: updated 1 credential row\(s\)/); -}); - -test('token sync stays off when CODEX_PROXY_TOKEN_SYNC=0 (opencode#1154 cutover)', async (t) => { - let dbPath; - const started = await startProxy(null, { CODEX_PROXY_TOKEN_SYNC: '0' }, (home) => { dbPath = seedSyncHome(home); }); - t.after(started.stop); - const rows = JSON.parse(runPy(READ_SYNC_DB, { SYNC_TEST_DB: dbPath })); - assert.equal(rows['cred-active'].value.access, 'OLD-ACCESS', 'sync off must leave the active row untouched'); - assert.equal(rows['cred-active'].time_updated, 111); - assert.match(started.log(), /codex-token-sync: disabled by CODEX_PROXY_TOKEN_SYNC=0/); - assert.doesNotMatch(started.log(), /codex-token-sync: updated/); -}); - -test('token sync failure is logged, not swallowed (#2533)', async (t) => { - const started = await startProxy(null, {}, (home) => { seedSyncHome(home, { corruptDb: true }); }); - t.after(started.stop); - assert.match(started.log(), /codex-token-sync FAILED:/); -}); - -test('non-object JSON body is a 400 and the proxy stays alive (#2816)', async (t) => { - const { port, stop } = await startProxy(); - t.after(stop); - for (const bad of ['null', '[1,2]', '"x"', '42']) { - const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: bad - }); - assert.equal(res.status, 400, `body ${bad} must be a 400, got ${res.status}`); - await res.text(); - } - const alive = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{bad json' - }); - assert.equal(alive.status, 400, 'proxy must still serve after non-object bodies'); - await alive.text(); -}); diff --git a/bin/provider-catalog-sync.mjs b/bin/provider-catalog-sync.mjs index 0bb21585d3..950f1450b8 100644 --- a/bin/provider-catalog-sync.mjs +++ b/bin/provider-catalog-sync.mjs @@ -36,7 +36,7 @@ // through a reviewable PR. // // #4544 split: the tracked configured default no longer carries the model -// catalogs sync-models owns (antigravity-direct, openai-codex, google, +// catalogs sync-models owns (antigravity-direct, google, // openai, cloudflare-gateway) — those live in the runtime overlay // (~/.local/state/opencode/opencode-runtime.jsonc). This tool diffs the // merged effective config (default + overlay; --runtime-config) and skips @@ -76,12 +76,23 @@ const defineValue = (obj, key, value) => { // --------------------------------------------------------------------------- const PROVIDER_SOURCES = { // No claude-code / commandcode / antigravity-agy / antigravity-ls - // entries: their CLI proxies were removed in the 2026-11-06 - // proxy-infra decommission (claude-code and commandcode were - // repointed to native fork providers on 2026-11-05; the - // antigravity doors retired 2026-10-30). Their catalogs are - // native-owned now, so they report 'no-source-configured'. - 'openai-codex': { kind: 'proxy', port: 18744, modelsDev: 'openai' }, + // / openai-codex entries: their CLI proxies were removed in the + // 2026-11-06 proxy-infra decommission (claude-code and + // commandcode were repointed to native fork providers on + // 2026-11-05; the antigravity doors retired 2026-10-30; the + // openai-codex provider was deleted 2026-11-03 and its door + // retired with the rest). Their catalogs are native-owned now, + // so they report 'no-source-configured'. + // The chatgpt entry stays as the enumeration machinery's worked + // example ONLY: its provider definition was deleted 2026-11-03 + // with openai-codex and the door program was retired + // 2026-11-06, but the CLI control fixtures (#3449/#4588) + // exercise the validated-addition path through this entry's + // source-dir snapshot and no other proxy-kind source remains. + // No live config names a chatgpt provider, so the entry is + // dormant; a run that ever names one reports the tolerated + // enumeration failure against the dead :18744 and falls back + // to cross-check only. chatgpt: { kind: 'proxy', port: 18744, modelsDev: 'openai' }, deepseek: { kind: 'crosscheck', modelsDev: 'deepseek' }, groq: { kind: 'crosscheck', modelsDev: 'groq' }, @@ -550,7 +561,6 @@ async function loadModelsDev(spec) { // but never writes them into the tracked configured default on --apply. export const SYNC_OWNED_PROVIDERS = new Set([ 'antigravity-direct', - 'openai-codex', 'google', 'openai', 'cloudflare-gateway', @@ -615,7 +625,7 @@ export async function runSync({ configPath, modelsDevSpec, sourceDir, runtimeCon providers: {}, totals: { additions_validated: 0, additions_unverified: 0, vanishings: 0, unverifiable: 0 }, }; - // Cache proxy enumerations: openai-codex and chatgpt share one door. + // Cache proxy enumerations by port: providers sharing one door share one fetch. const proxyCache = new Map(); for (const [providerId, block] of Object.entries(providers)) { const configIds = Object.keys(block?.models ?? {}); diff --git a/bin/provider-catalog-sync.test.mjs b/bin/provider-catalog-sync.test.mjs index 489163d06d..503ec854f7 100644 --- a/bin/provider-catalog-sync.test.mjs +++ b/bin/provider-catalog-sync.test.mjs @@ -433,10 +433,10 @@ test('CLI: OPENCODE_CONFIG_PATH pointing at the overlay does not redirect the ta // configured default) // --------------------------------------------------------------------------- -test('SYNC_OWNED_PROVIDERS names exactly the five sync-models-owned providers (#4544)', () => { +test('SYNC_OWNED_PROVIDERS names exactly the four sync-models-owned providers (#4544)', () => { assert.deepEqual( [...SYNC_OWNED_PROVIDERS].sort(), - ['antigravity-direct', 'cloudflare-gateway', 'google', 'openai', 'openai-codex'], + ['antigravity-direct', 'cloudflare-gateway', 'google', 'openai'], ); }); diff --git a/bin/proxy-port.test.mjs b/bin/proxy-port.test.mjs index 2ed947d1f7..243fd4ffb6 100644 --- a/bin/proxy-port.test.mjs +++ b/bin/proxy-port.test.mjs @@ -54,9 +54,9 @@ test('invalid values throw an error naming the env var and the value', () => { ]; for (const raw of invalid) { assert.throws( - () => parseProxyPortValue('CODEX_PROXY_PORT', raw, 18744), + () => parseProxyPortValue('X_PROXY_PORT', raw, 18744), (err) => { - assert.match(err.message, /CODEX_PROXY_PORT/); + assert.match(err.message, /X_PROXY_PORT/); assert.ok( err.message.includes(`"${raw}"`), `message should quote the value: ${err.message}` @@ -140,18 +140,6 @@ test('host:port addresses are parsed strictly (#494)', () => { } }); -const runCodex = (value) => - spawnSync(process.execPath, [path.join(binDir, 'codex-proxy.mjs')], { - env: { - ...process.env, - CODEX_PROXY_PORT: value, - CODEX_PROXY_TOKEN_SYNC: '0', - CODEX_PROXY_CODEX_BIN: '/bin/true' - }, - encoding: 'utf8', - timeout: 10000 - }); - const runRelay = (value) => spawnSync(process.execPath, [path.join(binDir, 'proxy-relay.mjs')], { env: { @@ -163,15 +151,6 @@ const runRelay = (value) => timeout: 10000 }); -test('codex-proxy exits at startup naming the var for abc / 0x… / 99999', () => { - for (const raw of ['abc', '0x4a38', '99999']) { - const result = runCodex(raw); - assert.equal(result.status, 1, `value ${raw}: ${result.stderr}`); - assert.match(result.stderr, /CODEX_PROXY_PORT/); - assert.ok(result.stderr.includes(`"${raw}"`), result.stderr); - assert.doesNotMatch(result.stdout, /listening/); - } -}); test('proxy-relay rejects every invalid target segment at startup', () => { const invalid = [ @@ -257,62 +236,15 @@ test('proxy-relay starts with an ordered valid target list', async (t) => { assert.equal(endpoint.relayTo, '100.99.113.103:18745'); }); -test('codex-proxy binds exactly the requested valid port', async (t) => { - const probe = net.createServer(); - await new Promise((resolve) => probe.listen(0, '127.0.0.1', resolve)); - const port = probe.address().port; - await new Promise((resolve) => probe.close(resolve)); - - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'proxy-port-test-')); - const child = spawn(process.execPath, [path.join(binDir, 'codex-proxy.mjs')], { - env: { - ...process.env, - HOME: tmp, - XDG_STATE_HOME: path.join(tmp, 'state'), - CODEX_PROXY_PORT: String(port), - CODEX_PROXY_TOKEN_SYNC: '0', - CODEX_PROXY_CODEX_BIN: '/bin/true' - }, - stdio: ['ignore', 'pipe', 'pipe'] - }); - t.after(() => child.kill()); - const listening = await new Promise((resolve, reject) => { - let out = ''; - const timer = setTimeout( - () => reject(new Error(`no listening line: ${out}`)), - 10000 - ); - child.stdout.on('data', (chunk) => { - out += chunk; - if (out.includes('listening')) { - clearTimeout(timer); - resolve(out); - } - }); - child.on('exit', () => { - clearTimeout(timer); - reject(new Error(`proxy exited early: ${out}`)); - }); - }); - assert.ok( - listening.includes(`http://127.0.0.1:${port}`), - `expected the requested port in: ${listening}` - ); - const res = await fetch(`http://127.0.0.1:${port}/health`); - assert.equal(res.status, 200); - assert.equal((await res.json()).port, port); -}); - test('every proxy port parse site in the surviving proxies uses the shared helper', () => { // Per-file inventory, named, so a rework that moves a port from one proxy // to another has to update this list on purpose instead of drifting a bare // total. The retired doors (agy-proxy, antigravity-ls-proxy and // design-code-proxy — retired 2026-10-30/2026-11-03, their bins kept - // as history until then — plus claude-code-proxy and - // commandcode-proxy) left this list with their bin programs in the + // as history until then — plus claude-code-proxy, + // commandcode-proxy and codex-proxy) left this list with their bin programs in the // 2026-11-06 proxy-infra decommission. const expected = { - 'codex-proxy.mjs': ['CODEX_PROXY_PORT'], 'muse-proxy.mjs': ['MUSE_PROXY_PORT'] }; for (const [file, names] of Object.entries(expected)) { @@ -337,33 +269,3 @@ test('every proxy port parse site in the surviving proxies uses the shared helpe ); } }); - -test('home-manager launches codex-proxy from the bin directory', () => { - // default.nix used to interpolate each script as a single store file - // (${../../bin/.mjs}); a sibling import like ./proxy-port.mjs - // cannot resolve from there. The directory form must stay where it - // is used: today that is the codex-proxy PATH wrapper (the surviving - // doors' units exec the live checkout, $HOME/code/bin, which - // satisfies the same requirement by construction). The other - // entries this test once listed were removed with their launchers: - // agy-proxy + antigravity-ls-proxy (retired 2026-10-30), - // design-code-proxy (2026-11-03), clef-proxy (2026-11-04, - // opencode#1410); the retired doors' bin programs were removed in - // the 2026-11-06 proxy-infra decommission. - const nix = fs.readFileSync( - path.join(binDir, '..', 'home', 'common', 'default.nix'), - 'utf8' - ); - for (const file of [ - 'codex-proxy.mjs' - ]) { - assert.ok( - nix.includes('${../../bin}/' + file), - `default.nix should launch ${file} via the bin directory` - ); - assert.ok( - !nix.includes('${../../bin/' + file + '}'), - `default.nix still launches ${file} as a single store file` - ); - } -}); diff --git a/bin/socket-activation.test.mjs b/bin/socket-activation.test.mjs index db871eee08..2930ca6d85 100644 --- a/bin/socket-activation.test.mjs +++ b/bin/socket-activation.test.mjs @@ -2,23 +2,14 @@ // Run: node --test bin/socket-activation.test.mjs // // Unit level: the LISTEN_FDS/LISTEN_PID parsing in socket-activation.mjs. -// Integration level: each proxy is spawned the way systemd starts it — -// a listening socket handed over as fd 3 with LISTEN_FDS=1 — and must -// answer on that socket (it never binds the port itself); the existing -// per-proxy test files cover the direct-launch fallback, where the proxy -// binds its configured port with no LISTEN_FDS in the environment. +// The integration level (spawning a proxy the way systemd starts it, +// with the listening socket handed over as fd 3) retired with the +// codex proxy in the 2026-11-06 proxy-infra decommission: it was +// the last socket-activated door. import assert from 'node:assert/strict'; -import { spawn } from 'node:child_process'; -import fs from 'node:fs'; -import net from 'node:net'; -import os from 'node:os'; -import path from 'node:path'; import test from 'node:test'; -import { fileURLToPath } from 'node:url'; import { listenTarget, systemdActivationFd } from './socket-activation.mjs'; -const binDir = path.dirname(fileURLToPath(import.meta.url)); - test('systemdActivationFd parses the LISTEN_FDS protocol', () => { assert.equal(systemdActivationFd({}, 123), null); assert.equal(systemdActivationFd({ LISTEN_FDS: '0' }, 123), null); @@ -34,53 +25,3 @@ test('listenTarget binds directly without activation, uses fd 3 with it', () => assert.deepEqual(listenTarget({ port: 18742, host: '127.0.0.1' }, {}, 123), { port: 18742, host: '127.0.0.1' }); assert.deepEqual(listenTarget({ port: 18742, host: '127.0.0.1' }, { LISTEN_FDS: '1' }, 123), { fd: 3 }); }); - -// Spawn `script` with a listening socket as fd 3, the way a systemd -// .socket unit starts its service, and wait for its /health route. -const startSocketActivated = async (script, extraEnv) => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'socket-activation-test-')); - const srv = net.createServer(); - await new Promise((resolve, reject) => { - srv.once('error', reject); - srv.listen(0, '127.0.0.1', resolve); - }); - const { port } = srv.address(); - const fd = srv._handle.fd; - const env = { - ...process.env, - HOME: tmp, - XDG_STATE_HOME: path.join(tmp, 'state'), - LISTEN_FDS: '1', - ...extraEnv(port), - }; - delete env.LISTEN_PID; - const child = spawn(process.execPath, [path.join(binDir, script)], { - env, - stdio: ['ignore', 'pipe', 'pipe', fd], - }); - // The descriptor is dup'd into the child; the parent copy can close. - srv.close(); - let log = ''; - child.stdout.on('data', (d) => { log += d; }); - child.stderr.on('data', (d) => { log += d; }); - const deadline = Date.now() + 10000; - for (;;) { - try { - const res = await fetch(`http://127.0.0.1:${port}/health`); - if (res.ok) return { child, port, log: () => log }; - } catch { /* not up yet */ } - if (child.exitCode !== null) throw new Error(`${script} exited early (${child.exitCode}):\n${log}`); - if (Date.now() > deadline) throw new Error(`${script} did not answer on the handed-off socket:\n${log}`); - await new Promise((r) => setTimeout(r, 50)); - } -}; - -test('codex-proxy serves on the systemd handed-off listener', async (t) => { - const { child, log } = await startSocketActivated('codex-proxy.mjs', (port) => ({ - CODEX_PROXY_PORT: String(port), - CODEX_PROXY_TOKEN_SYNC: '0', - CODEX_PROXY_CODEX_BIN: '/bin/true', - })); - t.after(() => { child.kill('SIGTERM'); }); - assert.match(log(), /listening on/); -}); diff --git a/home/common/default.nix b/home/common/default.nix index a936b675b6..a75d134085 100644 --- a/home/common/default.nix +++ b/home/common/default.nix @@ -17,7 +17,11 @@ let # clefProxyPort (18742) retired 2026-11-04 (opencode#1410): # the OpenChamber classifier rides the in-fork facade's # /v1/systemone (127.0.0.1:13420); the port is free. - codexProxyPort = 18744; + # codexProxyPort (18744) retired 2026-11-06 (Drew, proxy-infra + # decommission): the fork's native openai provider replaced the + # Codex CLI bridge, so the proxy had no consumers left; its let, + # units, session variable, bin program, launcher and guard row + # were removed in one change. The port is free. museProxyPort = 18747; # commandcodeProxyPort (18748) and claudeCodeProxyPort (18749) # retired 2026-11-06 (Drew, proxy-infra decommission): both @@ -703,43 +707,18 @@ in # remains the keyring credential owner and the native provider # refreshes in memory, in place. - systemd.user.services.codex-proxy = { - Unit = { - Description = "OpenAI Codex CLI (codex) Local Proxy Bridge for OpenCode"; - After = [ "network-online.target" ]; - Wants = [ "network-online.target" ]; - }; - Service = { - ExecStart = toString ( - pkgs.writeShellScript "codex-proxy-start" '' - export PATH="/run/current-system/sw/bin:$HOME/.local/bin:$PATH" - exec /run/current-system/sw/bin/node "$HOME/code/bin/codex-proxy.mjs" - '' - ); - Restart = "always"; - RestartSec = 3; - Environment = [ - "CODEX_PROXY_PORT=${toString codexProxyPort}" - "CODEX_PROXY_HOST=127.0.0.1" - # Gate 1 cutover (opencode#1154): the in-fork codex credential - # sync (opencode#1468) owns the token copy now; the door must - # not overwrite the true JWT expiry with its synthetic one. - "CODEX_PROXY_TOKEN_SYNC=0" - ]; - }; - # No Install: codex-proxy.socket owns the listener and activates this - # service on first connection (#1821). Enabling the service directly - # as well would race the socket for the same port. - }; - - systemd.user.sockets.codex-proxy = { - Unit.Description = "Codex proxy listener"; - Socket = { - ListenStream = "127.0.0.1:${toString codexProxyPort}"; - Service = "codex-proxy.service"; - }; - Install.WantedBy = [ "sockets.target" ]; - }; + # Codex proxy removed (2026-11-06, Drew): its unit + socket + # definitions stood here. The fork's native openai provider + # replaced the Codex CLI bridge -- the proxy-fronting providers + # (openai-codex, chatgpt) were deleted 2026-11-03 and their route + # legs re-seated onto openai-plan, and the token sync the door + # also performed was re-homed into the fork (opencode#1468). + # The definitions are removed, not commented out, so the switch + # stops the service and it stays off. bin/codex-proxy.mjs was + # removed in the same change. To undo: restore the two unit + # blocks, the bin program and the codexProxyPort let from git + # history, and re-add a proxy-fronting provider to + # opencode.jsonc. # Antigravity LS proxy retired (2026-10-30, Drew): its unit definition # stood here. The language-server door and the agy CLI-spawn door are @@ -1648,7 +1627,6 @@ in OPENCODE_EXPERIMENTAL_EVENT_SYSTEM = "1"; # Single source for the local proxy ports (see the let block): # opencode.jsonc reads them via {env:...} substitution. - CODEX_PROXY_PORT = toString codexProxyPort; # MUSE_PROXY_PORT below was one of three missing session # variables whose {env:...} templates in opencode.jsonc # resolved to an empty port in the OpenChamber serve @@ -1708,10 +1686,9 @@ in # their .mjs files removed in the 2026-11-06 proxy-infra # decommission — a PATH launcher would resurrect a retired door # on its canonical port. - (pkgs.writeShellScriptBin "codex-proxy" '' - export PATH="/run/current-system/sw/bin:$HOME/.local/bin:$PATH" - exec ${pkgs.nodejs}/bin/node ${../../bin}/codex-proxy.mjs "$@" - '') + # No "codex-proxy" launcher either: the door was retired + # 2026-11-06 in the proxy-infra decommission (the fork's + # native openai provider replaced the CLI bridge). (pkgs.writeShellScriptBin "sync-models" '' export PATH="/run/current-system/sw/bin:$HOME/.gemini/bin:$HOME/.local/bin:$PATH" exec ${pkgs.nodejs}/bin/node ${../../bin/sync-models.mjs} "$@" diff --git a/home/openclaw/README.md b/home/openclaw/README.md index fd854f3d86..de50512a9f 100644 --- a/home/openclaw/README.md +++ b/home/openclaw/README.md @@ -24,9 +24,9 @@ source in the fleet next to Muse (Archer) and Aster (Dot). It is installed retired — CommandCode (:18748) and Claude Code (:18749) in the 2026-11-06 proxy-infra decommission (both providers are native in the fork since 2026-11-05), Design (:18746) on 2026-11-03 and - Antigravity (:18743) on 2026-10-30. The Codex/OpenAI proxy - (:18744) is the final reserve and is deliberately not an automatic - fallback. See `workspace/QUOTAS.md`. + Antigravity (:18743) on 2026-10-30 and Codex (:18744) on + 2026-11-06 (replaced by the fork's native openai provider). + See `workspace/QUOTAS.md`. - **Coding:** ACP via the acpx plugin. The default ACP agent is `opencode` (spawn with cwd `~/code`) — the same OpenCode build/config/auth OpenChamber drives; `~/.acpx/config.json` (managed in diff --git a/home/openclaw/default.nix b/home/openclaw/default.nix index 021858e3ff..0923a5da2e 100644 --- a/home/openclaw/default.nix +++ b/home/openclaw/default.nix @@ -24,7 +24,7 @@ let homeDir = "/home/user"; # Local provider-proxy ports. The canonical definitions live in - # home/common/default.nix (codexProxyPort..museProxyPort); these are + # home/common/default.nix (museProxyPort); these are # the same numbers, repeated here because OpenClaw's config is rendered # as data, not shell env. Keep in sync with home/common. # The opencode-route provider talks to the OpenCode server facade @@ -103,7 +103,6 @@ in Unit = { After = [ "openclaw-embedding.service" - "codex-proxy.service" "mcpx.service" "opencode.service" ]; @@ -331,7 +330,7 @@ in # Laptop operations - Everything is a systemd **user** service (linger on): `systemctl --user status|restart `, logs via `journalctl --user -u `. - - Provider proxies on loopback: codex 18744, muse 18747 (the clef, agy, antigravity-ls, design-code, commandcode and claude-code doors are all retired — the last two in the 2026-11-06 proxy-infra decommission); the OpenCode server facade on 13420 is this gateway's only model route. This gateway: 18789 (tailnet). + - Provider proxy on loopback: muse 18747 (the codex, clef, agy, antigravity-ls, design-code, commandcode and claude-code doors are all retired — codex, commandcode and claude-code in the 2026-11-06 proxy-infra decommission); the OpenCode server facade on 13420 is this gateway's only model route. This gateway: 18789 (tailnet). - OpenChamber's managed OpenCode port is dynamic — read `~/.config/openchamber/managed-opencode/state.json`, never hardcode it. - Secrets are referenced by name only (Bitwarden Secrets Manager; sops files under /run/secrets/agent-auth/). Never print or commit a secret value. diff --git a/home/openclaw/workspace/TOOLS.md b/home/openclaw/workspace/TOOLS.md index ecaa39c5b7..ee31a9228b 100644 --- a/home/openclaw/workspace/TOOLS.md +++ b/home/openclaw/workspace/TOOLS.md @@ -9,7 +9,6 @@ This file is managed by Nix (source: `home/openclaw/` in the developing-today/co | `openclaw-gateway` | This gateway | tailnet, port 18789 (Control UI + WebChat) | | `openchamber` | OpenChamber server (GUI over OpenCode) | 127.0.0.1:3000, socket-activated | | `mcpx` | Standing MCP gateway daemon | config `~/.config/mcpx/config.json` | -| `codex-proxy` | ChatGPT/Codex plan proxy (OpenAI — final reserve) | 127.0.0.1:18744 | | `muse-proxy` | Meta High Usage plan proxy | 127.0.0.1:18747 | - Check one: `systemctl --user status ` · logs: `journalctl --user -u -f` diff --git a/pm-stack/PORTS.md b/pm-stack/PORTS.md index 3e5bdd72d6..81181e26d9 100644 --- a/pm-stack/PORTS.md +++ b/pm-stack/PORTS.md @@ -86,7 +86,7 @@ pattern at its atlas-search block). |---|---|---|---|---| | 18742 | clef-proxy | loopback | retired in `home/common/default.nix` (2026-11-04) | retired — free | | 18743 | agy-proxy (Antigravity) | loopback | retired 2026-10-30 (`.github/scripts/check-proxy-port-fallbacks.sh`) | retired — **stale `tailscale serve` forward still present**, pointing at a dead loopback port | -| 18744 | codex-proxy | loopback (socket-activated) + tailnet via serve | `home/common/default.nix:20` (`codexProxyPort`), unit + socket in the same file | live | +| 18744 | codex-proxy | loopback | retired 2026-11-06 (proxy-infra decommission) | retired — free (tailscale serve forward removed at kill) | | 18745 | antigravity-ls-proxy | loopback | retired 2026-10-30 | retired — **stale `tailscale serve` forward still present** | | 18746 | design-code-proxy | loopback | retired 2026-11-03 (`home/common/default.nix` comment block) | retired — **stale `tailscale serve` forward still present** | | 18747 | muse-proxy | loopback | `home/common/default.nix:21` (`museProxyPort`) | live |