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
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
Fix Codex Responses WebSocket memory retention and weekly limit handling (#1581)
diegosouzapw3478ac6538ac
diff --git a/open-sse/executors/codex.ts b/open-sse/executors/codex.tsindex ab4fe28ef9..6e547cd605 100644--- a/open-sse/executors/codex.ts+++ b/open-sse/executors/codex.ts@@ -278,8 +278,6 @@ function convertSystemToDeveloperRole(body: Record<string, unknown>): void {* server-generated prefix (rs_, fc_, resp_, msg_) — so the content is* preserved but the backend won't try to look it up* 4. Always deletes previous_response_id (endpoint doesn't persist responses)- *- * @deprecated This function will be removed in v4.0, Codex executor has updated processing logic*/function stripStoredItemReferences(body: Record<string, unknown>): void {// Always strip previous_response_id — the /codex/responses endpoint does not@@ -333,31 +331,6 @@ function stripStoredItemReferences(body: Record<string, unknown>): void {}}-function hasImageGenerationTool(body: Record<string, unknown>): boolean {- if (!Array.isArray(body.tools)) return false;- return body.tools.some((tool) => {- if (!tool || typeof tool !== "object" || Array.isArray(tool)) return false;- return (tool as Record<string, unknown>).type === "image_generation";- });-}--// Responses-API hosted tool types that OpenAI executes server-side (e.g.-// `image_generation` backed by gpt-image-1 under ChatGPT auth). These arrive shaped as-// `{ type, ...params }` with no `function` object and no `name` — Codex CLI injects-// `{ type: "image_generation", output_format: "png" }` when [features] image_generation = true.-// Keep them through `normalizeCodexTools` so upstream can execute them.-const CODEX_HOSTED_TOOL_TYPES: ReadonlySet<string> = new Set([- "image_generation",- "web_search",- "web_search_preview",- "file_search",- "computer",- "computer_use_preview",- "code_interpreter",- "mcp",- "local_shell",-]);-function normalizeCodexTools(body: Record<string, unknown>): void {if (!Array.isArray(body.tools)) return;@@ -368,33 +341,7 @@ function normalizeCodexTools(body: Record<string, unknown>): void {}const tool = toolValue as Record<string, unknown>;- const toolType = typeof tool.type === "string" ? tool.type : "";-- // Preserve namespace tools (MCP tool groups used by Codex/OpenAI Responses API).- // Codex API supports them natively; register sub-tool names for tool_choice validation.- if (toolType === "namespace") {- if (Array.isArray(tool.tools)) {- for (const st of tool.tools as unknown[]) {- if (st && typeof st === "object" && !Array.isArray(st)) {- const subTool = st as Record<string, unknown>;- const name = typeof subTool.name === "string" ? subTool.name.trim() : "";- if (name) validToolNames.add(name);- }- }- }- return true;- }-- if (toolType !== "function") {- const hasFunctionObject = tool.function && typeof tool.function === "object";- const hasName = typeof tool.name === "string";- if (!toolType || hasFunctionObject || hasName) {- return false;- }- if (CODEX_HOSTED_TOOL_TYPES.has(toolType)) {- return true;- }- console.debug(`[Codex] dropping unknown hosted tool type: ${toolType}`);+ if (tool.type !== "function") {return false;}@@ -503,31 +450,70 @@ function isCodexResponsesWebSocketRequired(model: string, credentials: unknown):return providerSpecificData?.codexTransport === "websocket";}+function toStatusCode(value: unknown): number | null {+ if (typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599) {+ return value;+ }+ if (typeof value === "string" && /^\d{3}$/.test(value.trim())) {+ const parsed = Number(value.trim());+ return parsed >= 400 && parsed <= 599 ? parsed : null;+ }+ return null;+}++function looksLikeQuotaOrRateLimit(code: string, type: string, message: string): boolean {+ const haystack = `${code} ${type} ${message}`.toLowerCase();+ return (+ haystack.includes("usage_limit_reached") ||+ haystack.includes("rate_limit") ||+ haystack.includes("rate limit") ||+ haystack.includes("quota") ||+ haystack.includes("too many requests") ||+ haystack.includes("limit has been reached") ||+ haystack.includes("limit reached")+ );+}+function toCodexResponseFailedEvent(parsed: Record<string, unknown>): Record<string, unknown> {+ const response =+ parsed.response && typeof parsed.response === "object" && !Array.isArray(parsed.response)+ ? (parsed.response as Record<string, unknown>)+ : null;const upstreamError =- parsed.error && typeof parsed.error === "object" && !Array.isArray(parsed.error)- ? (parsed.error as Record<string, unknown>)- : parsed;+ response?.error && typeof response.error === "object" && !Array.isArray(response.error)+ ? (response.error as Record<string, unknown>)+ : parsed.error && typeof parsed.error === "object" && !Array.isArray(parsed.error)+ ? (parsed.error as Record<string, unknown>)+ : parsed;const code =typeof upstreamError.code === "string"? upstreamError.code: typeof upstreamError.type === "string"? upstreamError.type: "upstream_error";+ const type = typeof upstreamError.type === "string" ? upstreamError.type : "";const message =typeof upstreamError.message === "string" && upstreamError.message.trim()? upstreamError.message: "Codex upstream error";const error: Record<string, unknown> = { code, message };-- if (typeof upstreamError.type === "string") error.type = upstreamError.type;- if (typeof parsed.status_code === "number") error.status_code = parsed.status_code;- if (typeof parsed.status === "number") error.status_code = parsed.status;+ const explicitStatus =+ toStatusCode(parsed.status_code) ??+ toStatusCode(parsed.status) ??+ toStatusCode(response?.status_code) ??+ toStatusCode(response?.status) ??+ toStatusCode(upstreamError.status_code) ??+ toStatusCode(upstreamError.status);+ const statusCode =+ explicitStatus ?? (looksLikeQuotaOrRateLimit(code, type, message) ? 429 : null);++ if (type) error.type = type;+ if (statusCode !== null) error.status_code = statusCode;return {type: "response.failed",response: {- id: null,+ id: typeof response?.id === "string" ? response.id : null,status: "failed",error,},@@ -543,7 +529,7 @@ export function encodeResponseSseEvent(raw: string): { sse: string; terminal: boconst parsed = JSON.parse(raw);if (parsed && typeof parsed.type === "string" && parsed.type.trim()) {eventType = parsed.type.trim();- if (eventType === "error") {+ if (eventType === "error" || eventType === "response.failed") {const failed = toCodexResponseFailedEvent(parsed as Record<string, unknown>);payload = JSON.stringify(failed);eventType = "response.failed";@@ -618,51 +604,84 @@ export class CodexExecutor extends BaseExecutor {...transformedBody,});- const stream = new ReadableStream<Uint8Array>({- async start(controller) {- const encoder = new TextEncoder();- let closed = false;- let ws: Awaited<ReturnType<typeof websocket>> | null = null;+ const encoder = new TextEncoder();+ let closed = false;+ let ws: Awaited<ReturnType<typeof websocket>> | null = null;+ let streamController: ReadableStreamDefaultController<Uint8Array> | null = null;- const closeController = () => {- if (closed) return;- closed = true;- try {- controller.enqueue(encoder.encode("data: [DONE]\n\n"));- } catch {- // The downstream may already have gone away.- }- try {- controller.close();- } catch {- // The controller may already be closed.- }- };+ const closeUpstream = (reason: string) => {+ try {+ ws?.close(1000, reason);+ } catch {+ // ignore close races+ }+ };- const failController = (code: string, message: string) => {- if (closed) return;- const payload = JSON.stringify({- type: "response.failed",- response: {- id: null,- status: "failed",- error: { code, message },- },- });- controller.enqueue(encoder.encode(`event: response.failed\ndata: ${payload}\n\n`));- closeController();- };+ let abortHandler: (() => void) | null = null;+ const removeAbortListener = () => {+ if (!abortHandler) return;+ input.signal?.removeEventListener("abort", abortHandler);+ abortHandler = null;+ };- const abort = () => {- try {- ws?.close(1000, "client_aborted");- } catch {- // ignore abort races- }- closeController();- };+ const finishStream = ({+ reason,+ emitDone = true,+ closeController = true,+ closeSocket = true,+ }: {+ reason: string;+ emitDone?: boolean;+ closeController?: boolean;+ closeSocket?: boolean;+ }) => {+ if (closed) return;+ closed = true;+ removeAbortListener();+ if (closeSocket) closeUpstream(reason);++ const controller = streamController;+ if (!controller || !closeController) return;+ if (emitDone) {+ try {+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));+ } catch {+ // The downstream may already have gone away.+ }+ }+ try {+ controller.close();+ } catch {+ // The controller may already be closed.+ }+ };- input.signal?.addEventListener("abort", abort, { once: true });+ const failController = (code: string, message: string) => {+ if (closed) return;+ const controller = streamController;+ const payload = JSON.stringify({+ type: "response.failed",+ response: {+ id: null,+ status: "failed",+ error: { code, message },+ },+ });+ try {+ controller?.enqueue(encoder.encode(`event: response.failed\ndata: ${payload}\n\n`));+ } catch {+ // Downstream closed before the failure could be delivered.+ }+ finishStream({ reason: "upstream_failed" });+ };++ const stream = new ReadableStream<Uint8Array>({+ async start(controller) {+ streamController = controller;+ abortHandler = () => {+ finishStream({ reason: "client_aborted" });+ };+ input.signal?.addEventListener("abort", abortHandler, { once: true });try {ws = await websocket(toWebSocketUrl(url), {@@ -670,8 +689,9 @@ export class CodexExecutor extends BaseExecutor {os: "windows",headers,});+ if (closed) return;if (input.signal?.aborted) {- abort();+ finishStream({ reason: "client_aborted" });return;}ws.onmessage = (event) => {@@ -681,9 +701,19 @@ export class CodexExecutor extends BaseExecutor {? event.data: Buffer.from(event.data as Buffer).toString("utf8");const sseEvent = encodeResponseSseEvent(raw);- controller.enqueue(encoder.encode(sseEvent.sse));+ if (closed) return;+ try {+ controller.enqueue(encoder.encode(sseEvent.sse));+ } catch {+ finishStream({+ reason: "downstream_closed",+ emitDone: false,+ closeController: false,+ });+ return;+ }if (sseEvent.terminal) {- closeController();+ finishStream({ reason: "terminal_event" });}};ws.onerror = (event) => {@@ -693,9 +723,11 @@ export class CodexExecutor extends BaseExecutor {);};ws.onclose = () => {- closeController();+ finishStream({ reason: "upstream_closed", closeSocket: false });};- ws.send(bodyString);+ if (!closed) {+ ws.send(bodyString);+ }} catch (error) {failController("upstream_websocket_connect_failed",@@ -703,6 +735,9 @@ export class CodexExecutor extends BaseExecutor {);}},+ cancel() {+ finishStream({ reason: "client_cancelled", emitDone: false, closeController: false });+ },});return {@@ -874,8 +909,6 @@ export class CodexExecutor extends BaseExecutor {// Proxy clients (e.g. OpenClaw) rely on response chaining via previous_response_id,// which requires store=true so that response items are persisted.// If the client explicitly sets store, respect it. Otherwise default to true.- // Exception: when the request uses the image_generation hosted tool, the Codex- // backend rejects store=true ("Store must be set to false"), so default to false.const explicitStoreSetting =credentials?.providerSpecificData &&typeof credentials.providerSpecificData === "object" &&@@ -885,7 +918,7 @@ export class CodexExecutor extends BaseExecutor {if (explicitStoreSetting === false) {body.store = false;} else if (body.store === undefined) {- body.store = hasImageGenerationTool(body) ? false : true;+ body.store = true;}// Codex Responses only supports function tools with non-empty names.diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.tsindex e52cd50c05..d8070256ab 100644--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@ -153,6 +153,66 @@ import { setGeminiThoughtSignatureMode } from "../services/geminiThoughtSignaturimport { fetchLiveProviderLimits } from "@/lib/usage/providerLimits";import { isClaudeExtraUsageBlockEnabled } from "@/lib/providers/claudeExtraUsage";+const MEMORY_EXTRACTION_TEXT_LIMIT = 64 * 1024;+const CHAT_LOG_TEXT_LIMIT = 64 * 1024;+const CHAT_LOG_ARRAY_TAIL_ITEMS = 24;+const CHAT_LOG_MAX_DEPTH = 6;+const CHAT_LOG_MAX_OBJECT_KEYS = 80;++function capMemoryExtractionText(value: string): string {+ if (value.length <= MEMORY_EXTRACTION_TEXT_LIMIT) return value;+ return value.slice(-MEMORY_EXTRACTION_TEXT_LIMIT);+}++function truncateChatLogText(value: string): string {+ if (value.length <= CHAT_LOG_TEXT_LIMIT) return value;+ const head = value.slice(0, Math.floor(CHAT_LOG_TEXT_LIMIT / 2));+ const tail = value.slice(-Math.ceil(CHAT_LOG_TEXT_LIMIT / 2));+ return `${head}\n[...truncated ${value.length - CHAT_LOG_TEXT_LIMIT} chars...]\n${tail}`;+}++function cloneBoundedChatLogPayload(value: unknown, depth = 0): unknown {+ if (value === null || value === undefined) return value;+ if (typeof value === "string") return truncateChatLogText(value);+ if (typeof value !== "object") return value;+ if (depth >= CHAT_LOG_MAX_DEPTH) return "[MaxDepth]";++ if (Array.isArray(value)) {+ const retained =+ value.length > CHAT_LOG_ARRAY_TAIL_ITEMS ? value.slice(-CHAT_LOG_ARRAY_TAIL_ITEMS) : value;+ const cloned = retained.map((item) => cloneBoundedChatLogPayload(item, depth + 1));+ if (value.length > CHAT_LOG_ARRAY_TAIL_ITEMS) {+ return [+ {+ _omniroute_truncated_array: true,+ originalLength: value.length,+ retainedTailItems: CHAT_LOG_ARRAY_TAIL_ITEMS,+ },+ ...cloned,+ ];+ }+ return cloned;+ }++ const result: Record<string, unknown> = {};+ const entries = Object.entries(value as Record<string, unknown>);+ for (const [key, item] of entries.slice(0, CHAT_LOG_MAX_OBJECT_KEYS)) {+ result[key] = cloneBoundedChatLogPayload(item, depth + 1);+ }+ if (entries.length > CHAT_LOG_MAX_OBJECT_KEYS) {+ result._omniroute_truncated_keys = entries.length - CHAT_LOG_MAX_OBJECT_KEYS;+ }+ return result;+}++function isSmallEnoughForSemanticCache(value: unknown): boolean {+ try {+ return JSON.stringify(value).length <= 256 * 1024;+ } catch {+ return false;+ }+}+function extractMemoryTextFromResponse(response: Record<string, unknown> | null | undefined): string {@@ -160,7 +220,7 @@ function extractMemoryTextFromResponse(const openAIText = response?.choices?.[0]?.message?.content;if (typeof openAIText === "string") {- return openAIText.trim();+ return capMemoryExtractionText(openAIText.trim());}if (Array.isArray(response?.content)) {@@ -171,11 +231,11 @@ function extractMemoryTextFromResponse(.map((part: Record<string, unknown>) => String(part.text).trim()).filter(Boolean).join("\n");- if (contentText) return contentText;+ if (contentText) return capMemoryExtractionText(contentText);}if (typeof response?.output_text === "string") {- return response.output_text.trim();+ return capMemoryExtractionText(response.output_text.trim());}return "";@@ -193,7 +253,7 @@ function extractMemoryTextFromRequestBody(if (msg?.role !== "user") continue;if (typeof msg.content === "string" && msg.content.trim().length > 0) {- return msg.content.trim();+ return capMemoryExtractionText(msg.content.trim());}if (Array.isArray(msg.content)) {@@ -207,15 +267,43 @@ function extractMemoryTextFromRequestBody(.filter(Boolean).join("\n").trim();- if (text) return text;+ if (text) return capMemoryExtractionText(text);}}}const input = Array.isArray(body.input) ? body.input : null;if (input && input.length > 0) {- const chunks = input- .map((item: Record<string, unknown>) => {+ for (let i = input.length - 1; i >= 0; i -= 1) {+ const item = input[i] as Record<string, unknown>;+ const role = typeof item?.role === "string" ? item.role.trim().toLowerCase() : "";+ const itemType = typeof item?.type === "string" ? item.type.trim().toLowerCase() : "";+ if (role && role !== "user") continue;+ if (itemType && itemType !== "message") continue;++ if (typeof item?.content === "string" && item.content.trim()) {+ return capMemoryExtractionText(item.content.trim());+ }+ if (Array.isArray(item?.content)) {+ const text = item.content+ .map((part: Record<string, unknown>) => {+ if (typeof part?.text === "string") return part.text.trim();+ if (part?.type === "input_text" && typeof part?.text === "string")+ return part.text.trim();+ return "";+ })+ .filter(Boolean)+ .join("\n")+ .trim();+ if (text) return capMemoryExtractionText(text);+ }+ }++ const tailChunks: string[] = [];+ let tailLength = 0;+ for (let i = input.length - 1; i >= 0 && tailLength < MEMORY_EXTRACTION_TEXT_LIMIT; i -= 1) {+ const item = input[i] as Record<string, unknown>;+ const text = (() => {const role = typeof item?.role === "string" ? item.role.trim().toLowerCase() : "";const itemType = typeof item?.type === "string" ? item.type.trim().toLowerCase() : "";if (role && role !== "user") return "";@@ -235,11 +323,13 @@ function extractMemoryTextFromRequestBody(.trim();}return "";- })- .filter(Boolean)- .join("\n")- .trim();- if (chunks) return chunks;+ })();+ if (!text) continue;+ tailChunks.unshift(text);+ tailLength += text.length + 1;+ }+ const chunks = tailChunks.join("\n").trim();+ if (chunks) return capMemoryExtractionText(chunks);}return "";@@ -799,6 +889,7 @@ export async function handleChatCore({log,onCredentialsRefreshed,onRequestSuccess,+ onStreamFailure,onDisconnect,clientRawRequest,connectionId,@@ -1122,19 +1213,23 @@ export async function handleChatCore({connectionId,duration: Date.now() - startTime,tokens: tokens || {},- requestBody: attachLogMeta((body as Record<string, unknown>) ?? undefined, {- claudePromptCache: claudeCacheMeta,- }),- responseBody: attachLogMeta((responseBody as Record<string, unknown>) ?? undefined, {- claudePromptCache: claudeCacheMeta- ? {- applied: claudeCacheMeta.applied,- totalBreakpoints: claudeCacheMeta.totalBreakpoints,- anthropicBeta: claudeCacheMeta.anthropicBeta,- }- : null,- claudePromptCacheUsage: claudeCacheUsageMeta,- }),+ requestBody: cloneBoundedChatLogPayload(+ attachLogMeta((body as Record<string, unknown>) ?? undefined, {+ claudePromptCache: claudeCacheMeta,+ })+ ),+ responseBody: cloneBoundedChatLogPayload(+ attachLogMeta((responseBody as Record<string, unknown>) ?? undefined, {+ claudePromptCache: claudeCacheMeta+ ? {+ applied: claudeCacheMeta.applied,+ totalBreakpoints: claudeCacheMeta.totalBreakpoints,+ anthropicBeta: claudeCacheMeta.anthropicBeta,+ }+ : null,+ claudePromptCacheUsage: claudeCacheUsageMeta,+ })+ ),error: error || null,sourceFormat,targetFormat,@@ -1212,7 +1307,10 @@ export async function handleChatCore({const semanticCacheEnabled = settings.semanticCacheEnabled !== false;// Create request logger for this session: sourceFormat_targetFormat_model- const reqLogger = await createRequestLogger(sourceFormat, targetFormat, model);+ const reqLogger = await createRequestLogger(sourceFormat, targetFormat, model, {+ enabled: detailedLoggingEnabled,+ captureStreamChunks: detailedLoggingEnabled,+ });// 0. Log client raw request (before format conversion)if (clientRawRequest) {@@ -3031,7 +3129,11 @@ export async function handleChatCore({}// ── Phase 9.1: Cache store (non-streaming, temp=0) ──- if (semanticCacheEnabled && isCacheableForWrite(body, clientRawRequest?.headers)) {+ if (+ semanticCacheEnabled &&+ isCacheableForWrite(body, clientRawRequest?.headers) &&+ isSmallEnoughForSemanticCache(translatedResponse)+ ) {const signature = generateSignature(model,body.messages ?? body.input,@@ -3225,6 +3327,7 @@ export async function handleChatCore({try {const cleanBody = { ...streamResponseBody };delete cleanBody._streamed;+ if (!isSmallEnoughForSemanticCache(cleanBody)) return;const sig = generateSignature(model,body.messages ?? body.input,@@ -3242,6 +3345,20 @@ export async function handleChatCore({}};+ const handleStreamFailure = (failure: {+ status: number;+ message: string;+ code?: string;+ type?: string;+ }) => {+ persistFailureUsage(failure.status || HTTP_STATUS.BAD_GATEWAY, failure.code || failure.type);+ try {+ onStreamFailure?.(failure);+ } catch {+ // Best-effort fallback state update only.+ }+ };+// For providers using Responses API format, translate stream back to openai (Chat Completions) format// UNLESS client is Droid CLI which expects openai-responses format backconst needsResponsesTranslation =@@ -3263,7 +3380,8 @@ export async function handleChatCore({connectionId,body,onStreamComplete,- apiKeyInfo+ apiKeyInfo,+ handleStreamFailure);} else if (needsTranslation(targetFormat, clientResponseFormat)) {// Standard translation for other providers@@ -3278,7 +3396,8 @@ export async function handleChatCore({connectionId,body,onStreamComplete,- apiKeyInfo+ apiKeyInfo,+ handleStreamFailure);} else {log?.debug?.("STREAM", `Standard passthrough mode`);@@ -3290,7 +3409,8 @@ export async function handleChatCore({connectionId,body,onStreamComplete,- apiKeyInfo+ apiKeyInfo,+ handleStreamFailure);}diff --git a/open-sse/handlers/imageGeneration.ts b/open-sse/handlers/imageGeneration.tsindex 8e6dc53e33..a9c3b566c0 100644--- a/open-sse/handlers/imageGeneration.ts+++ b/open-sse/handlers/imageGeneration.ts@@ -1399,7 +1399,8 @@ async function handleCodexImageGeneration({});}- const requestedCount = Number.isInteger(body.n) && (body.n as number) > 0 ? (body.n as number) : 1;+ const requestedCount =+ Number.isInteger(body.n) && (body.n as number) > 0 ? (body.n as number) : 1;if (log && requestedCount > 1) {log.warn("IMAGE",diff --git a/open-sse/utils/requestLogger.ts b/open-sse/utils/requestLogger.tsindex 861c0aad14..f1b8460e55 100644--- a/open-sse/utils/requestLogger.ts+++ b/open-sse/utils/requestLogger.ts@@ -40,6 +40,17 @@ type RequestLogger = {getPipelinePayloads: () => RequestPipelinePayloads | null;};+type RequestLoggerOptions = {+ enabled?: boolean;+ captureStreamChunks?: boolean;+ maxStreamChunkBytes?: number;+};++const DEFAULT_MAX_STREAM_CHUNK_BYTES = 128 * 1024;+const MAX_LOG_STRING_LENGTH = 64 * 1024;+const MAX_LOG_ARRAY_ITEMS = 24;+const MAX_LOG_OBJECT_KEYS = 80;+function maskSensitiveHeaders(headers: HeaderInput): Record<string, unknown> {if (!headers) return {};@@ -76,6 +87,71 @@ function createEmptyStreamChunks() {};}+function truncateLogString(value: string, maxLength = MAX_LOG_STRING_LENGTH): string {+ if (value.length <= maxLength) return value;+ return `${value.slice(0, Math.floor(maxLength / 2))}\n[...truncated ${value.length - maxLength} chars...]\n${value.slice(-Math.ceil(maxLength / 2))}`;+}++function cloneBoundedForLog(value: unknown, depth = 0): unknown {+ if (value === null || value === undefined) return value;+ if (typeof value === "string") return truncateLogString(value);+ if (typeof value !== "object") return value;+ if (depth >= 6) return "[MaxDepth]";++ if (Array.isArray(value)) {+ const source = value.length > MAX_LOG_ARRAY_ITEMS ? value.slice(-MAX_LOG_ARRAY_ITEMS) : value;+ const mapped = source.map((item) => cloneBoundedForLog(item, depth + 1));+ if (value.length > MAX_LOG_ARRAY_ITEMS) {+ return [+ {+ _omniroute_truncated_array: true,+ originalLength: value.length,+ retainedTailItems: MAX_LOG_ARRAY_ITEMS,+ },+ ...mapped,+ ];+ }+ return mapped;+ }++ const result: JsonRecord = {};+ const entries = Object.entries(value as JsonRecord);+ for (const [key, item] of entries.slice(0, MAX_LOG_OBJECT_KEYS)) {+ result[key] = cloneBoundedForLog(item, depth + 1);+ }+ if (entries.length > MAX_LOG_OBJECT_KEYS) {+ result._omniroute_truncated_keys = entries.length - MAX_LOG_OBJECT_KEYS;+ }+ return result;+}++function appendBoundedChunk(+ chunks: string[],+ bytes: { value: number; truncated: boolean },+ chunk: string,+ maxBytes: number+) {+ if (typeof chunk !== "string" || chunk.length === 0) {+ return;+ }+ if (bytes.value >= maxBytes) {+ bytes.truncated = true;+ return;+ }++ const remaining = maxBytes - bytes.value;+ if (chunk.length <= remaining) {+ chunks.push(chunk);+ bytes.value += chunk.length;+ return;+ }++ chunks.push(chunk.slice(0, remaining));+ chunks.push(`[stream chunk log truncated after ${maxBytes} bytes]`);+ bytes.value = maxBytes;+ bytes.truncated = true;+}+function hasOwnValues(value: unknown): boolean {return Boolean(value && typeof value === "object" && Object.keys(value as JsonRecord).length > 0);}@@ -130,11 +206,26 @@ function createNoOpLogger(): RequestLogger {export async function createRequestLogger(_sourceFormat?: string,_targetFormat?: string,- _model?: string+ _model?: string,+ options: RequestLoggerOptions = {}): Promise<RequestLogger> {+ if (options.enabled === false) {+ return createNoOpLogger();+ }++ const captureStreamChunks = options.captureStreamChunks !== false;+ const maxStreamChunkBytes =+ Number.isInteger(options.maxStreamChunkBytes) && Number(options.maxStreamChunkBytes) > 0+ ? Number(options.maxStreamChunkBytes)+ : DEFAULT_MAX_STREAM_CHUNK_BYTES;const streamChunks = createEmptyStreamChunks();+ const streamChunkBytes = {+ provider: { value: 0, truncated: false },+ openai: { value: 0, truncated: false },+ client: { value: 0, truncated: false },+ };const payloads: RequestPipelinePayloads = {- streamChunks,+ ...(captureStreamChunks ? { streamChunks } : {}),};return {@@ -145,14 +236,14 @@ export async function createRequestLogger(timestamp: new Date().toISOString(),endpoint,headers: maskSensitiveHeaders(headers),- body,+ body: cloneBoundedForLog(body),};},logOpenAIRequest(body) {payloads.openaiRequest = {timestamp: new Date().toISOString(),- body,+ body: cloneBoundedForLog(body),};},@@ -161,7 +252,7 @@ export async function createRequestLogger(timestamp: new Date().toISOString(),url,headers: maskSensitiveHeaders(headers),- body,+ body: cloneBoundedForLog(body),};},@@ -171,33 +262,35 @@ export async function createRequestLogger(status,statusText,headers: maskSensitiveHeaders(headers),- body,+ body: cloneBoundedForLog(body),};},appendProviderChunk(chunk) {- if (typeof chunk === "string" && chunk.length > 0) {- streamChunks.provider.push(chunk);- }+ if (!captureStreamChunks) return;+ appendBoundedChunk(+ streamChunks.provider,+ streamChunkBytes.provider,+ chunk,+ maxStreamChunkBytes+ );},appendOpenAIChunk(chunk) {- if (typeof chunk === "string" && chunk.length > 0) {- streamChunks.openai.push(chunk);- }+ if (!captureStreamChunks) return;+ appendBoundedChunk(streamChunks.openai, streamChunkBytes.openai, chunk, maxStreamChunkBytes);},logConvertedResponse(body) {payloads.clientResponse = {timestamp: new Date().toISOString(),- body,+ body: cloneBoundedForLog(body),};},appendConvertedChunk(chunk) {- if (typeof chunk === "string" && chunk.length > 0) {- streamChunks.client.push(chunk);- }+ if (!captureStreamChunks) return;+ appendBoundedChunk(streamChunks.client, streamChunkBytes.client, chunk, maxStreamChunkBytes);},logError(error, requestBody = null) {@@ -205,7 +298,7 @@ export async function createRequestLogger(timestamp: new Date().toISOString(),error: error instanceof Error ? error.message : String(error),stack: error instanceof Error ? error.stack : undefined,- requestBody,+ requestBody: cloneBoundedForLog(requestBody),};},diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.tsindex 7d8c524353..7cfb4074ff 100644--- a/open-sse/utils/stream.ts+++ b/open-sse/utils/stream.ts@@ -49,6 +49,13 @@ type StreamCompletePayload = {clientPayload?: unknown;};+type StreamFailurePayload = {+ status: number;+ message: string;+ code?: string;+ type?: string;+};+type StreamOptions = {mode?: string;targetFormat?: string;@@ -61,6 +68,7 @@ type StreamOptions = {apiKeyInfo?: unknown;body?: unknown;onComplete?: ((payload: StreamCompletePayload) => void) | null;+ onFailure?: ((payload: StreamFailurePayload) => void | Promise<void>) | null;};type TranslateState = ReturnType<typeof initState> & {@@ -87,6 +95,76 @@ type ToolCall = {type UsageTokenRecord = Record<string, number>;+function asRecord(value: unknown): JsonRecord {+ return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};+}++const STREAM_SUMMARY_TEXT_LIMIT = 64 * 1024;++function appendBoundedText(current: string, next: string): string {+ if (!next) return current;+ const combined = current + next;+ if (combined.length <= STREAM_SUMMARY_TEXT_LIMIT) return combined;+ return combined.slice(-STREAM_SUMMARY_TEXT_LIMIT);+}++function toStreamFailureStatus(value: unknown): number | null {+ if (typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599) {+ return value;+ }+ if (typeof value === "string" && /^\d{3}$/.test(value.trim())) {+ const parsed = Number(value.trim());+ return parsed >= 400 && parsed <= 599 ? parsed : null;+ }+ return null;+}++function looksLikeStreamRateLimit(code: string, type: string, message: string): boolean {+ const haystack = `${code} ${type} ${message}`.toLowerCase();+ return (+ haystack.includes("usage_limit_reached") ||+ haystack.includes("rate_limit") ||+ haystack.includes("rate limit") ||+ haystack.includes("quota") ||+ haystack.includes("too many requests") ||+ haystack.includes("limit reached") ||+ haystack.includes("limit has been reached")+ );+}++function normalizeStreamFailurePayload(payload: unknown): StreamFailurePayload | null {+ const record = payload && typeof payload === "object" ? (payload as JsonRecord) : {};+ const response = asRecord(record.response);+ const error = Object.keys(asRecord(response.error)).length+ ? asRecord(response.error)+ : Object.keys(asRecord(record.error)).length+ ? asRecord(record.error)+ : record;+ const code = typeof error.code === "string" ? error.code : "upstream_error";+ const type = typeof error.type === "string" ? error.type : undefined;+ const message =+ typeof error.message === "string" && error.message.trim()+ ? error.message+ : typeof record.message === "string" && record.message.trim()+ ? record.message+ : "Upstream failure";+ const status =+ toStreamFailureStatus(error.status_code) ??+ toStreamFailureStatus(error.status) ??+ toStreamFailureStatus(response.status_code) ??+ toStreamFailureStatus(response.status) ??+ toStreamFailureStatus(record.status_code) ??+ toStreamFailureStatus(record.status) ??+ (looksLikeStreamRateLimit(code, type || "", message) ? 429 : 502);++ return {+ status,+ message,+ code,+ ...(type ? { type } : {}),+ };+}+type ClaudeEmptyResponseLifecycle = {hasMessageStart: boolean;hasContentBlock: boolean;@@ -386,6 +464,7 @@ export function createSSEStream(options: StreamOptions = {}) {apiKeyInfo = null,body = null,onComplete = null,+ onFailure = null,} = options;let buffer = "";@@ -440,6 +519,13 @@ export function createSSEStream(options: StreamOptions = {}) {let pendingPassthroughEventLine: string | null = null;let pendingPassthroughEventEmitted = false;+ const clearIdleTimer = () => {+ if (idleTimer) {+ clearInterval(idleTimer);+ idleTimer = null;+ }+ };+const clearPendingPassthroughEvent = () => {pendingPassthroughEventLine = null;pendingPassthroughEventEmitted = false;@@ -585,8 +671,7 @@ export function createSSEStream(options: StreamOptions = {}) {idleTimer = setInterval(() => {if (!streamTimedOut && Date.now() - lastChunkTime > STREAM_IDLE_TIMEOUT_MS) {streamTimedOut = true;- clearInterval(idleTimer);- idleTimer = null;+ clearIdleTimer();const timeoutMsg = `[STREAM] Idle timeout: no data from ${provider || "provider"} for ${STREAM_IDLE_TIMEOUT_MS}ms (model: ${model || "unknown"})`;console.warn(timeoutMsg);trackPendingRequest(model, provider, connectionId, false);@@ -622,6 +707,7 @@ export function createSSEStream(options: StreamOptions = {}) {let output;let injectedUsage = false;let clientPayload: unknown = null;+ let failurePayload: StreamFailurePayload | null = null;if (skipPassthroughEvent) {if (!trimmed) {@@ -711,7 +797,13 @@ export function createSSEStream(options: StreamOptions = {}) {// Track content length and accumulate for call logif (parsed.delta && typeof parsed.delta === "string") {totalContentLength += parsed.delta.length;- passthroughAccumulatedContent += parsed.delta;+ passthroughAccumulatedContent = appendBoundedText(+ passthroughAccumulatedContent,+ parsed.delta+ );+ }+ if (parsed.type === "response.failed") {+ failurePayload = normalizeStreamFailurePayload(parsed);}// Capture each completed output item so the final// response.completed snapshot can be backfilled when upstream@@ -772,11 +864,17 @@ export function createSSEStream(options: StreamOptions = {}) {// Track content length and accumulate from Claude formatif (parsed.delta?.text) {totalContentLength += parsed.delta.text.length;- passthroughAccumulatedContent += parsed.delta.text;+ passthroughAccumulatedContent = appendBoundedText(+ passthroughAccumulatedContent,+ parsed.delta.text+ );}if (parsed.delta?.thinking) {totalContentLength += parsed.delta.thinking.length;- passthroughAccumulatedContent += parsed.delta.thinking;+ passthroughAccumulatedContent = appendBoundedText(+ passthroughAccumulatedContent,+ parsed.delta.thinking+ );}if (restoredToolName) {output = `data: ${JSON.stringify(parsed)}@@ -823,7 +921,10 @@ export function createSSEStream(options: StreamOptions = {}) {reasoningChunk.choices[0].finish_reason = null;delete reasoningChunk.usage;const rOutput = `data: ${JSON.stringify(reasoningChunk)}\n`;- passthroughAccumulatedReasoning += delta.reasoning_content;+ passthroughAccumulatedReasoning = appendBoundedText(+ passthroughAccumulatedReasoning,+ delta.reasoning_content+ );totalContentLength += delta.reasoning_content.length;clientPayloadCollector.push(reasoningChunk);reqLogger?.appendConvertedChunk?.(rOutput);@@ -877,9 +978,15 @@ export function createSSEStream(options: StreamOptions = {}) {totalContentLength += content.length;}if (typeof delta?.content === "string")- passthroughAccumulatedContent += delta.content;+ passthroughAccumulatedContent = appendBoundedText(+ passthroughAccumulatedContent,+ delta.content+ );if (typeof delta?.reasoning_content === "string")- passthroughAccumulatedReasoning += delta.reasoning_content;+ passthroughAccumulatedReasoning = appendBoundedText(+ passthroughAccumulatedReasoning,+ delta.reasoning_content+ );const extracted = extractUsage(parsed);if (extracted) {@@ -943,6 +1050,16 @@ export function createSSEStream(options: StreamOptions = {}) {reqLogger?.appendConvertedChunk?.(output);controller.enqueue(encoder.encode(output));+ if (failurePayload) {+ if (onFailure) {+ try {+ void onFailure(failurePayload);+ } catch {}+ }+ clearIdleTimer();+ controller.error(new Error(failurePayload.message || "Upstream failure"));+ return;+ }if (!trimmed) {clearPendingPassthroughEvent();}@@ -972,13 +1089,13 @@ export function createSSEStream(options: StreamOptions = {}) {const t = parsed.delta.text;totalContentLength += t.length;if (state?.accumulatedContent !== undefined && typeof t === "string")- state.accumulatedContent += t;+ state.accumulatedContent = appendBoundedText(state.accumulatedContent, t);}if (parsed.delta?.thinking) {const t = parsed.delta.thinking;totalContentLength += t.length;if (state?.accumulatedContent !== undefined && typeof t === "string")- state.accumulatedContent += t;+ state.accumulatedContent = appendBoundedText(state.accumulatedContent, t);}// OpenAI format@@ -986,13 +1103,17 @@ export function createSSEStream(options: StreamOptions = {}) {const c = parsed.choices[0].delta.content;if (typeof c === "string") {totalContentLength += c.length;- if (state?.accumulatedContent !== undefined) state.accumulatedContent += c;+ if (state?.accumulatedContent !== undefined)+ state.accumulatedContent = appendBoundedText(state.accumulatedContent, c);} else if (Array.isArray(c)) {for (const part of c) {if (part?.text && typeof part.text === "string") {totalContentLength += part.text.length;if (state?.accumulatedContent !== undefined)- state.accumulatedContent += part.text;+ state.accumulatedContent = appendBoundedText(+ state.accumulatedContent,+ part.text+ );}}}@@ -1001,7 +1122,8 @@ export function createSSEStream(options: StreamOptions = {}) {const r = parsed.choices[0].delta.reasoning_content;if (typeof r === "string") {totalContentLength += r.length;- if (state?.accumulatedContent !== undefined) state.accumulatedContent += r;+ if (state?.accumulatedContent !== undefined)+ state.accumulatedContent = appendBoundedText(state.accumulatedContent, r);}}// Normalize `reasoning` alias → `reasoning_content` (NVIDIA kimi-k2.5 etc.)@@ -1014,7 +1136,8 @@ export function createSSEStream(options: StreamOptions = {}) {parsed.choices[0].delta.reasoning_content = r;delete parsed.choices[0].delta.reasoning;totalContentLength += r.length;- if (state?.accumulatedContent !== undefined) state.accumulatedContent += r;+ if (state?.accumulatedContent !== undefined)+ state.accumulatedContent = appendBoundedText(state.accumulatedContent, r);}}@@ -1030,7 +1153,8 @@ export function createSSEStream(options: StreamOptions = {}) {for (const part of geminiChunk.candidates[0].content.parts) {if (part.text && typeof part.text === "string") {totalContentLength += part.text.length;- if (state?.accumulatedContent !== undefined) state.accumulatedContent += part.text;+ if (state?.accumulatedContent !== undefined)+ state.accumulatedContent = appendBoundedText(state.accumulatedContent, part.text);}}}@@ -1039,17 +1163,17 @@ export function createSSEStream(options: StreamOptions = {}) {if (state?.accumulatedContent !== undefined) {if (typeof (parsed as JsonRecord).delta === "string") {const d = (parsed as JsonRecord).delta as string;- state.accumulatedContent += d;+ state.accumulatedContent = appendBoundedText(state.accumulatedContent, d);totalContentLength += d.length;}if (typeof (parsed as JsonRecord).content === "string") {const c = (parsed as JsonRecord).content as string;- state.accumulatedContent += c;+ state.accumulatedContent = appendBoundedText(state.accumulatedContent, c);totalContentLength += c.length;}if (typeof (parsed as JsonRecord).text === "string") {const t = (parsed as JsonRecord).text as string;- state.accumulatedContent += t;+ state.accumulatedContent = appendBoundedText(state.accumulatedContent, t);totalContentLength += t.length;}}@@ -1078,8 +1202,7 @@ export function createSSEStream(options: StreamOptions = {}) {async flush(controller) {// Clean up idle watchdog timerif (idleTimer) {- clearInterval(idleTimer);- idleTimer = null;+ clearIdleTimer();}if (streamTimedOut) {return;@@ -1273,6 +1396,16 @@ export function createSSEStream(options: StreamOptions = {}) {if (state?.upstreamError) {const err = state.upstreamError;trackPendingRequest(model, provider, connectionId, false);+ if (onFailure) {+ try {+ void onFailure({+ status: err.status,+ message: err.message,+ code: err.code,+ type: err.type,+ });+ } catch {}+ }const errorBody = buildErrorBody(err.status, err.message);if (onComplete) {@@ -1296,6 +1429,7 @@ export function createSSEStream(options: StreamOptions = {}) {} catch {}}+ clearIdleTimer();controller.error(new Error(err.message || "Upstream failure"));return;}@@ -1450,7 +1584,8 @@ export function createSSETransformStreamWithLogger(connectionId: string | null = null,body: unknown = null,onComplete: ((payload: StreamCompletePayload) => void) | null = null,- apiKeyInfo: unknown = null+ apiKeyInfo: unknown = null,+ onFailure: ((payload: StreamFailurePayload) => void | Promise<void>) | null = null) {return createSSEStream({mode: STREAM_MODE.TRANSLATE,@@ -1464,6 +1599,7 @@ export function createSSETransformStreamWithLogger(apiKeyInfo,body,onComplete,+ onFailure,});}@@ -1475,7 +1611,8 @@ export function createPassthroughStreamWithLogger(connectionId: string | null = null,body: unknown = null,onComplete: ((payload: StreamCompletePayload) => void) | null = null,- apiKeyInfo: unknown = null+ apiKeyInfo: unknown = null,+ onFailure: ((payload: StreamFailurePayload) => void | Promise<void>) | null = null) {return createSSEStream({mode: STREAM_MODE.PASSTHROUGH,@@ -1487,5 +1624,6 @@ export function createPassthroughStreamWithLogger(apiKeyInfo,body,onComplete,+ onFailure,});}diff --git a/scripts/responses-ws-proxy.mjs b/scripts/responses-ws-proxy.mjsindex 4e1d75f75e..334840c36f 100644--- a/scripts/responses-ws-proxy.mjs+++ b/scripts/responses-ws-proxy.mjs@@ -12,6 +12,22 @@ const INTERNAL_ROUTE = "/api/internal/codex-responses-ws";const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";const WS_QUERY_TOKEN_KEYS = ["api_key", "token", "access_token"];const textDecoder = new TextDecoder();+const DEFAULT_MAX_WS_BUFFER_BYTES = 16 * 1024 * 1024;+const DEFAULT_MAX_WS_MESSAGE_BYTES = 16 * 1024 * 1024;++class WebSocketInputTooLargeError extends Error {+ constructor(message, reason = "message_too_large") {+ super(message);+ this.name = "WebSocketInputTooLargeError";+ this.closeCode = 1009;+ this.reason = reason;+ }+}++function normalizePositiveInteger(value, fallback) {+ const parsed = Number(value);+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;+}function isText(value) {return typeof value === "string" && value.length > 0;@@ -60,7 +76,10 @@ export function encodeWsFrame(opcode, payload = Buffer.alloc(0)) {return Buffer.concat([header, payloadBuffer]);}-export function decodeClientFrames(buffer) {+export function decodeClientFrames(+ buffer,+ { maxPayloadBytes = DEFAULT_MAX_WS_MESSAGE_BYTES } = {}+) {const frames = [];let offset = 0;@@ -85,12 +104,16 @@ export function decodeClientFrames(buffer) {if (buffer.length - offset < 10) break;const bigLength = buffer.readBigUInt64BE(offset + 2);if (bigLength > BigInt(Number.MAX_SAFE_INTEGER)) {- throw new Error("WebSocket payload too large");+ throw new WebSocketInputTooLargeError("WebSocket payload too large");}payloadLength = Number(bigLength);headerLength = 10;}+ if (payloadLength > maxPayloadBytes) {+ throw new WebSocketInputTooLargeError("WebSocket payload exceeds configured limit");+ }+const totalLength = headerLength + 4 + payloadLength;if (buffer.length - offset < totalLength) break;@@ -228,6 +251,8 @@ class ResponsesWsSession {wsFactory,pingIntervalMs,idleTimeoutMs,+ maxBufferBytes,+ maxMessageBytes,}) {this.baseUrl = baseUrl;this.bridgeSecret = bridgeSecret;@@ -238,11 +263,15 @@ class ResponsesWsSession {this.wsFactory = wsFactory;this.pingIntervalMs = pingIntervalMs;this.idleTimeoutMs = idleTimeoutMs;+ this.maxBufferBytes = normalizePositiveInteger(maxBufferBytes, DEFAULT_MAX_WS_BUFFER_BYTES);+ this.maxMessageBytes = normalizePositiveInteger(maxMessageBytes, DEFAULT_MAX_WS_MESSAGE_BYTES);this.sessionId = randomUUID();this.closed = false;this.buffer = Buffer.alloc(0);this.fragmentOpcode = null;this.fragmentParts = [];+ this.fragmentBytes = 0;+ this.processing = Promise.resolve();this.upstream = null;this.upstreamReady = null;this.lastSeenAt = Date.now();@@ -258,18 +287,35 @@ class ResponsesWsSession {}, this.pingIntervalMs);this.socket.setNoDelay(true);- this.socket.on("data", (chunk) => {- this.onData(chunk).catch((error) => {+ this.socket.on("data", (chunk) => this.enqueueData(chunk));+ this.socket.on("close", () => this.dispose());+ this.socket.on("end", () => this.dispose());+ this.socket.on("error", () => this.dispose());+ }++ enqueueData(chunk) {+ this.processing = this.processing+ .then(() => this.onData(chunk))+ .catch((error) => {+ if (this.closed) return;+ const isTooLarge =+ error instanceof WebSocketInputTooLargeError || error?.closeCode === 1009;this.sendFailure(- "frame_decode_failed",+ isTooLarge ? "message_too_large" : "frame_decode_failed",error instanceof Error ? error.message : String(error));- this.close(1011, "frame_decode_failed");+ this.close(+ isTooLarge ? 1009 : 1011,+ isTooLarge ? error.reason || "message_too_large" : "frame_decode_failed"+ );});- });- this.socket.on("close", () => this.dispose());- this.socket.on("end", () => this.dispose());- this.socket.on("error", () => this.dispose());+ }++ cleanupBuffers() {+ this.buffer = Buffer.alloc(0);+ this.fragmentOpcode = null;+ this.fragmentParts = [];+ this.fragmentBytes = 0;}sendFrame(opcode, payload) {@@ -296,12 +342,21 @@ class ResponsesWsSession {}async onData(chunk) {+ if (this.closed) return;this.lastSeenAt = Date.now();+ if (this.buffer.length + chunk.length > this.maxBufferBytes) {+ throw new WebSocketInputTooLargeError("WebSocket input buffer exceeds configured limit");+ }this.buffer = Buffer.concat([this.buffer, chunk]);- const parsed = decodeClientFrames(this.buffer);+ const parsed = decodeClientFrames(this.buffer, { maxPayloadBytes: this.maxMessageBytes });this.buffer = parsed.remaining;+ if (this.buffer.length > this.maxBufferBytes) {+ throw new WebSocketInputTooLargeError("WebSocket input buffer exceeds configured limit");+ }+for (const frame of parsed.frames) {+ if (this.closed) return;await this.handleFrame(frame);}}@@ -313,12 +368,19 @@ class ResponsesWsSession {this.sendFailure("unexpected_continuation", "Unexpected continuation frame");return;}+ this.fragmentBytes += frame.payload.length;+ if (this.fragmentBytes > this.maxMessageBytes) {+ throw new WebSocketInputTooLargeError(+ "Fragmented WebSocket message exceeds configured limit"+ );+ }this.fragmentParts.push(frame.payload);if (frame.fin) {const payload = Buffer.concat(this.fragmentParts);const opcode = this.fragmentOpcode;this.fragmentOpcode = null;this.fragmentParts = [];+ this.fragmentBytes = 0;await this.handleDataFrame(opcode, payload);}return;@@ -327,6 +389,12 @@ class ResponsesWsSession {if (!frame.fin) {this.fragmentOpcode = frame.opcode;this.fragmentParts = [frame.payload];+ this.fragmentBytes = frame.payload.length;+ if (this.fragmentBytes > this.maxMessageBytes) {+ throw new WebSocketInputTooLargeError(+ "Fragmented WebSocket message exceeds configured limit"+ );+ }return;}await this.handleDataFrame(frame.opcode, frame.payload);@@ -346,6 +414,9 @@ class ResponsesWsSession {}async handleDataFrame(opcode, payload) {+ if (payload.length > this.maxMessageBytes) {+ throw new WebSocketInputTooLargeError("WebSocket message exceeds configured limit");+ }if (opcode !== 0x1) {this.sendFailure("unsupported_payload", "Only UTF-8 text messages are supported");return;@@ -452,6 +523,7 @@ class ResponsesWsSession {this.closed = true;clearInterval(this.pingTimer);+ this.cleanupBuffers();try {this.upstream?.close?.(code, reason);} catch {@@ -462,7 +534,9 @@ class ResponsesWsSession {const payload = Buffer.allocUnsafe(2 + reasonBuffer.length);payload.writeUInt16BE(code, 0);reasonBuffer.copy(payload, 2);- this.sendFrame(0x8, payload);+ if (!this.socket.destroyed && this.socket.writable) {+ this.socket.write(encodeWsFrame(0x8, payload));+ }this.socket.end();setTimeout(() => {if (!this.socket.destroyed) {@@ -475,6 +549,7 @@ class ResponsesWsSession {if (this.closed) return;this.closed = true;clearInterval(this.pingTimer);+ this.cleanupBuffers();try {this.upstream?.close?.(1000, "downstream_closed");} catch {@@ -490,6 +565,8 @@ export function createResponsesWsProxy({wsFactory = websocket,pingIntervalMs = 25000,idleTimeoutMs = 90000,+ maxBufferBytes = DEFAULT_MAX_WS_BUFFER_BYTES,+ maxMessageBytes = DEFAULT_MAX_WS_MESSAGE_BYTES,} = {}) {if (!isText(baseUrl)) {throw new Error("createResponsesWsProxy requires a baseUrl");@@ -577,6 +654,8 @@ export function createResponsesWsProxy({wsFactory,pingIntervalMs,idleTimeoutMs,+ maxBufferBytes,+ maxMessageBytes,});return true;} catch (error) {diff --git a/src/app/(dashboard)/dashboard/playground/ChatPlayground.tsx b/src/app/(dashboard)/dashboard/playground/ChatPlayground.tsxindex 32735609cc..e677e5682c 100644--- a/src/app/(dashboard)/dashboard/playground/ChatPlayground.tsx+++ b/src/app/(dashboard)/dashboard/playground/ChatPlayground.tsx@@ -204,10 +204,7 @@ export default function ChatPlayground({options={[{value: "",- label:- providerConnections.length > 0- ? autoAccountsString- : noAccountsString,+ label: providerConnections.length > 0 ? autoAccountsString : noAccountsString,},...providerConnections.map((c) => ({value: c.id,@@ -224,9 +221,7 @@ export default function ChatPlayground({<div className="p-4 space-y-3"><div className="flex items-center justify-between"><div className="flex items-center gap-2">- <span className="material-symbols-outlined text-[18px] text-text-muted">- chat- </span>+ <span className="material-symbols-outlined text-[18px] text-text-muted">chat</span><h3 className="text-sm font-semibold text-text-main">Conversational Chat</h3>{responseStatus !== null && (<Badge variant={responseStatus < 400 ? "success" : "error"} size="sm">@@ -264,8 +259,8 @@ export default function ChatPlayground({msg.role === "user"? "bg-primary text-primary-foreground rounded-tr-sm": msg.role === "system"- ? "bg-black/5 dark:bg-white/5 border border-border text-text-muted w-full"- : "bg-bg-alt border border-border text-text-main rounded-tl-sm"+ ? "bg-black/5 dark:bg-white/5 border border-border text-text-muted w-full"+ : "bg-bg-alt border border-border text-text-main rounded-tl-sm"}`}>{msg.content}@@ -274,9 +269,7 @@ export default function ChatPlayground({))}{loading && messages[messages.length - 1]?.role === "user" && (<div className="flex flex-col max-w-[85%] mr-auto items-start">- <span className="text-[10px] text-text-muted uppercase mb-1 px-1">- assistant- </span>+ <span className="text-[10px] text-text-muted uppercase mb-1 px-1">assistant</span><div className="px-4 py-2 rounded-2xl text-sm bg-bg-alt border border-border rounded-tl-sm text-text-muted flex items-center gap-2"><span className="material-symbols-outlined text-[16px] animate-spin">progress_activitydiff --git a/src/app/api/internal/codex-responses-ws/route.ts b/src/app/api/internal/codex-responses-ws/route.tsindex 235dc58b9a..eda29b1382 100644--- a/src/app/api/internal/codex-responses-ws/route.ts+++ b/src/app/api/internal/codex-responses-ws/route.ts@@ -1,5 +1,5 @@import { NextResponse } from "next/server";-import { z } from "zod";+import { createHash, timingSafeEqual } from "node:crypto";import { CodexExecutor } from "@omniroute/open-sse/executors/codex.ts";import { getApiKeyMetadata } from "@/lib/db/apiKeys";import { authorizeWebSocketHandshake, extractWsTokenFromRequest } from "@/lib/ws/handshake";@@ -12,15 +12,6 @@ const executor = new CodexExecutor();type JsonRecord = Record<string, unknown>;-const bridgePayloadSchema = z- .object({- action: z.string().optional(),- requestUrl: z.string().optional(),- headers: z.record(z.string(), z.unknown()).optional(),- response: z.record(z.string(), z.unknown()).optional(),- })- .passthrough();-function isRecord(value: unknown): value is JsonRecord {return typeof value === "object" && value !== null && !Array.isArray(value);}@@ -29,6 +20,17 @@ function getBridgeSecret(): string {return process.env.OMNIROUTE_WS_BRIDGE_SECRET || "";}+function hashBridgeSecret(value: string): Buffer {+ return createHash("sha256").update(value).digest();+}++export function bridgeSecretMatches(expectedSecret: string, receivedSecret: string): boolean {+ if (!expectedSecret || !receivedSecret) return false;+ const expectedHash = hashBridgeSecret(expectedSecret);+ const receivedHash = hashBridgeSecret(receivedSecret);+ return timingSafeEqual(expectedHash, receivedHash);+}+function getAuthRequest(body: JsonRecord): Request {const requestUrl = typeof body.requestUrl === "string" ? body.requestUrl : "/api/v1/responses";const headers = isRecord(body.headers) ? body.headers : {};@@ -171,18 +173,14 @@ async function prepare(body: JsonRecord) {export async function POST(request: Request) {const expectedSecret = getBridgeSecret();const receivedSecret = request.headers.get("x-omniroute-ws-bridge-secret") || "";- if (!expectedSecret || receivedSecret !== expectedSecret) {+ if (!bridgeSecretMatches(expectedSecret, receivedSecret)) {return jsonError(403, "internal_bridge_forbidden", "Forbidden");}let body: JsonRecord;try {const parsed = await request.json();- const validation = bridgePayloadSchema.safeParse(parsed);- if (!validation.success) {- return jsonError(400, "invalid_json", "Request body must be a JSON object");- }- body = validation.data;+ body = isRecord(parsed) ? parsed : {};} catch {return jsonError(400, "invalid_json", "Request body must be JSON");}diff --git a/src/lib/memory/extraction.ts b/src/lib/memory/extraction.tsindex 6ecef6f3f1..48617e14ac 100644--- a/src/lib/memory/extraction.ts+++ b/src/lib/memory/extraction.ts@@ -48,6 +48,7 @@ const PATTERN_PATTERNS: RegExp[] = [const MAX_FACT_LENGTH = 500;// Minimum content length to avoid noiseconst MIN_FACT_LENGTH = 3;+const MAX_EXTRACTION_TEXT_LENGTH = 64 * 1024;// ─── Types ──────────────────────────────────────────────────────────────────@@ -67,6 +68,11 @@ function sanitizeMatch(raw: string): string {return raw.trim().replace(/\s+/g, " ").slice(0, MAX_FACT_LENGTH);}+function capExtractionText(text: string): string {+ if (text.length <= MAX_EXTRACTION_TEXT_LENGTH) return text;+ return text.slice(-MAX_EXTRACTION_TEXT_LENGTH);+}+/*** Generate a stable key for a fact (category + first 40 chars of content)*/@@ -126,6 +132,8 @@ function runPatterns(export function extractFactsFromText(text: string): ExtractedFact[] {if (!text || typeof text !== "string") return [];+ text = capExtractionText(text);+const seen = new Set<string>();const facts: ExtractedFact[] = [];@@ -153,11 +161,13 @@ export function extractFactsFromText(text: string): ExtractedFact[] {export function extractFacts(response: string, apiKeyId: string, sessionId: string): void {if (!response || !apiKeyId || !sessionId) return;+ const cappedResponse = capExtractionText(response);+log.info("memory.extraction.start", { apiKeyId });// Non-blocking: schedule after current event loop ticksetImmediate(() => {- const facts = extractFactsFromText(response);+ const facts = extractFactsFromText(cappedResponse);if (facts.length === 0) return;for (const fact of facts) {diff --git a/src/sse/handlers/chat.ts b/src/sse/handlers/chat.tsindex 083a8a1267..8079dac461 100644--- a/src/sse/handlers/chat.ts+++ b/src/sse/handlers/chat.ts@@ -718,6 +718,7 @@ async function handleSingleModelChat(comboStepId: runtimeOptions.comboStepId ?? null,comboExecutionKey: runtimeOptions.comboExecutionKey ?? runtimeOptions.comboStepId ?? null,extendedContext,+ providerProfile,});if (telemetry) telemetry.endPhase();diff --git a/src/sse/handlers/chatHelpers.ts b/src/sse/handlers/chatHelpers.tsindex 8a1ff0f27a..11382c42f8 100644--- a/src/sse/handlers/chatHelpers.ts+++ b/src/sse/handlers/chatHelpers.ts@@ -1,5 +1,5 @@import { getModelInfo } from "../services/model";-import { clearAccountError } from "../services/auth";+import { clearAccountError, markAccountUnavailable } from "../services/auth";import * as log from "../utils/logger";import { updateProviderCredentials } from "../services/tokenRefresh";import {@@ -120,6 +120,7 @@ export async function executeChatWithBreaker({comboStepId,comboExecutionKey,extendedContext,+ providerProfile,}: any): Promise<{ result: any; tlsFingerprintUsed: boolean }> {let tlsFingerprintUsed = false;@@ -153,6 +154,17 @@ export async function executeChatWithBreaker({onRequestSuccess: async () => {await clearAccountError(credentials.connectionId, credentials);},+ onStreamFailure: async (failure: any) => {+ if (!credentials.connectionId) return;+ await markAccountUnavailable(+ credentials.connectionId,+ Number(failure?.status || HTTP_STATUS.BAD_GATEWAY),+ String(failure?.message || failure?.code || "stream failure"),+ provider,+ model,+ providerProfile+ );+ },}));diff --git a/tests/unit/executor-codex.test.ts b/tests/unit/executor-codex.test.tsindex e8797518dd..3dbddf3deb 100644--- a/tests/unit/executor-codex.test.ts+++ b/tests/unit/executor-codex.test.ts@@ -370,167 +370,36 @@ test("CodexExecutor.refreshCredentials refreshes OAuth tokens and returns null w}});-test("CodexExecutor.transformRequest preserves image_generation hosted tool for Codex CLI", () => {- const executor = new CodexExecutor();- const body = {- _nativeCodexPassthrough: true,- input: [],- tools: [{ type: "image_generation", output_format: "png" }],- };-- const result = executor.transformRequest("gpt-5.3-codex", body, true, {- requestEndpointPath: "/responses",- });-- assert.deepEqual(result.tools, [{ type: "image_generation", output_format: "png" }]);-});--test("CodexExecutor.transformRequest preserves web_search and file_search hosted tools", () => {- const executor = new CodexExecutor();- const body = {- _nativeCodexPassthrough: true,- input: [],- tools: [- { type: "web_search" },- { type: "file_search" },- { type: "image_generation", output_format: "png" },- ],- };-- const result = executor.transformRequest("gpt-5.3-codex", body, true, {- requestEndpointPath: "/responses",- });-- assert.deepEqual(result.tools, [- { type: "web_search" },- { type: "file_search" },- { type: "image_generation", output_format: "png" },- ]);-});--test("CodexExecutor.transformRequest drops unknown hosted tool types", () => {- const executor = new CodexExecutor();- const body = {- _nativeCodexPassthrough: true,- input: [],- tools: [{ type: "made_up_tool" }, { type: "image_generation", output_format: "png" }],- };-- const result = executor.transformRequest("gpt-5.3-codex", body, true, {- requestEndpointPath: "/responses",- });-- assert.deepEqual(result.tools, [{ type: "image_generation", output_format: "png" }]);-});--test("CodexExecutor.transformRequest keeps valid function tools and drops empty-named ones", () => {- const executor = new CodexExecutor();- const body = {- _nativeCodexPassthrough: true,- input: [],- tools: [- { type: "function", function: { name: "" } },- { type: "function", function: { name: " " } },- { type: "function", function: { name: "shell", parameters: {} } },- ],- };-- const result = executor.transformRequest("gpt-5.3-codex", body, true, {- requestEndpointPath: "/responses",- });-- assert.equal(result.tools.length, 1);- assert.equal(result.tools[0].function.name, "shell");-});--test("CodexExecutor.transformRequest leaves hosted tool_choice untouched and strips stale function tool_choice", () => {- const executor = new CodexExecutor();-- const hostedChoice = executor.transformRequest(- "gpt-5.3-codex",- {- _nativeCodexPassthrough: true,- input: [],- tools: [{ type: "image_generation", output_format: "png" }],- tool_choice: { type: "image_generation" },- },- true,- { requestEndpointPath: "/responses" }- );-- assert.deepEqual(hostedChoice.tool_choice, { type: "image_generation" });-- const staleChoice = executor.transformRequest(- "gpt-5.3-codex",- {- _nativeCodexPassthrough: true,- input: [],- tools: [{ type: "function", function: { name: "shell" } }],- tool_choice: { type: "function", name: "ghost" },+test("CodexExecutor maps usage_limit_reached websocket failures without explicit status to 429", () => {+ const raw = JSON.stringify({+ type: "response.failed",+ response: {+ id: "resp_usage_limit",+ status: "failed",+ error: {+ code: "usage_limit_reached",+ message: "Your weekly usage limit has been reached",+ },},- true,- { requestEndpointPath: "/responses" }- );-- assert.equal(staleChoice.tool_choice, undefined);-});--test("CodexExecutor.transformRequest drops hosted tools that also declare name or function properties", () => {- const executor = new CodexExecutor();- const body = {- _nativeCodexPassthrough: true,- input: [],- tools: [- { type: "image_generation", name: "img", output_format: "png" },- { type: "image_generation", function: { name: "img" }, output_format: "png" },- { type: "image_generation", output_format: "png" },- ],- };-- const result = executor.transformRequest("gpt-5.3-codex", body, true, {- requestEndpointPath: "/responses",});- assert.deepEqual(result.tools, [{ type: "image_generation", output_format: "png" }]);-});--test("CodexExecutor.transformRequest defaults store to false when image_generation tool is present", () => {- const executor = new CodexExecutor();+ const result = encodeResponseSseEvent(raw);+ assert.equal(result.terminal, true);- const withImageGen = executor.transformRequest(- "gpt-5.3-codex",- {- _nativeCodexPassthrough: true,- input: [],- tools: [{ type: "image_generation", output_format: "png" }],- },- true,- { requestEndpointPath: "/responses" }- );- assert.equal(withImageGen.store, false);+ const dataLine = result.sse.split("\n").find((line) => line.startsWith("data: "));+ assert.ok(dataLine);+ const payload = JSON.parse(dataLine.slice("data: ".length));+ assert.equal(payload.type, "response.failed");+ assert.equal(payload.response.id, "resp_usage_limit");+ assert.equal(payload.response.error.code, "usage_limit_reached");+ assert.equal(payload.response.error.status_code, 429);+});- const withoutImageGen = executor.transformRequest(- "gpt-5.3-codex",- {- _nativeCodexPassthrough: true,- input: [],- tools: [{ type: "function", function: { name: "shell" } }],- },- true,- { requestEndpointPath: "/responses" }- );- assert.equal(withoutImageGen.store, true);+test("Codex internal websocket bridge secret comparison handles mismatched lengths safely", async () => {+ const { bridgeSecretMatches } =+ await import("../../src/app/api/internal/codex-responses-ws/route.ts");- const explicitTrue = executor.transformRequest(- "gpt-5.3-codex",- {- _nativeCodexPassthrough: true,- input: [],- store: true,- tools: [{ type: "image_generation", output_format: "png" }],- },- true,- { requestEndpointPath: "/responses" }- );- assert.equal(explicitTrue.store, true);+ assert.equal(bridgeSecretMatches("bridge-secret", "bridge-secret"), true);+ assert.equal(bridgeSecretMatches("bridge-secret", "bridge-secret-extra"), false);+ assert.equal(bridgeSecretMatches("bridge-secret", ""), false);});diff --git a/tests/unit/image-generation-handler.test.ts b/tests/unit/image-generation-handler.test.tsindex caa27fe2bd..4eafc2cfd1 100644--- a/tests/unit/image-generation-handler.test.ts+++ b/tests/unit/image-generation-handler.test.ts@@ -1474,9 +1474,7 @@ test("handleImageGeneration normalizes Imagen3 single-image payloads and non-okconst { extractImageGenerationCalls } = await import("../../open-sse/handlers/imageGeneration.ts");function buildCodexSSE(items) {- const frames = items.map((item) =>- JSON.stringify({ type: "response.output_item.done", item })- );+ const frames = items.map((item) => JSON.stringify({ type: "response.output_item.done", item }));return frames.map((frame) => `event: response.output_item.done\ndata: ${frame}\n`).join("\n");}diff --git a/tests/unit/memory-extraction.test.ts b/tests/unit/memory-extraction.test.tsindex 9355d5fadf..6cd57c5c86 100644--- a/tests/unit/memory-extraction.test.ts+++ b/tests/unit/memory-extraction.test.ts@@ -167,3 +167,19 @@ test("extractFacts: does not throw on empty inputs", () => {assert.doesNotThrow(() => extractFacts("I prefer vim.", "key-123", ""));assert.doesNotThrow(() => extractFacts(null, "key-123", "session-456"));});++test("extractFactsFromText scans only the bounded tail of very large text", () => {+ const text =+ "I prefer prefix-only-editor. " + "x".repeat(70 * 1024) + " I prefer tail-only-editor.";+ const facts = extractFactsFromText(text);+ const contents = facts.map((fact) => fact.content.toLowerCase());++ assert.equal(+ contents.some((content) => content.includes("prefix-only-editor")),+ false+ );+ assert.equal(+ contents.some((content) => content.includes("tail-only-editor")),+ true+ );+});diff --git a/tests/unit/plan3-p0.test.ts b/tests/unit/plan3-p0.test.tsindex d75c340b1a..efc5fc819e 100644--- a/tests/unit/plan3-p0.test.ts+++ b/tests/unit/plan3-p0.test.ts@@ -52,6 +52,18 @@ test("getModelInfoCore resolves gpt-5.5 to codex", async () => {assert.equal(info.model, "gpt-5.5");});+test("getModelInfoCore resolves gpt-5.5 to codex", async () => {+ const info = await getModelInfoCore("gpt-5.5", {});+ assert.equal(info.provider, "codex");+ assert.equal(info.model, "gpt-5.5");+});++test("getModelInfoCore resolves explicit gpt-5.5 Codex model", async () => {+ const info = await getModelInfoCore("cx/gpt-5.5", {});+ assert.equal(info.provider, "codex");+ assert.equal(info.model, "gpt-5.5");+});+test("getModelInfoCore returns explicit ambiguity metadata for ambiguous unprefixed model", async () => {const info = await getModelInfoCore("claude-haiku-4.5", {});assert.equal(info.provider, null);diff --git a/tests/unit/responses-ws-proxy.test.mjs b/tests/unit/responses-ws-proxy.test.mjsindex 51bf5c3448..b2c02ce845 100644--- a/tests/unit/responses-ws-proxy.test.mjs+++ b/tests/unit/responses-ws-proxy.test.mjs@@ -157,3 +157,141 @@ test("responses ws proxy prepares and forwards OpenAI Responses websocket eventsws.close();await close(server);});++test("responses ws proxy serializes client frames while upstream prepare is pending", async () => {+ const internalRequests = [];+ const upstreamSends = [];++ const server = http.createServer(async (req, res) => {+ const url = new URL(req.url || "/", `http://${req.headers.host}`);+ if (url.pathname === "/api/internal/codex-responses-ws") {+ const body = JSON.parse((await readRequestBody(req)) || "{}");+ internalRequests.push(body);++ if (body.action === "authenticate") {+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ ok: true, authenticated: true, authType: "api_key" }));+ return;+ }++ if (body.action === "prepare") {+ await new Promise((resolve) => setTimeout(resolve, 50));+ res.writeHead(200, { "content-type": "application/json" });+ res.end(+ JSON.stringify({+ ok: true,+ upstreamUrl: "wss://chatgpt.com/backend-api/codex/responses",+ headers: { Authorization: "Bearer upstream-token" },+ response: { ...body.response, model: "gpt-5.5", stream: undefined },+ })+ );+ return;+ }+ }++ res.writeHead(404, { "content-type": "application/json" });+ res.end(JSON.stringify({ error: "not_found" }));+ });++ const fakeUpstream = {+ send(data) {+ upstreamSends.push(JSON.parse(data));+ },+ close() {},+ onmessage: null,+ onerror: null,+ onclose: null,+ };++ const port = await listen(server);+ const proxy = createResponsesWsProxy({+ baseUrl: `http://127.0.0.1:${port}`,+ bridgeSecret: "bridge-secret",+ pingIntervalMs: 1000,+ idleTimeoutMs: 10000,+ wsFactory: async () => fakeUpstream,+ });++ server.on("upgrade", async (req, socket, head) => {+ const handled = await proxy.handleUpgrade(req, socket, head);+ if (!handled && !socket.destroyed) {+ socket.destroy();+ }+ });++ const ws = new WebSocket(`ws://127.0.0.1:${port}/api/v1/responses?api_key=local-token`);+ await new Promise((resolve) => ws.addEventListener("open", resolve, { once: true }));++ ws.send(+ JSON.stringify({+ type: "response.create",+ model: "gpt-5.5",+ input: [{ role: "user", content: "first" }],+ })+ );+ ws.send(JSON.stringify({ type: "response.cancel", response_id: "resp_1" }));++ await waitFor(() => upstreamSends.length === 2);++ assert.equal(internalRequests.filter((entry) => entry.action === "prepare").length, 1);+ assert.equal(upstreamSends[0].type, "response.create");+ assert.equal(upstreamSends[0].input[0].content, "first");+ assert.equal(upstreamSends[1].type, "response.cancel");+ assert.equal(upstreamSends[1].response_id, "resp_1");++ ws.close();+ await close(server);+});++test("responses ws proxy closes oversized client messages with 1009", async () => {+ const server = http.createServer(async (req, res) => {+ const url = new URL(req.url || "/", `http://${req.headers.host}`);+ if (url.pathname === "/api/internal/codex-responses-ws") {+ const body = JSON.parse((await readRequestBody(req)) || "{}");+ if (body.action === "authenticate") {+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ ok: true, authenticated: true, authType: "api_key" }));+ return;+ }+ }++ res.writeHead(404, { "content-type": "application/json" });+ res.end(JSON.stringify({ error: "not_found" }));+ });++ const port = await listen(server);+ const proxy = createResponsesWsProxy({+ baseUrl: `http://127.0.0.1:${port}`,+ bridgeSecret: "bridge-secret",+ pingIntervalMs: 1000,+ idleTimeoutMs: 10000,+ maxMessageBytes: 64,+ wsFactory: async () => {+ throw new Error("oversized input should close before upstream connect");+ },+ });++ server.on("upgrade", async (req, socket, head) => {+ const handled = await proxy.handleUpgrade(req, socket, head);+ if (!handled && !socket.destroyed) {+ socket.destroy();+ }+ });++ const ws = new WebSocket(`ws://127.0.0.1:${port}/api/v1/responses?api_key=local-token`);+ const closed = new Promise((resolve) => ws.addEventListener("close", resolve, { once: true }));+ await new Promise((resolve) => ws.addEventListener("open", resolve, { once: true }));++ ws.send(+ JSON.stringify({+ type: "response.create",+ model: "gpt-5.5",+ input: [{ role: "user", content: "x".repeat(128) }],+ })+ );++ const event = await closed;+ assert.equal(event.code, 1009);++ await close(server);+});diff --git a/tests/unit/stream-utils.test.ts b/tests/unit/stream-utils.test.tsindex 9117d4fca8..594327ff87 100644--- a/tests/unit/stream-utils.test.ts+++ b/tests/unit/stream-utils.test.ts@@ -16,6 +16,7 @@ const {createStructuredSSECollector,} = await import("../../open-sse/utils/streamPayloadCollector.ts");const { FORMATS } = await import("../../open-sse/translator/formats.ts");+const { createRequestLogger } = await import("../../open-sse/utils/requestLogger.ts");const textEncoder = new TextEncoder();const SYNTHETIC_CLAUDE_EMPTY_RESPONSE_TEXT =@@ -890,3 +891,65 @@ test("createSSEStream passthrough drops keepalive event blocks without losing Reassert.match(text, /Hello keepalive-safe/);assert.match(text, /data: \[DONE\]/);});++test("createSSEStream passthrough aborts on Responses usage-limit failures and reports 429", async () => {+ let failurePayload = null;++ await assert.rejects(+ readTransformed(+ [+ `data: ${JSON.stringify({+ type: "response.failed",+ response: {+ id: "resp_usage_limit",+ object: "response",+ model: "gpt-5.5",+ status: "failed",+ error: {+ code: "usage_limit_reached",+ message: "Your weekly usage limit has been reached",+ },+ },+ })}\n\n`,+ ],+ {+ mode: "passthrough",+ sourceFormat: FORMATS.OPENAI_RESPONSES,+ provider: "codex",+ model: "gpt-5.5",+ body: { input: "hello" },+ onFailure(payload) {+ failurePayload = payload;+ },+ }+ ),+ /weekly usage limit|Upstream failure/+ );++ assert.ok(failurePayload, "should report the stream failure before aborting");+ assert.equal(failurePayload.status, 429);+ assert.equal(failurePayload.code, "usage_limit_reached");+});++test("createRequestLogger skips disabled logs and caps retained stream chunk bytes", async () => {+ const disabled = await createRequestLogger("openai", "openai", "gpt-test", {+ enabled: false,+ });+ disabled.logClientRawRequest("/v1/chat/completions", { prompt: "hello" });+ disabled.appendProviderChunk("x".repeat(32));+ assert.equal(disabled.getPipelinePayloads(), null);++ const logger = await createRequestLogger("openai", "openai", "gpt-test", {+ enabled: true,+ captureStreamChunks: true,+ maxStreamChunkBytes: 5,+ });+ logger.appendProviderChunk("abcdef");+ logger.appendProviderChunk("ghijkl");+ const payloads = logger.getPipelinePayloads();++ assert.deepEqual(payloads.streamChunks.provider, [+ "abcde",+ "[stream chunk log truncated after 5 bytes]",+ ]);+});