diff --git a/bin/codex-proxy.mjs b/bin/codex-proxy.mjs index 7745ba0f70..8027b668b4 100755 --- a/bin/codex-proxy.mjs +++ b/bin/codex-proxy.mjs @@ -14,6 +14,27 @@ 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 @@ -841,6 +862,35 @@ const runAppServerOnce = async ({ messages, fullName, baseModel, effort, prompt, 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 @@ -849,9 +899,12 @@ const runAppServerOnce = async ({ messages, fullName, baseModel, effort, prompt, 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); } }; @@ -870,13 +923,17 @@ const runCodexOnce = ({ args, prompt, emit, onSpawn }) => done({ ok: false, content: '', sessionId: null, detail: err.message }); return; } - if (onSpawn) onSpawn(child); + const killChild = createExecChildKiller(child); + if (onSpawn) onSpawn(child, killChild); - console.log(`[codex-proxy] Spawning: ${CODEX_BIN} ${args.join(' ')}`); + timeoutTimer = setTimeout(() => { + timeoutTimer = null; + timedOut = true; + killChild(); + }, EXEC_TURN_TIMEOUT_MS); + timeoutTimer.unref?.(); - // Write prompt to stdin and close stdin - child.stdin.write(prompt); - child.stdin.end(); + console.log(`[codex-proxy] Spawning: ${CODEX_BIN} ${args.join(' ')}`); let lineBuffer = ''; const stdoutDecoder = createStreamDecoder(); @@ -894,6 +951,21 @@ const runCodexOnce = ({ args, prompt, emit, onSpawn }) => 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; @@ -980,6 +1052,22 @@ const runCodexOnce = ({ args, prompt, emit, onSpawn }) => 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, @@ -1231,13 +1319,11 @@ const server = http.createServer(async (req, res) => { }; (async () => { - let currentChild = null; + let currentKillChild = null; res.on('close', () => { - if (!res.writableEnded && currentChild) { - try { currentChild.kill('SIGTERM'); } catch (_) {} - } + if (!res.writableEnded && currentKillChild) currentKillChild(); }); - const onSpawn = (c) => { currentChild = c; }; + 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 @@ -1295,6 +1381,11 @@ const server = http.createServer(async (req, res) => { 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` ); diff --git a/bin/codex-proxy.test.mjs b/bin/codex-proxy.test.mjs index 83a0402f4e..bb42675dba 100644 --- a/bin/codex-proxy.test.mjs +++ b/bin/codex-proxy.test.mjs @@ -30,6 +30,9 @@ 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 @@ -41,6 +44,8 @@ for a in "$@"; do [ "$a" = "resume" ] && resume=1; done } >> "$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 ;; @@ -77,6 +82,10 @@ case "$prompt" in 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"}}' @@ -272,6 +281,27 @@ const post = (port, body) => fetch(`http://127.0.0.1:${port}/v1/chat/completions 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` }]; @@ -390,6 +420,149 @@ test('empty-stderr fallback names the killing signal, not code null (#676)', asy 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