Spaces:
Paused
fix: detect empty Codex responses and auto-retry with account rotation (#18)
Browse files* fix: detect empty Codex responses and auto-retry with account rotation
Codex API intermittently returns HTTP 200 with valid SSE events but zero
text deltas. Add EmptyResponseError detection in all three translation
layers (OpenAI, Anthropic, Gemini) and a retry loop in proxy-handler
that switches accounts on empty responses (up to 3 attempts).
- Non-streaming: catch EmptyResponseError → release account → acquire
new account → retry with fresh CodexApi (max 2 retries)
- Streaming: inject "[Error] Codex returned an empty response" text
chunk when response.completed fires with no content
- All retries exhausted → 502 with clear error message
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: prevent double-release of account in empty-response retry loop
The outer catch block used the original entryId, which was already
released when EmptyResponseError switched to a new account. Introduce
activeEntryId to track the currently-active account across retries.
Also set EmptyResponseError.name for proper serialization.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
---------
Co-authored-by: icebear0828 <icebear0828@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Files changed (6)
7 unmodified lines89101112137 unmodified lines### Added- 自动提取 Chromium 版本:`extract-fingerprint.ts` 从 `package.json` 读取 Electron 版本,通过 `electron-to-chromium` 映射为 Chromium 大版本,`apply-update.ts` 自动更新 `chromium_version` 和 TLS impersonate profile- 动态模型列表:后台从 Codex 后端自动获取模型目录,与静态 YAML 合并(`src/models/model-store.ts`、`src/models/model-fetcher.ts`)- `/debug/models` 诊断端点,展示模型来源(static/backend)与刷新状态7 unmodified lines8910111213147 unmodified lines### Added- 空响应检测 + 自动换号重试:Codex API 返回 HTTP 200 但无内容时,非流式自动切换账号重试(最多 3 次),流式注入错误提示文本- 自动提取 Chromium 版本:`extract-fingerprint.ts` 从 `package.json` 读取 Electron 版本,通过 `electron-to-chromium` 映射为 Chromium 大版本,`apply-update.ts` 自动更新 `chromium_version` 和 TLS impersonate profile- 动态模型列表:后台从 Codex 后端自动获取模型目录,与静态 YAML 合并(`src/models/model-store.ts`、`src/models/model-fetcher.ts`)- `/debug/models` 诊断端点,展示模型来源(static/backend)与刷新状态
11 unmodified lines12131415161754 unmodified lines72737475767767 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419511 unmodified linesimport { randomUUID } from "crypto";import { CodexApi, CodexApiError } from "../../proxy/codex-api.js";import type { CodexResponsesRequest } from "../../proxy/codex-api.js";import type { AccountPool } from "../../auth/account-pool.js";import type { SessionManager } from "../../session/manager.js";import type { CookieJar } from "../../proxy/cookie-jar.js";54 unmodified linesconst { entryId, token, accountId } = acquired;const codexApi = new CodexApi(token, accountId, cookieJar, entryId);// 2. Session lookup for multi-turnconst existingSession = sessionManager.findSession(req.sessionMessages);67 unmodified lines}});} else {try {const result = await fmt.collectTranslator(codexApi,rawResponse,req.model,);if (result.responseId) {const taskId = `task-${randomUUID()}`;sessionManager.storeSession(taskId,"turn-1",req.sessionMessages,);sessionManager.updateResponseId(taskId, result.responseId);}accountPool.release(entryId, result.usage);return c.json(result.response);} catch (collectErr) {accountPool.release(entryId);const msg = collectErr instanceof Error ? collectErr.message : "Unknown error";c.status(502);return c.json(fmt.formatError(502, msg));}}} catch (err) {// 5. Error handling with format-specific responsesif (err instanceof CodexApiError) {console.error(`[${fmt.tag}] Account ${entryId} | Codex API error:`,err.message,);if (err.status === 429) {// P1-6: Count 429s as requests via encapsulated API (no direct entry mutation)accountPool.markRateLimited(entryId, { countRequest: true });c.status(429);return c.json(fmt.format429(err.message));}accountPool.release(entryId);const code = (err.status >= 400 && err.status < 600 ? err.status : 502) as StatusCode;c.status(code);return c.json(fmt.formatError(code, err.message));}accountPool.release(entryId);throw err;}}11 unmodified lines1213141516171854 unmodified lines737475767778798067 unmodified lines14814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724811 unmodified linesimport { randomUUID } from "crypto";import { CodexApi, CodexApiError } from "../../proxy/codex-api.js";import type { CodexResponsesRequest } from "../../proxy/codex-api.js";import { EmptyResponseError } from "../../translation/codex-event-extractor.js";import type { AccountPool } from "../../auth/account-pool.js";import type { SessionManager } from "../../session/manager.js";import type { CookieJar } from "../../proxy/cookie-jar.js";54 unmodified linesconst { entryId, token, accountId } = acquired;const codexApi = new CodexApi(token, accountId, cookieJar, entryId);// Tracks which account the outer catch should release (updated by retry loop)let activeEntryId = entryId;// 2. Session lookup for multi-turnconst existingSession = sessionManager.findSession(req.sessionMessages);67 unmodified lines}});} else {// Non-streaming: retry loop for empty responses (switch accounts)const MAX_EMPTY_RETRIES = 2;let currentEntryId = entryId;let currentCodexApi = codexApi;let currentRawResponse = rawResponse;for (let attempt = 1; ; attempt++) {try {const result = await fmt.collectTranslator(currentCodexApi,currentRawResponse,req.model,);if (result.responseId) {const taskId = `task-${randomUUID()}`;sessionManager.storeSession(taskId,"turn-1",req.sessionMessages,);sessionManager.updateResponseId(taskId, result.responseId);}accountPool.release(currentEntryId, result.usage);return c.json(result.response);} catch (collectErr) {if (collectErr instanceof EmptyResponseError && attempt <= MAX_EMPTY_RETRIES) {console.warn(`[${fmt.tag}] Account ${currentEntryId} | Empty response (attempt ${attempt}/${MAX_EMPTY_RETRIES + 1}), switching account...`,);accountPool.release(currentEntryId, collectErr.usage);// Acquire a new accountconst newAcquired = accountPool.acquire();if (!newAcquired) {console.warn(`[${fmt.tag}] No available account for retry`);c.status(502);return c.json(fmt.formatError(502, "Codex returned an empty response and no other accounts are available for retry"));}currentEntryId = newAcquired.entryId;activeEntryId = currentEntryId;currentCodexApi = new CodexApi(newAcquired.token, newAcquired.accountId, cookieJar, newAcquired.entryId);try {currentRawResponse = await withRetry(() => currentCodexApi.createResponse(req.codexRequest, abortController.signal),{ tag: fmt.tag },);} catch (retryErr) {accountPool.release(currentEntryId);if (retryErr instanceof CodexApiError) {const code = (retryErr.status >= 400 && retryErr.status < 600 ? retryErr.status : 502) as StatusCode;c.status(code);return c.json(fmt.formatError(code, retryErr.message));}throw retryErr;}continue;}// Not an empty response error, or retries exhaustedaccountPool.release(currentEntryId);if (collectErr instanceof EmptyResponseError) {console.warn(`[${fmt.tag}] Account ${currentEntryId} | Empty response (attempt ${attempt}/${MAX_EMPTY_RETRIES + 1}), all retries exhausted`,);c.status(502);return c.json(fmt.formatError(502, "Codex returned empty responses across all available accounts"));}const msg = collectErr instanceof Error ? collectErr.message : "Unknown error";c.status(502);return c.json(fmt.formatError(502, msg));}}}} catch (err) {// 5. Error handling with format-specific responsesif (err instanceof CodexApiError) {console.error(`[${fmt.tag}] Account ${activeEntryId} | Codex API error:`,err.message,);if (err.status === 429) {// P1-6: Count 429s as requests via encapsulated API (no direct entry mutation)accountPool.markRateLimited(activeEntryId, { countRequest: true });c.status(429);return c.json(fmt.format429(err.message));}accountPool.release(activeEntryId);const code = (err.status >= 400 && err.status < 600 ? err.status : 502) as StatusCode;c.status(code);return c.json(fmt.formatError(code, err.message));}accountPool.release(activeEntryId);throw err;}}
32 unmodified lines33343536373832 unmodified linesarguments: string;}export interface ExtractedEvent {typed: TypedCodexEvent;responseId?: string;32 unmodified lines3334353637383940414243444546474832 unmodified linesarguments: string;}export class EmptyResponseError extends Error {constructor(public readonly responseId: string | null,public readonly usage: UsageInfo | undefined,) {super("Codex returned an empty response");this.name = "EmptyResponseError";}}export interface ExtractedEvent {typed: TypedCodexEvent;responseId?: string;
15 unmodified lines1617181920212220 unmodified lines43444546474851 unmodified lines10010110210310410550 unmodified lines15615715815916016118 unmodified lines18018118218318418566 unmodified lines25225325425525625715 unmodified linesAnthropicMessagesResponse,AnthropicUsage,} from "../types/anthropic.js";import { iterateCodexEvents } from "./codex-event-extractor.js";export interface AnthropicUsageInfo {input_tokens: number;20 unmodified lineslet outputTokens = 0;let inputTokens = 0;let hasToolCalls = false;let contentIndex = 0;let textBlockStarted = false;const callIdsWithDeltas = new Set<string>();51 unmodified lines// Handle function call start → close text block, open tool_use blockif (evt.functionCallStart) {hasToolCalls = true;// Close text block if still openif (textBlockStarted) {50 unmodified linesswitch (evt.typed.type) {case "response.output_text.delta": {if (evt.textDelta) {// Reopen a text block if the previous one was closed (e.g. after tool calls)if (!textBlockStarted) {yield formatSSE("content_block_start", {18 unmodified linesoutputTokens = evt.usage.output_tokens;onUsage?.({ input_tokens: inputTokens, output_tokens: outputTokens });}break;}}66 unmodified lines}}const hasToolCalls = toolUseBlocks.length > 0;const content: AnthropicContentBlock[] = [];if (fullText) {15 unmodified lines1617181920212220 unmodified lines4344454647484951 unmodified lines10110210310410510610750 unmodified lines15815916016116216316418 unmodified lines18318418518618718818919019119219319419519666 unmodified lines26326426526626726826927027127227315 unmodified linesAnthropicMessagesResponse,AnthropicUsage,} from "../types/anthropic.js";import { iterateCodexEvents, EmptyResponseError } from "./codex-event-extractor.js";export interface AnthropicUsageInfo {input_tokens: number;20 unmodified lineslet outputTokens = 0;let inputTokens = 0;let hasToolCalls = false;let hasContent = false;let contentIndex = 0;let textBlockStarted = false;const callIdsWithDeltas = new Set<string>();51 unmodified lines// Handle function call start → close text block, open tool_use blockif (evt.functionCallStart) {hasToolCalls = true;hasContent = true;// Close text block if still openif (textBlockStarted) {50 unmodified linesswitch (evt.typed.type) {case "response.output_text.delta": {if (evt.textDelta) {hasContent = true;// Reopen a text block if the previous one was closed (e.g. after tool calls)if (!textBlockStarted) {yield formatSSE("content_block_start", {18 unmodified linesoutputTokens = evt.usage.output_tokens;onUsage?.({ input_tokens: inputTokens, output_tokens: outputTokens });}// Inject error text if stream completed with no contentif (!hasContent && textBlockStarted) {yield formatSSE("content_block_delta", {type: "content_block_delta",index: contentIndex,delta: { type: "text_delta", text: "[Error] Codex returned an empty response. Please retry." },});}break;}}66 unmodified lines}}// Detect empty response (HTTP 200 but no content)if (!fullText && toolUseBlocks.length === 0 && outputTokens === 0) {throw new EmptyResponseError(responseId, { input_tokens: inputTokens, output_tokens: outputTokens });}const hasToolCalls = toolUseBlocks.length > 0;const content: AnthropicContentBlock[] = [];if (fullText) {
14 unmodified lines1516171819202113 unmodified lines35363738394019 unmodified lines60616263646522 unmodified lines88899091929318 unmodified lines11211311411511611771 unmodified lines18919019119219319414 unmodified linesGeminiUsageMetadata,GeminiPart,} from "../types/gemini.js";import { iterateCodexEvents } from "./codex-event-extractor.js";export interface GeminiUsageInfo {input_tokens: number;13 unmodified lines): AsyncGenerator<string> {let inputTokens = 0;let outputTokens = 0;for await (const evt of iterateCodexEvents(codexApi, rawResponse)) {if (evt.responseId) onResponseId?.(evt.responseId);19 unmodified lines// Function call done → emit as a candidate with functionCall partif (evt.functionCallDone) {let args: Record<string, unknown> = {};try {args = JSON.parse(evt.functionCallDone.arguments) as Record<string, unknown>;22 unmodified linesswitch (evt.typed.type) {case "response.output_text.delta": {if (evt.textDelta) {const chunk: GeminiGenerateContentResponse = {candidates: [{18 unmodified linesonUsage?.({ input_tokens: inputTokens, output_tokens: outputTokens });}// Final chunk with finishReason and usageconst finalChunk: GeminiGenerateContentResponse = {candidates: [71 unmodified linestotalTokenCount: inputTokens + outputTokens,};// Build response parts: text + function callsconst parts: GeminiPart[] = [];if (fullText) {14 unmodified lines1516171819202113 unmodified lines3536373839404119 unmodified lines6162636465666722 unmodified lines9091929394959618 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613771 unmodified lines20921021121221321421521621721821914 unmodified linesGeminiUsageMetadata,GeminiPart,} from "../types/gemini.js";import { iterateCodexEvents, EmptyResponseError } from "./codex-event-extractor.js";export interface GeminiUsageInfo {input_tokens: number;13 unmodified lines): AsyncGenerator<string> {let inputTokens = 0;let outputTokens = 0;let hasContent = false;for await (const evt of iterateCodexEvents(codexApi, rawResponse)) {if (evt.responseId) onResponseId?.(evt.responseId);19 unmodified lines// Function call done → emit as a candidate with functionCall partif (evt.functionCallDone) {hasContent = true;let args: Record<string, unknown> = {};try {args = JSON.parse(evt.functionCallDone.arguments) as Record<string, unknown>;22 unmodified linesswitch (evt.typed.type) {case "response.output_text.delta": {if (evt.textDelta) {hasContent = true;const chunk: GeminiGenerateContentResponse = {candidates: [{18 unmodified linesonUsage?.({ input_tokens: inputTokens, output_tokens: outputTokens });}// Inject error text if stream completed with no contentif (!hasContent) {const emptyErrChunk: GeminiGenerateContentResponse = {candidates: [{content: {parts: [{ text: "[Error] Codex returned an empty response. Please retry." }],role: "model",},index: 0,},],modelVersion: model,};yield `data: ${JSON.stringify(emptyErrChunk)}\n\n`;}// Final chunk with finishReason and usageconst finalChunk: GeminiGenerateContentResponse = {candidates: [71 unmodified linestotalTokenCount: inputTokens + outputTokens,};// Detect empty response (HTTP 200 but no content)if (!fullText && functionCallParts.length === 0 && outputTokens === 0) {throw new EmptyResponseError(responseId, { input_tokens: inputTokens, output_tokens: outputTokens });}// Build response parts: text + function callsconst parts: GeminiPart[] = [];if (fullText) {
17 unmodified lines1819202122232417 unmodified lines42434445464753 unmodified lines10110210310410510676 unmodified lines18318418518618718813 unmodified lines20220320420520620757 unmodified lines26526626726826927017 unmodified linesChatCompletionToolCall,ChatCompletionChunkToolCall,} from "../types/openai.js";import { iterateCodexEvents, type UsageInfo } from "./codex-event-extractor.js";export type { UsageInfo };17 unmodified linesconst chunkId = `chatcmpl-${randomUUID().replace(/-/g, "").slice(0, 24)}`;const created = Math.floor(Date.now() / 1000);let hasToolCalls = false;// Track tool call indices by call_idconst toolCallIndexMap = new Map<string, number>();let nextToolCallIndex = 0;53 unmodified lines// Handle function call eventsif (evt.functionCallStart) {hasToolCalls = true;const idx = nextToolCallIndex++;toolCallIndexMap.set(evt.functionCallStart.callId, idx);const toolCall: ChatCompletionChunkToolCall = {76 unmodified linesswitch (evt.typed.type) {case "response.output_text.delta": {if (evt.textDelta) {yield formatSSE({id: chunkId,object: "chat.completion.chunk",13 unmodified linescase "response.completed": {if (evt.usage) onUsage?.(evt.usage);yield formatSSE({id: chunkId,object: "chat.completion.chunk",57 unmodified lines}}const hasToolCalls = toolCalls.length > 0;const message: ChatCompletionResponse["choices"][0]["message"] = {role: "assistant",17 unmodified lines1819202122232417 unmodified lines4243444546474853 unmodified lines10210310410510610710876 unmodified lines18518618718818919019113 unmodified lines20520620720820921021121221321421521621721821922022122222322422522657 unmodified lines28428528628728828929029129229329417 unmodified linesChatCompletionToolCall,ChatCompletionChunkToolCall,} from "../types/openai.js";import { iterateCodexEvents, EmptyResponseError, type UsageInfo } from "./codex-event-extractor.js";export type { UsageInfo };17 unmodified linesconst chunkId = `chatcmpl-${randomUUID().replace(/-/g, "").slice(0, 24)}`;const created = Math.floor(Date.now() / 1000);let hasToolCalls = false;let hasContent = false;// Track tool call indices by call_idconst toolCallIndexMap = new Map<string, number>();let nextToolCallIndex = 0;53 unmodified lines// Handle function call eventsif (evt.functionCallStart) {hasToolCalls = true;hasContent = true;const idx = nextToolCallIndex++;toolCallIndexMap.set(evt.functionCallStart.callId, idx);const toolCall: ChatCompletionChunkToolCall = {76 unmodified linesswitch (evt.typed.type) {case "response.output_text.delta": {if (evt.textDelta) {hasContent = true;yield formatSSE({id: chunkId,object: "chat.completion.chunk",13 unmodified linescase "response.completed": {if (evt.usage) onUsage?.(evt.usage);// Inject error text if stream completed with no contentif (!hasContent) {yield formatSSE({id: chunkId,object: "chat.completion.chunk",created,model,choices: [{index: 0,delta: { content: "[Error] Codex returned an empty response. Please retry." },finish_reason: null,},],});}yield formatSSE({id: chunkId,object: "chat.completion.chunk",57 unmodified lines}}// Detect empty response (HTTP 200 but no content)if (!fullText && toolCalls.length === 0 && completionTokens === 0) {throw new EmptyResponseError(responseId, { input_tokens: promptTokens, output_tokens: completionTokens });}const hasToolCalls = toolCalls.length > 0;const message: ChatCompletionResponse["choices"][0]["message"] = {role: "assistant",