From 542db84f77dda093927a43ab8f80d698b6297315 Mon Sep 17 00:00:00 2001 From: "Muse (sandbox agent)" Date: Sat, 24 Oct 2026 16:08:15 +0000 Subject: [PATCH 1/2] codex-proxy: warm resumable exec sessions keyed by conversation (#480) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit First turn of a conversation runs codex exec without --ephemeral and captures the session id from the thread.started JSON event; later turns run codex exec resume with only the new non-assistant tail. Key = sha256(resolved model/effort + system prompt + first user message). Session map persisted to sessions.json in the proxy state dir (LRU 64, 2h TTL). Any resume failure falls back to a full-history fresh run and re-keys. syncCodexTokensToOpenCode, endpoint.json, port parsing and SSE behaviour unchanged. Tests: 4 new warm-session tests (resume tail-only, resume-failure fallback, system-prompt change bypass, restart persistence) alongside the existing #676/#680 failure tests — 10/10 pass. --- bin/codex-proxy.mjs | 601 +++++++++++++++++++++++++++------------ bin/codex-proxy.test.mjs | 148 +++++++++- 2 files changed, 559 insertions(+), 190 deletions(-) diff --git a/bin/codex-proxy.mjs b/bin/codex-proxy.mjs index 1e6696b90d..ee8c69732a 100755 --- a/bin/codex-proxy.mjs +++ b/bin/codex-proxy.mjs @@ -183,6 +183,322 @@ const formatPrompt = (messages) => { 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' && + 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) => { + if (!key || !sessionId) return; + loadSessions().set(key, { + sessionId, + fedCount: messages.length, + fedHashes: messages.map(messageHash), + lastUsed: Date.now() + }); + saveSessions(); +}; + +const forgetSession = (key) => { + if (key && loadSessions().delete(key)) saveSessions(); +}; + +// 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; + const done = (result) => { + if (!settled) { + settled = true; + 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; + } + if (onSpawn) onSpawn(child); + + console.log(`[codex-proxy] Spawning: ${CODEX_BIN} ${args.join(' ')}`); + + // Write prompt to stdin and close stdin + child.stdin.write(prompt); + child.stdin.end(); + + let lineBuffer = ''; + let fullContent = ''; + let promptTokens = Math.max(1, Math.ceil(prompt.length / 4)); + let completionTokens = 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; + + 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; + } + } + } catch (err) { + // Non-JSON line or parser error ignored + } + }; + + child.stdout.on('data', (chunk) => { + lineBuffer += chunk.toString('utf-8'); + const lines = lineBuffer.split('\n'); + lineBuffer = lines.pop(); // remainder + for (const line of lines) { + processJsonLine(line); + } + }); + + child.stderr.on('data', (chunk) => { + const msg = chunk.toString('utf-8'); + 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)); + } + + // 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}` + : `codex exec exited with code ${code}`; + const detail = (turnFailedMessage || stderrLine || fallback).trim(); + done({ + ok: false, + content: fullContent, + promptTokens, + completionTokens, + sessionId, + detail + }); + return; + } + + done({ + ok: true, + content: fullContent, + promptTokens, + completionTokens, + sessionId, + detail: null + }); + }); + + child.on('error', (err) => { + console.error(`[codex-proxy child error] ${err.message}`); + spawnError = err; + }); + }); + const server = http.createServer((req, res) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); @@ -272,11 +588,11 @@ const server = http.createServer((req, res) => { const chatId = `chatcmpl-codex-${crypto.randomUUID()}`; const created = Math.floor(Date.now() / 1000); - // Spawn arguments for codex exec - const args = [ - 'exec', + // 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', - '--ephemeral', '--skip-git-repo-check', '--dangerously-bypass-approvals-and-sandbox', '--disable', 'shell_tool', @@ -284,42 +600,14 @@ const server = http.createServer((req, res) => { '-m', baseModel, '-c', `model_reasoning_effort="${effort}"`, '-c', 'model_context_window=1000000', - '-c', 'model_auto_compact_token_limit=950000', - '-' + '-c', 'model_auto_compact_token_limit=950000' ]; + const freshArgs = ['exec', ...commonArgs, '-']; + const resumeArgs = (sessionId) => ['exec', 'resume', ...commonArgs, sessionId, '-']; // Refresh OpenCode tokens in background syncCodexTokensToOpenCode(); - console.log(`[codex-proxy] Spawning: ${CODEX_BIN} ${args.join(' ')}`); - - 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) { - console.error(`[codex-proxy] Failed to spawn codex: ${err.message}`); - res.writeHead(500, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ error: { message: `Failed to spawn codex: ${err.message}` } })); - return; - } - - // Write prompt to stdin and close stdin - child.stdin.write(prompt); - child.stdin.end(); - - res.on('close', () => { - if (!res.writableEnded) { - try { child.kill('SIGTERM'); } catch (_) {} - } - }); - if (stream) { res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', @@ -329,157 +617,41 @@ const server = http.createServer((req, res) => { }); } - let lineBuffer = ''; - let fullContent = ''; - let promptTokens = Math.max(1, Math.ceil(prompt.length / 4)); - let completionTokens = 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; - - const processJsonLine = (line) => { - const trimmed = line.trim(); - if (!trimmed || !trimmed.startsWith('{')) return; - - try { - const event = JSON.parse(trimmed); - - // Agent message completed - if (event.type === 'item.completed' && event.item && event.item.type === 'agent_message' && typeof event.item.text === 'string') { - const text = event.item.text; - fullContent += text; - - if (stream && !res.writableEnded) { - const chunk = { - id: chatId, - object: 'chat.completion.chunk', - created, - model: fullName, - choices: [{ - index: 0, - delta: { content: text }, - finish_reason: null - }] - }; - res.write(`data: ${JSON.stringify(chunk)}\n\n`); - } - } - - // 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') { - const msg = typeof event.error === 'string' - ? event.error - : (event.error && typeof event.error.message === 'string' ? event.error.message : ''); - turnFailedMessage = msg; - } - - // 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; - } - } - } catch (err) { - // Non-JSON line or parser error ignored - } + 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`); }; - child.stdout.on('data', chunk => { - lineBuffer += chunk.toString('utf-8'); - const lines = lineBuffer.split('\n'); - lineBuffer = lines.pop(); // remainder - for (const line of lines) { - processJsonLine(line); - } - }); - - child.stderr.on('data', chunk => { - const msg = chunk.toString('utf-8'); - 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 = ''; - } - + const sendSuccess = (result, replay) => { if (res.writableEnded) 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 — it used to be reported as - // a successful 'stop' carrying the truncated text (or an - // empty 200 when nothing was produced at all). - if (code !== 0 || turnFailedMessage !== null) { - const stderrLine = stderrTail.trim().split('\n').pop(); - const fallback = spawnError - ? spawnError.message - : signal - ? `codex exec terminated by signal ${signal}` - : `codex exec exited with code ${code}`; - const detail = (turnFailedMessage || stderrLine || fallback).trim(); - 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). - if (!res.writableEnded) { - 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)); - return; - } - + const usage = { + prompt_tokens: result.promptTokens, + completion_tokens: result.completionTokens, + total_tokens: result.promptTokens + result.completionTokens + }; if (stream) { - if (completionTokens === 0 && fullContent.length > 0) { - completionTokens = Math.max(1, Math.ceil(fullContent.length / 4)); - } - + // 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: { - prompt_tokens: promptTokens, - completion_tokens: completionTokens, - total_tokens: promptTokens + completionTokens - } + 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 { - if (completionTokens === 0 && fullContent.length > 0) { - completionTokens = Math.max(1, Math.ceil(fullContent.length / 4)); - } - res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ id: chatId, @@ -488,28 +660,85 @@ const server = http.createServer((req, res) => { model: fullName, choices: [{ index: 0, - message: { - role: 'assistant', - content: fullContent - }, + message: { role: 'assistant', content: result.content }, finish_reason: 'stop' }], - usage: { - prompt_tokens: promptTokens, - completion_tokens: completionTokens, - total_tokens: promptTokens + completionTokens - } + usage }, null, 2)); } - }); + }; - child.on('error', err => { - console.error(`[codex-proxy child error] ${err.message}`); - spawnError = err; + 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({ error: { message: `Codex execution error: ${err.message}` } })); } + res.end(JSON.stringify(errorBody)); + }; + + (async () => { + let currentChild = null; + res.on('close', () => { + if (!res.writableEnded && currentChild) { + try { currentChild.kill('SIGTERM'); } catch (_) {} + } + }); + const onSpawn = (c) => { currentChild = c; }; + + // 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 = 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; + } + 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; diff --git a/bin/codex-proxy.test.mjs b/bin/codex-proxy.test.mjs index dc83c5c7a1..dc7f86c0b9 100644 --- a/bin/codex-proxy.test.mjs +++ b/bin/codex-proxy.test.mjs @@ -21,6 +21,26 @@ const binDir = path.dirname(fileURLToPath(import.meta.url)); const STUB = `#!/bin/sh 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 + *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 @@ -39,6 +59,7 @@ case "$prompt" in *SIGKILLME*) kill -9 $$ ;; *) + 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}}' exit 0 ;; @@ -54,17 +75,18 @@ const freePort = () => new Promise((resolve, reject) => { }); }); -const startProxy = async () => { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-proxy-test-')); +const startProxy = async (reuse) => { + 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 }); + 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: path.join(tmp, 'state'), + XDG_STATE_HOME: stateHome, CODEX_PROXY_PORT: String(port) }, stdio: ['ignore', 'pipe', 'pipe'] @@ -81,7 +103,7 @@ const startProxy = async () => { if (Date.now() > deadline) throw new Error(`proxy did not start:\n${log}`); await new Promise(r => setTimeout(r, 50)); } - return { port, stop: () => child.kill('SIGKILL') }; + return { port, tmp, home, stateHome, stop: () => child.kill('SIGKILL') }; }; const post = (port, body) => fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { @@ -161,3 +183,121 @@ test('empty-stderr fallback names the killing signal, not code null (#676)', asy t.after(stop); await assertFailure(port, 'SIGKILLME', /Codex execution failed: codex exec terminated by signal SIGKILL/); }); + +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'); +}); From 6f0a33ccbb88281a1cc693a6f6a30d6a1232b87d Mon Sep 17 00:00:00 2001 From: "Muse (sandbox agent)" Date: Sat, 24 Oct 2026 16:15:01 +0000 Subject: [PATCH 2/2] codex-proxy: exec resume has no --color flag (verified on laptop codex-cli 0.160.0) Passing --color to 'codex exec resume' is a clap usage error (exit 2). Probe on amd: resume with the shared option set minus --color succeeds, re-emits thread.started with the same thread_id, and answers from the resumed session. --- bin/codex-proxy.mjs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/bin/codex-proxy.mjs b/bin/codex-proxy.mjs index ee8c69732a..3cc26dc39f 100755 --- a/bin/codex-proxy.mjs +++ b/bin/codex-proxy.mjs @@ -596,13 +596,15 @@ const server = http.createServer((req, res) => { '--skip-git-repo-check', '--dangerously-bypass-approvals-and-sandbox', '--disable', 'shell_tool', - '--color', 'never', '-m', baseModel, '-c', `model_reasoning_effort="${effort}"`, '-c', 'model_context_window=1000000', '-c', 'model_auto_compact_token_limit=950000' ]; - const freshArgs = ['exec', ...commonArgs, '-']; + 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