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/3] 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/3] 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 From 77d462ae2b1ea828b94152501470272981a7ba31 Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Sat, 24 Oct 2026 16:39:03 +0000 Subject: [PATCH 3/3] codex-proxy: warm app-server daemon transport as lead route (#480) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit One persistent WebSocket-over-Unix-socket connection to the managed codex app-server daemon (~/.codex/app-server-control/*.sock): initialize handshake once at first use, conversations map to daemon threads with the same keying/prefix-validation/persisted-LRU discipline as the exec resume build, keyed turns send only the new tail via turn/start, deltas stream as SSE, usage maps from thread/tokenUsage/updated (last). Raw floor on the laptop daemon (0.164.0), gpt-5.6-luna: thread/start 5.1s, turn 1 14.4s, turn 2 2.15s — vs 46s/56s for the exec-resume build on the same model and script. The stdio bridge (codex app-server proxy) never answered an initialize against this daemon; the direct control socket (WebSocket over UDS) answers instantly and needs no child. CODEX_PROXY_TRANSPORT=app-server (default) | exec-resume | exec. Any app-server failure before response commit — daemon down, thread lost, RPC error, daemon death mid-turn — falls back to exec-resume, then exec; one reconnect attempt precedes the fallback. sync of Codex tokens to OpenCode preserved unchanged. --- bin/codex-proxy.mjs | 434 ++++++++++++++++++++++++++++++++++++++- bin/codex-proxy.test.mjs | 248 +++++++++++++++++++++- 2 files changed, 675 insertions(+), 7 deletions(-) diff --git a/bin/codex-proxy.mjs b/bin/codex-proxy.mjs index 3cc26dc39f..d9a21e38b2 100755 --- a/bin/codex-proxy.mjs +++ b/bin/codex-proxy.mjs @@ -1,5 +1,6 @@ #!/usr/bin/env node import http from 'node:http'; +import net from 'node:net'; import { spawn, execSync } from 'node:child_process'; import crypto from 'node:crypto'; import fs from 'node:fs'; @@ -106,6 +107,21 @@ const findCodexBinary = () => { const CODEX_BIN = findCodexBinary(); +// 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) => { let rawModel = (requestedModel || 'gpt-6.1-sol').trim(); // Strip any provider prefix before '/' (e.g. 'openai-codex/', 'codex/', 'openai/', 'chatgpt/') @@ -225,7 +241,7 @@ const loadSessions = () => { for (const [key, entry] of Object.entries(raw)) { if ( entry && - typeof entry.sessionId === 'string' && + (typeof entry.sessionId === 'string' || typeof entry.threadId === 'string') && Array.isArray(entry.fedHashes) && now - (entry.lastUsed || 0) <= SESSION_TTL_MS ) { @@ -311,10 +327,15 @@ const planResume = (messages, fullName) => { return { key, entry, tailMessages }; }; -const recordSession = (key, sessionId, messages) => { - if (!key || !sessionId) return; +const recordSession = (key, sessionId, messages, threadId) => { + if (!key || (!sessionId && !threadId)) return; + const prev = loadSessions().get(key) || {}; loadSessions().set(key, { - sessionId, + // 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() @@ -322,10 +343,376 @@ const recordSession = (key, sessionId, messages) => { 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, + fail: (err) => { + client.turnStates.delete(threadId); + done({ ok: false, content: state.content, promptTokens: state.promptTokens, completionTokens: state.completionTokens, 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; + } 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, 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, 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 }; +}; + // 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 @@ -520,6 +907,7 @@ const server = http.createServer((req, res) => { service: 'openai-codex-proxy', port: PORT, binary: CODEX_BIN, + transport: TRANSPORT, defaultModel: 'gpt-5.6-luna-low' }, null, 2)); return; @@ -697,10 +1085,46 @@ const server = http.createServer((req, res) => { }); const onSpawn = (c) => { currentChild = c; }; + // 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 = planResume(body.messages, fullName); + const plan = TRANSPORT === 'exec' ? null : planResume(body.messages, fullName); if (plan) { const tailPrompt = formatPrompt(plan.tailMessages); const attempt = await runCodexOnce({ diff --git a/bin/codex-proxy.test.mjs b/bin/codex-proxy.test.mjs index dc7f86c0b9..4eb7d3745e 100644 --- a/bin/codex-proxy.test.mjs +++ b/bin/codex-proxy.test.mjs @@ -10,6 +10,7 @@ // partial output. import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; +import crypto from 'node:crypto'; import fs from 'node:fs'; import net from 'node:net'; import os from 'node:os'; @@ -66,6 +67,123 @@ case "$prompt" in esac `; + +// --------------------------------------------------------------------------- +// 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 }, total: { inputTokens: 42, outputTokens: 5 } } } }); + 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); @@ -75,7 +193,7 @@ const freePort = () => new Promise((resolve, reject) => { }); }); -const startProxy = async (reuse) => { +const startProxy = async (reuse, extraEnv = {}) => { 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 }); @@ -87,7 +205,8 @@ const startProxy = async (reuse) => { ...process.env, HOME: home, XDG_STATE_HOME: stateHome, - CODEX_PROXY_PORT: String(port) + CODEX_PROXY_PORT: String(port), + ...extraEnv }, stdio: ['ignore', 'pipe', 'pipe'] }); @@ -301,3 +420,128 @@ test('session map survives a proxy restart via sessions.json (#480)', async (t) 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); + + 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'); +});