Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(codex): sanitize responses replay state (#1868)

Raxxoor1e3c08565c7b
diff --git a/open-sse/config/cliFingerprints.ts b/open-sse/config/cliFingerprints.ts
index b3ff57d164..4449502104 100644
--- a/open-sse/config/cliFingerprints.ts
+++ b/open-sse/config/cliFingerprints.ts
@@ -44,16 +44,19 @@ export const CLI_FINGERPRINTS: Record<string, CliFingerprint> = {
],
bodyFieldOrder: [
"model",
- "messages",
- "temperature",
- "top_p",
- "max_tokens",
"stream",
+ "input",
+ "instructions",
+ "store",
+ "reasoning",
"tools",
"tool_choice",
- "response_format",
- "n",
- "stop",
+ "include",
+ "service_tier",
+ "prompt_cache_key",
+ "client_metadata",
+ "parallel_tool_calls",
+ "metadata",
],
// Codex builds mode-specific client headers in its executor/config. The CLI fingerprint must
// only preserve ordering here; overriding User-Agent with a generic value would erase the
diff --git a/open-sse/services/responsesToolCallState.ts b/open-sse/services/responsesToolCallState.ts
index 9f1af5f5bb..5160f02ec2 100644
--- a/open-sse/services/responsesToolCallState.ts
+++ b/open-sse/services/responsesToolCallState.ts
@@ -28,6 +28,38 @@ function toRecord(value: unknown): JsonRecord | null {
return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : null;
}
+function isResponsesMessageItem(record: JsonRecord): boolean {
+ return record.type === "message" || (!record.type && typeof record.role === "string");
+}
+
+function isInternalAssistantMessage(record: JsonRecord): boolean {
+ if (!isResponsesMessageItem(record)) return false;
+ if (record.role !== "assistant") return false;
+
+ const phase = typeof record.phase === "string" ? record.phase.trim().toLowerCase() : "";
+ if (!phase) return false;
+
+ // OpenCode can send assistant-side commentary/analysis frames in Responses
+ // shape. Those frames are local runtime state, not durable conversation turns
+ // for Codex replay. Re-injecting them makes the model continue hidden notes.
+ return phase !== "final";
+}
+
+function sanitizeRememberedConversationItems(items: readonly unknown[]): unknown[] {
+ const sanitized: unknown[] = [];
+
+ for (const item of items) {
+ const record = toRecord(item);
+ if (record && isInternalAssistantMessage(record)) {
+ continue;
+ }
+
+ sanitized.push(structuredClone(item));
+ }
+
+ return sanitized;
+}
+
function cleanupRememberedResponseToolCalls(now: number = Date.now()) {
for (const [responseId, entry] of rememberedResponseToolCalls.entries()) {
if (entry.expiresAt <= now) {
@@ -122,7 +154,7 @@ export function rememberResponseFunctionCalls(
rememberedResponseToolCalls.set(normalizedResponseId, {
functionCalls,
- conversationItems: existingEntry?.conversationItems?.map((item) => structuredClone(item)) || [],
+ conversationItems: sanitizeRememberedConversationItems(existingEntry?.conversationItems || []),
updatedAt: now,
expiresAt: now + RESPONSE_TOOL_CALL_TTL_MS,
});
@@ -140,7 +172,10 @@ export function rememberResponseConversationState(
const normalizedRequestInput = Array.isArray(requestInput) ? requestInput : [];
const normalizedOutputItems = Array.isArray(outputItems) ? outputItems : [];
- const conversationItems = [...normalizedRequestInput, ...normalizedOutputItems];
+ const conversationItems = sanitizeRememberedConversationItems([
+ ...normalizedRequestInput,
+ ...normalizedOutputItems,
+ ]);
if (conversationItems.length === 0) {
return;
}
@@ -150,7 +185,7 @@ export function rememberResponseConversationState(
const existingEntry = rememberedResponseToolCalls.get(normalizedResponseId);
rememberedResponseToolCalls.set(normalizedResponseId, {
functionCalls: existingEntry?.functionCalls?.map((functionCall) => ({ ...functionCall })) || [],
- conversationItems: conversationItems.map((item) => structuredClone(item)),
+ conversationItems,
updatedAt: Date.now(),
expiresAt: Date.now() + RESPONSE_TOOL_CALL_TTL_MS,
});
@@ -185,7 +220,7 @@ export function getRememberedResponseConversationItems(responseId: unknown): unk
return [];
}
- return entry.conversationItems.map((item) => structuredClone(item));
+ return sanitizeRememberedConversationItems(entry.conversationItems);
}
export function getRememberedFunctionCallsByIds(
diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.ts
index 0443b0dcbd..111fd1095d 100644
--- a/open-sse/utils/stream.ts
+++ b/open-sse/utils/stream.ts
@@ -982,9 +982,16 @@ export function createSSEStream(options: StreamOptions = {}) {
if (extracted) {
usage = extracted;
}
- // Track content length and accumulate for call log
- if (parsed.delta && typeof parsed.delta === "string") {
+ // Keep generic Responses deltas for fallback usage estimates,
+ // but only visible text deltas may become assistant content in
+ // logs/replay payloads.
+ if (typeof parsed.delta === "string") {
totalContentLength += parsed.delta.length;
+ }
+ if (
+ parsed.type === "response.output_text.delta" &&
+ typeof parsed.delta === "string"
+ ) {
passthroughAccumulatedContent = appendBoundedText(
passthroughAccumulatedContent,
parsed.delta
diff --git a/tests/integration/chat-pipeline.test.ts b/tests/integration/chat-pipeline.test.ts
index a381a65f7f..442c2d31b4 100644
--- a/tests/integration/chat-pipeline.test.ts
+++ b/tests/integration/chat-pipeline.test.ts
@@ -26,6 +26,7 @@ const { BaseExecutor } = await import("../../open-sse/executors/base.ts");
const { getCircuitBreaker, resetAllCircuitBreakers } =
await import("../../src/shared/utils/circuitBreaker.ts");
const { clearProviderFailure } = await import("../../open-sse/services/accountFallback.ts");
+const { setCliCompatProviders } = await import("../../open-sse/config/cliFingerprints.ts");
const originalFetch = globalThis.fetch;
const originalRetryDelayMs = BaseExecutor.RETRY_CONFIG.delayMs;
@@ -346,9 +347,15 @@ async function resetStorage() {
async function seedConnection(provider, overrides = {}) {
return providersDb.createProviderConnection({
provider,
- authType: "apikey",
+ authType: overrides.authType || "apikey",
name: overrides.name || `${provider}-primary`,
+ email: overrides.email,
apiKey: overrides.apiKey || `sk-${provider}-${Math.random().toString(16).slice(2, 10)}`,
+ accessToken: overrides.accessToken,
+ refreshToken: overrides.refreshToken,
+ tokenType: overrides.tokenType,
+ expiresAt: overrides.expiresAt,
+ tokenExpiresAt: overrides.tokenExpiresAt,
isActive: overrides.isActive ?? true,
testStatus: overrides.testStatus || "active",
priority: overrides.priority,
@@ -471,6 +478,7 @@ test.beforeEach(async () => {
test.afterEach(async () => {
BaseExecutor.RETRY_CONFIG.delayMs = originalRetryDelayMs;
+ setCliCompatProviders([]);
await resetStorage();
});
@@ -564,6 +572,84 @@ test("chat pipeline persists Codex responses cache and reasoning tokens to call
assert.equal(callLog.tokens.reasoning, 13);
});
+test("chat pipeline applies Codex CLI fingerprint to OAuth responses requests", async () => {
+ setCliCompatProviders(["codex"]);
+ await seedConnection("codex", {
+ apiKey: "unused-for-oauth",
+ authType: "oauth",
+ accessToken: "codex-oauth-token",
+ providerSpecificData: {
+ openaiStoreEnabled: false,
+ requestDefaults: { reasoningEffort: "high" },
+ codexInstallationId: "11111111-1111-4111-a111-111111111111",
+ },
+ });
+
+ const fetchCalls = [];
+ globalThis.fetch = async (url, init = {}) => {
+ fetchCalls.push({
+ url: String(url),
+ headers: toPlainHeaders(init.headers),
+ bodyString: String(init.body || ""),
+ body: init.body ? JSON.parse(String(init.body)) : null,
+ });
+ return buildOpenAIResponsesSSE({ text: "fingerprint ok" });
+ };
+
+ const response = await handleChat(
+ buildRequest({
+ url: "http://localhost/v1/responses",
+ body: {
+ model: "codex/gpt-5.5-low",
+ stream: false,
+ conversation_id: "conv_codex_fingerprint",
+ input: [
+ {
+ type: "message",
+ role: "user",
+ content: [{ type: "input_text", text: "Reply with fingerprint ok" }],
+ },
+ ],
+ },
+ })
+ );
+
+ await response.json();
+
+ assert.equal(response.status, 200);
+ assert.equal(fetchCalls.length, 1);
+ const call = fetchCalls[0];
+ assert.match(call.url, /chatgpt\.com\/backend-api\/codex\/responses$/);
+ assert.equal(call.headers.Authorization, "Bearer codex-oauth-token");
+ assert.equal(call.headers.Accept, "text/event-stream");
+ assert.equal(call.headers.Version, "0.125.0");
+ assert.equal(call.headers["Openai-Beta"], "responses=experimental");
+ assert.equal(call.headers["X-Codex-Beta-Features"], "responses_websockets");
+ assert.equal(call.headers["User-Agent"], "codex-cli/0.125.0 (Windows 10.0.26200; x64)");
+ assert.equal(call.headers["x-codex-window-id"], "conv_codex_fingerprint:0");
+ assert.ok(call.headers["x-client-request-id"], "expected Codex request id header");
+ assert.ok(call.headers["x-codex-turn-metadata"], "expected Codex turn metadata header");
+
+ const headerOrder = Object.keys(call.headers);
+ assert.ok(headerOrder.indexOf("Content-Type") < headerOrder.indexOf("Authorization"));
+ assert.ok(headerOrder.indexOf("Authorization") < headerOrder.indexOf("Accept"));
+ assert.ok(headerOrder.indexOf("Accept") < headerOrder.indexOf("User-Agent"));
+
+ const bodyOrder = Object.keys(JSON.parse(call.bodyString));
+ assert.deepEqual(bodyOrder.slice(0, 7), [
+ "model",
+ "stream",
+ "input",
+ "instructions",
+ "store",
+ "reasoning",
+ "prompt_cache_key",
+ ]);
+ assert.equal(call.body.model, "gpt-5.5");
+ assert.equal(call.body.store, false);
+ assert.equal(call.body.client_metadata["x-codex-installation-id"], "11111111-1111-4111-a111-111111111111");
+});
+
test("chat pipeline treats Codex /responses/compact as non-streaming JSON", async () => {
await seedConnection("codex", { apiKey: "sk-codex-compact" });
const fetchCalls = [];
diff --git a/tests/unit/executor-codex.test.ts b/tests/unit/executor-codex.test.ts
index 22336d58b2..468c63f28e 100644
--- a/tests/unit/executor-codex.test.ts
+++ b/tests/unit/executor-codex.test.ts
@@ -24,13 +24,28 @@ import {
} from "../../open-sse/services/thinkingBudget.ts";
import { CODEX_CHAT_DEFAULT_INSTRUCTIONS } from "../../open-sse/config/codexInstructions.ts";
+type MockCodexWebSocket = {
+ send: (data: string) => void;
+ close: (code?: number, reason?: string) => void;
+ onmessage: ((event: { data: unknown }) => void) | null;
+ onerror: ((event: { message?: string }) => void) | null;
+ onclose: (() => void) | null;
+};
+
+function getRecord(value: unknown): Record<string, unknown> {
+ assert.equal(typeof value, "object");
+ assert.notEqual(value, null);
+ assert.equal(Array.isArray(value), false);
+ return value as Record<string, unknown>;
+}
+
test.afterEach(() => {
setThinkingBudgetConfig(DEFAULT_THINKING_CONFIG);
__setCodexWebSocketTransportForTesting(undefined);
clearRememberedResponseFunctionCallsForTesting();
});
-async function withEnv(entries: Record<string, string | undefined>, fn: () => any) {
+async function withEnv<T>(entries: Record<string, string | undefined>, fn: () => T | Promise<T>) {
const previous = new Map();
for (const [key, value] of Object.entries(entries)) {
@@ -74,7 +89,13 @@ test("Codex helper functions isolate rate-limit scopes and parse quota headers",
assert.equal(getCodexUpstreamModel("gpt-5.5-medium"), "gpt-5.5");
// With mock WS transport + codexTransport=websocket, gpt-5.5 models require WS
__setCodexWebSocketTransportForTesting(
- async () => ({ send() {}, close() {}, onmessage: null, onerror: null, onclose: null }) as any
+ async (): Promise<MockCodexWebSocket> => ({
+ send() {},
+ close() {},
+ onmessage: null,
+ onerror: null,
+ onclose: null,
+ })
);
assert.equal(
isCodexResponsesWebSocketRequired("gpt-5.5-xhigh", {
@@ -387,6 +408,66 @@ test("CodexExecutor.transformRequest expands remembered conversation state for s
});
});
+test("CodexExecutor.transformRequest does not replay internal assistant commentary", () => {
+ const executor = new CodexExecutor();
+ rememberResponseConversationState(
+ "resp_prev_commentary_123",
+ [
+ {
+ type: "message",
+ role: "user",
+ content: [{ type: "input_text", text: "Summarize the previous result." }],
+ },
+ {
+ role: "assistant",
+ phase: "commentary",
+ content: [{ type: "output_text", text: "Need inspect raw tool output first." }],
+ },
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "Visible assistant answer." }],
+ },
+ ],
+ [
+ {
+ type: "function_call",
+ call_id: "call_safe_123",
+ name: "workspace_read_file",
+ arguments: '{"path":"README.md"}',
+ },
+ ]
+ );
+
+ const body = {
+ _nativeCodexPassthrough: true,
+ previous_response_id: "resp_prev_commentary_123",
+ input: [
+ {
+ type: "function_call_output",
+ call_id: "call_safe_123",
+ output: '{"ok":true}',
+ },
+ ],
+ stream: false,
+ };
+
+ const result = executor.transformRequest("gpt-5.5-low", body, false, {
+ requestEndpointPath: "/responses",
+ });
+
+ assert.equal(result.previous_response_id, undefined);
+ assert.equal(result.input.length, 4);
+ assert.equal(
+ result.input.some((item) => JSON.stringify(item).includes("Need inspect raw tool output")),
+ false
+ );
+ assert.equal(result.input[0].role, "user");
+ assert.equal(result.input[1].role, "assistant");
+ assert.equal(result.input[2].type, "function_call");
+ assert.equal(result.input[3].type, "function_call_output");
+});
+
test("CodexExecutor.transformRequest rehydrates missing function_call items for stateful tool outputs", () => {
const executor = new CodexExecutor();
rememberResponseFunctionCalls("resp_prev_tool_123", [
@@ -744,7 +825,7 @@ test("CodexExecutor.execute falls back to HTTP when websocket transport is unava
// When WS transport is unavailable, isCodexResponsesWebSocketRequired returns false
// and the executor falls back to HTTP via super.execute()
assert.equal(result.response.status, 200);
- assert.equal((result.transformedBody as any).model, "gpt-5.5");
+ assert.equal(getRecord(result.transformedBody).model, "gpt-5.5");
} finally {
globalThis.fetch = originalFetch;
}
diff --git a/tests/unit/stream-utilities.test.ts b/tests/unit/stream-utilities.test.ts
index 68e9d95dda..be2b7d6a13 100644
--- a/tests/unit/stream-utilities.test.ts
+++ b/tests/unit/stream-utilities.test.ts
@@ -180,6 +180,65 @@ test("createPassthroughStreamWithLogger backfills completed output from function
assert.ok(result.includes('"arguments":"{\\"path\\":\\"README.md\\"}"'));
});
+test("createPassthroughStreamWithLogger keeps reasoning deltas out of logged assistant content", async () => {
+ let completePayload = null;
+ const transform = createPassthroughStreamWithLogger(
+ "codex",
+ null,
+ null,
+ "gpt-5.5-low",
+ null,
+ {
+ input: [
+ {
+ type: "message",
+ role: "user",
+ content: [{ type: "input_text", text: "Say OK." }],
+ },
+ ],
+ },
+ (payload) => {
+ completePayload = payload;
+ },
+ null,
+ null,
+ "openai-responses"
+ );
+
+ const writer = transform.writable.getWriter();
+ await writer.write(
+ new TextEncoder().encode(
+ [
+ 'data: {"type":"response.created","response":{"id":"resp_reasoning_delta_1"}}',
+ "event: response.reasoning_summary_text.delta",
+ 'data: {"type":"response.reasoning_summary_text.delta","response_id":"resp_reasoning_delta_1","delta":"Internal reasoning should not be content."}',
+ "event: response.function_call_arguments.delta",
+ 'data: {"type":"response.function_call_arguments.delta","response_id":"resp_reasoning_delta_1","delta":"{\\"path\\":\\"secret.txt\\"}"}',
+ "event: response.output_text.delta",
+ 'data: {"type":"response.output_text.delta","response_id":"resp_reasoning_delta_1","delta":"OK"}',
+ "event: response.completed",
+ 'data: {"type":"response.completed","response":{"id":"resp_reasoning_delta_1","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}}',
+ "",
+ ].join("\n")
+ )
+ );
+ await writer.close();
+
+ const reader = transform.readable.getReader();
+ while (true) {
+ const { done } = await reader.read();
+ if (done) break;
+ }
+
+ assert.ok(completePayload, "expected onComplete payload");
+ assert.equal(completePayload.responseBody.choices[0].message.content, "OK");
+ assert.equal(
+ JSON.stringify(completePayload.responseBody).includes("Internal reasoning should not be content"),
+ false
+ );
+ assert.equal(JSON.stringify(completePayload.responseBody).includes("secret.txt"), false);
+});
+
test("createStreamController returns valid controller", () => {
let completeLogged = false;
let disconnectLogged = false;