Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): 透传 Responses 里 null 数组字段补成空数组,第三方模型不再说一句就停 (#4266)
FicoWang035bef212fb6
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 55a982df7d..38398b3a16 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -2,6 +2,7 @@ import fs from 'node:fs';import { once } from 'node:events';import { WebSocket, WebSocketServer } from 'ws';import { createServer, request as httpRequest } from 'node:http';+import { Transform } from 'node:stream';import type { AddressInfo } from 'node:net';import os from 'node:os';import path from 'node:path';@@ -2950,6 +2951,86 @@ describe('codex proxy host', () => {}});+ it('repairs null array fields in passthrough Responses SSE before Codex parses them (#4251)', async () => {+ const host = await freshCodexProxyHost();+ // Minimal reproduction from #4251: a third-party model behind the Responses passthrough+ // serializes `reasoning.summary` / `message.content` as null, which Codex 0.153 rejects.+ const upstreamEvents = [+ { type: 'response.output_item.added', output_index: 0, item: { id: 'rs_1', type: 'reasoning', status: 'in_progress', summary: null } },+ { type: 'response.output_item.added', output_index: 1, item: { id: 'msg_2', type: 'message', status: 'in_progress', role: 'assistant', content: null } },+ { type: 'response.output_text.delta', item_id: 'msg_2', output_index: 1, content_index: 0, delta: '我查一下' },+ { type: 'response.output_item.added', output_index: 2, item: { id: 'fc_3', type: 'function_call', status: 'in_progress', call_id: 'call_3', name: 'exec', arguments: '' } },+ { type: 'response.function_call_arguments.done', item_id: 'fc_3', output_index: 2, arguments: JSON.stringify({ input: 'ls' }) },+ { type: 'response.output_item.done', output_index: 2, item: { id: 'fc_3', type: 'function_call', status: 'completed', call_id: 'call_3', name: 'exec', arguments: JSON.stringify({ input: 'ls' }) } },+ { type: 'response.completed', response: { id: 'resp_1', output: [+ { id: 'rs_1', type: 'reasoning', summary: null },+ { id: 'msg_2', type: 'message', role: 'assistant', content: null },+ ], usage: { input_tokens: 1, output_tokens: 1 } } },+ ];+ const upstream = createServer(async (req, res) => {+ for await (const chunk of req) void chunk;+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'close' });+ for (const event of upstreamEvents) res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);+ res.end();+ });+ await new Promise<void>(resolve => upstream.listen(0, '127.0.0.1', resolve));+ const upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;+ const actual = await vi.importActual<typeof import('@cindy/anthropic-compat-proxy')>('@cindy/anthropic-compat-proxy');+ mockState.createAnthropicCompatProxy.mockImplementation((opts: Parameters<typeof actual.createAnthropicCompatProxy>[0]) =>+ actual.createAnthropicCompatProxy({+ ...opts,+ upstream: upstreamUrl,+ resolveOutboundProxy: () => null,+ routingTransform: async (body, ctx) => ({ ...(await opts.routingTransform?.(body, ctx)), upstreamOverride: upstreamUrl }),+ }),+ );+ host.setCodexProxyAuthInjection('oauth-bearer');+ try {+ await host.ensureCodexProxyReady();+ const proxyUrl = host.getCodexProxyEndpoint()!;+ const post = (body: Record<string, unknown>) => new Promise<string>((resolve, reject) => {+ const req = httpRequest(proxyUrl + '/v1/responses', { method: 'POST', headers: { 'content-type': 'application/json' } }, res => {+ const chunks: Buffer[] = [];+ res.on('data', (chunk: Buffer) => chunks.push(chunk));+ res.once('end', () => resolve(Buffer.concat(chunks).toString('utf8')));+ });+ req.once('error', reject);+ req.end(JSON.stringify(body));+ });+ const parse = (raw: string) => raw.split('\n\n').filter(Boolean).map(frame =>+ JSON.parse(frame.split('\n').find(line => line.startsWith('data: '))!.slice(6)) as {+ type: string; item?: Record<string, unknown>; response?: { output: Array<Record<string, unknown>> };+ });++ // Plain passthrough: only the repair stage is active.+ const plain = parse(await post({ model: 'gpt-6', stream: true, input: [{ type: 'message', role: 'user', content: [{ type: 'input_text', text: 'hi' }] }] }));+ expect(plain.map(event => event.type)).toEqual(upstreamEvents.map(event => event.type));+ expect(plain[0]?.item).toEqual({ id: 'rs_1', type: 'reasoning', status: 'in_progress', summary: [] });+ expect(plain[1]?.item).toEqual({ id: 'msg_2', type: 'message', status: 'in_progress', role: 'assistant', content: [] });+ expect(plain[3]?.item).toEqual(upstreamEvents[3]!.item); // function_call passes through untouched+ expect(plain[6]?.response?.output).toEqual([+ { id: 'rs_1', type: 'reasoning', summary: [] },+ { id: 'msg_2', type: 'message', role: 'assistant', content: [] },+ ]);++ // Wiring: the proxy-level transformResponse only wraps plain SSE bodies. Chaining with the+ // exec custom-tool adapter is covered by the responses-chat-bridge unit tests.+ const proxyOpts = mockState.createAnthropicCompatProxy.mock.calls[0]![0] as {+ transformResponse: (ctx: Record<string, unknown>) => unknown;+ };+ const responseCtx = (contentType: string) => ({+ reqId: 999, method: 'POST', url: '/v1/responses', upstreamBase: upstreamUrl, status: 200,+ requestHeaders: {}, responseHeaders: { 'content-type': contentType }, requestBody: Buffer.alloc(0),+ });+ expect(proxyOpts.transformResponse(responseCtx('application/json'))).toBeNull();+ expect(proxyOpts.transformResponse(responseCtx('text/event-stream'))).toBeInstanceOf(Transform);+ } finally {+ await host.disposeCodexProxy();+ upstream.closeAllConnections();+ await new Promise<void>(resolve => upstream.close(() => resolve()));+ }+ });+it.each([["Invalid 'input[2].id': 'ctc_old'. Expected an ID that begins with 'fc'.", 'tool_item_id'],[JSON.stringify({ error: { message: "Invalid \"input[2].id\": \"fco_old\". Expected an ID that begins with \"ctco\"." } }), 'tool_item_id'],diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex 668e3ebe0e..087eb3e308 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -41,7 +41,9 @@ import {} from '@cindy/anthropic-compat-proxy';import { buildVisionBridgeProxyTransform } from '../vision-bridge/vision-bridge-controller.js';import {+ chainResponseTransforms,createResponsesCustomToolFunctionAdapter,+ createResponsesNullArrayRepairTransform,normalizeResponsesToolItemIds,createResponsesChatHandler,type ChatBridgeCapabilities,@@ -3396,10 +3398,18 @@ function createCodexProxyHandle(return path.kind !== 'not-custom-provider-route'&& !(path.kind === 'route' && path.pathKind === 'responses');},- transformResponse: (ctx) => execAdapter.createResponseTransform(ctx.reqId, {- contentType: ctx.responseHeaders['content-type'] ?? '',- contentEncoding: ctx.responseHeaders['content-encoding'] ?? '',- }),+ transformResponse: (ctx) => {+ const response = {+ contentType: ctx.responseHeaders['content-type'] ?? '',+ contentEncoding: ctx.responseHeaders['content-encoding'] ?? '',+ };+ // Repair runs first so items with `null` arrays reach the custom-tool adapter (and Codex)+ // as valid ResponseItems (#4251). The adapter keeps its own compressed/MIME rejections.+ return chainResponseTransforms(+ createResponsesNullArrayRepairTransform(response),+ execAdapter.createResponseTransform(ctx.reqId, response),+ );+ },// 常规 session proxy 继续读取当前全局 spawn 形态;control-plane proxy 在创建时// 冻结自己的形态,两个 app-server 并行时不会互相改写路由。routingTransform: withCodexUpstreamRecording(diff --git a/packages/responses-chat-bridge/src/__tests__/responses-null-array-repair.test.ts b/packages/responses-chat-bridge/src/__tests__/responses-null-array-repair.test.tsnew file mode 100644index 0000000000..f5be51356a--- /dev/null+++ b/packages/responses-chat-bridge/src/__tests__/responses-null-array-repair.test.ts@@ -0,0 +1,469 @@+import { PassThrough, Transform } from "node:stream";+import { describe, expect, it } from "vitest";+import {+ chainResponseTransforms,+ createResponsesNullArrayRepairTransform,+ repairResponsesEventNullArrays,+ repairResponsesItemNullArrays,+ ResponsesNullArrayRepairTransform,+} from "../responses-null-array-repair.js";++/** The exact minimal reproduction from #4251: array fields serialized as `null`. */+const REASONING_ADDED_NULL =+ '{"type":"response.output_item.added","output_index":0,"item":{"id":"rs_1","type":"reasoning","status":"in_progress","summary":null}}';+const MESSAGE_ADDED_NULL =+ '{"type":"response.output_item.added","output_index":1,"item":{"id":"msg_2","type":"message","status":"in_progress","role":"assistant","content":null}}';+const TEXT_DELTA =+ '{"type":"response.output_text.delta","item_id":"msg_2","output_index":1,"content_index":0,"delta":"Hello"}';++async function pump(+ transform: Transform,+ chunks: readonly string[],+): Promise<string> {+ const out: Buffer[] = [];+ const done = new Promise<void>((resolve, reject) => {+ transform.on("data", (chunk: Buffer) => out.push(chunk));+ transform.on("end", resolve);+ transform.on("error", reject);+ });+ for (const chunk of chunks) transform.write(Buffer.from(chunk, "utf8"));+ transform.end();+ await done;+ return Buffer.concat(out).toString("utf8");+}++describe("repairResponsesItemNullArrays", () => {+ it("replaces null reasoning.summary and message.content with empty arrays", () => {+ expect(+ repairResponsesItemNullArrays({+ type: "reasoning",+ id: "rs_1",+ summary: null,+ }),+ ).toEqual({+ type: "reasoning",+ id: "rs_1",+ summary: [],+ });+ expect(+ repairResponsesItemNullArrays({+ type: "message",+ role: "assistant",+ content: null,+ status: "in_progress",+ }),+ ).toEqual({+ type: "message",+ role: "assistant",+ content: [],+ status: "in_progress",+ });+ });++ it("leaves valid, missing, non-array and unknown-type items untouched", () => {+ expect(+ repairResponsesItemNullArrays({ type: "reasoning", summary: [] }),+ ).toBeNull();+ expect(+ repairResponsesItemNullArrays({ type: "reasoning", id: "rs_1" }),+ ).toBeNull();+ expect(+ repairResponsesItemNullArrays({ type: "reasoning", summary: "text" }),+ ).toBeNull();+ expect(+ repairResponsesItemNullArrays({+ type: "message",+ content: [{ type: "output_text", text: "x" }],+ }),+ ).toBeNull();+ expect(+ repairResponsesItemNullArrays({+ type: "function_call",+ name: "exec",+ arguments: null,+ }),+ ).toBeNull();+ expect(+ repairResponsesItemNullArrays({ type: "web_search_call", action: null }),+ ).toBeNull();+ expect(repairResponsesItemNullArrays(null)).toBeNull();+ expect(repairResponsesItemNullArrays("reasoning")).toBeNull();+ });++ it("does not touch the optional reasoning.content field", () => {+ expect(+ repairResponsesItemNullArrays({+ type: "reasoning",+ summary: [],+ content: null,+ }),+ ).toBeNull();+ expect(+ repairResponsesItemNullArrays({+ type: "reasoning",+ summary: null,+ content: null,+ }),+ ).toEqual({+ type: "reasoning",+ summary: [],+ content: null,+ });+ });+});++describe("repairResponsesEventNullArrays", () => {+ it("repairs output_item.added and output_item.done items", () => {+ const added = JSON.parse(REASONING_ADDED_NULL) as Record<string, unknown>;+ expect(repairResponsesEventNullArrays(added)).toEqual({+ ...added,+ item: { ...(added.item as object), summary: [] },+ });+ const done = {+ type: "response.output_item.done",+ output_index: 1,+ item: { type: "message", content: null },+ };+ expect(repairResponsesEventNullArrays(done)).toEqual({+ ...done,+ item: { type: "message", content: [] },+ });+ });++ it("repairs items inside response.output on completed events only when needed", () => {+ const completed = {+ type: "response.completed",+ response: {+ id: "resp_1",+ output: [+ { type: "reasoning", summary: null },+ {+ type: "function_call",+ call_id: "c1",+ name: "exec",+ arguments: "{}",+ },+ { type: "message", content: null },+ ],+ usage: { input_tokens: 1 },+ },+ };+ expect(repairResponsesEventNullArrays(completed)).toEqual({+ ...completed,+ response: {+ ...completed.response,+ output: [+ { type: "reasoning", summary: [] },+ {+ type: "function_call",+ call_id: "c1",+ name: "exec",+ arguments: "{}",+ },+ { type: "message", content: [] },+ ],+ },+ });+ expect(+ repairResponsesEventNullArrays({+ type: "response.completed",+ response: { output: [{ type: "message", content: [] }] },+ }),+ ).toBeNull();+ expect(+ repairResponsesEventNullArrays({+ type: "response.completed",+ response: { output: null },+ }),+ ).toBeNull();+ });++ it("ignores delta events, unknown shapes and non-objects", () => {+ expect(repairResponsesEventNullArrays(JSON.parse(TEXT_DELTA))).toBeNull();+ expect(+ repairResponsesEventNullArrays({+ type: "response.output_item.added",+ item: null,+ }),+ ).toBeNull();+ expect(+ repairResponsesEventNullArrays({+ item: { type: "message", content: null },+ }),+ ).toBeNull();+ expect(repairResponsesEventNullArrays("x")).toBeNull();+ });+});++describe("ResponsesNullArrayRepairTransform", () => {+ it("repairs the #4251 stream so every item carries an array", async () => {+ const input = `data: ${REASONING_ADDED_NULL}\n\ndata: ${MESSAGE_ADDED_NULL}\n\ndata: ${TEXT_DELTA}\n\ndata: [DONE]\n\n`;+ const output = await pump(new ResponsesNullArrayRepairTransform(), [input]);+ const frames = output.split("\n\n").filter(Boolean);+ expect(frames).toHaveLength(4);+ const added = frames.slice(0, 2).map(+ (frame) =>+ JSON.parse(frame.slice("data: ".length)) as {+ item: Record<string, unknown>;+ },+ );+ expect(added[0]!.item).toEqual({+ id: "rs_1",+ type: "reasoning",+ status: "in_progress",+ summary: [],+ });+ expect(added[1]!.item).toEqual({+ id: "msg_2",+ type: "message",+ status: "in_progress",+ role: "assistant",+ content: [],+ });+ expect(frames[2]).toBe(`data: ${TEXT_DELTA}`);+ expect(frames[3]).toBe("data: [DONE]");+ });++ it("re-emits streams that need no repair byte for byte, including CRLF framing and comments", async () => {+ const valid = REASONING_ADDED_NULL.replace(+ '"summary":null',+ '"summary":[]',+ );+ const input = `: keepalive\r\n\r\nevent: response.output_item.added\r\ndata: ${valid}\r\n\r\ndata: ${TEXT_DELTA}\r\n\r\nnot-json\r\n\r\ndata: [DONE]\r\n\r\n`;+ expect(await pump(new ResponsesNullArrayRepairTransform(), [input])).toBe(+ input,+ );+ });++ it("keeps the event line and CRLF delimiter when rewriting a named frame", async () => {+ const input = `event: response.output_item.added\r\ndata: ${MESSAGE_ADDED_NULL}\r\n\r\n`;+ const output = await pump(new ResponsesNullArrayRepairTransform(), [input]);+ expect(output.startsWith("event: response.output_item.added\ndata: ")).toBe(+ true,+ );+ expect(output.endsWith("\r\n\r\n")).toBe(true);+ expect(+ (+ JSON.parse(output.split("\ndata: ")[1]!.trim()) as {+ item: { content: unknown };+ }+ ).item.content,+ ).toEqual([]);+ });++ it("handles frames and multi-byte characters split across chunks", async () => {+ const message = MESSAGE_ADDED_NULL.replace(+ '"status":"in_progress"',+ '"status":"进行中"',+ );+ const whole = `data: ${message}\n\ndata: ${TEXT_DELTA}\n\n`;+ const bytes = Buffer.from(whole, "utf8");+ const cut = whole.indexOf("进") + 1; // inside the multi-byte character+ const chunks = [+ bytes.subarray(0, cut),+ bytes.subarray(cut, cut + 40),+ bytes.subarray(cut + 40),+ ];+ const transform = new ResponsesNullArrayRepairTransform();+ const out: Buffer[] = [];+ const ended = new Promise<void>((resolve) => transform.on("end", resolve));+ transform.on("data", (chunk: Buffer) => out.push(chunk));+ for (const chunk of chunks) transform.write(chunk);+ transform.end();+ await ended;+ const frames = Buffer.concat(out)+ .toString("utf8")+ .split("\n\n")+ .filter(Boolean);+ expect(+ (+ JSON.parse(frames[0]!.slice(6)) as {+ item: { status: string; content: unknown };+ }+ ).item,+ ).toMatchObject({+ status: "进行中",+ content: [],+ });+ expect(frames[1]).toBe(`data: ${TEXT_DELTA}`);+ });++ it("splits frames on every legal SSE boundary, including mixed LF/CRLF, and keeps each delimiter", async () => {+ const input = `data: ${REASONING_ADDED_NULL}\n\r\ndata: ${MESSAGE_ADDED_NULL}\r\n\ndata: ${TEXT_DELTA}\r\n\r\ndata: [DONE]\n\n`;+ const output = await pump(new ResponsesNullArrayRepairTransform(), [input]);+ const frames = output.split(/\r?\n\r?\n/).filter(Boolean);+ expect(frames).toHaveLength(4);+ expect(+ (JSON.parse(frames[0]!.slice(6)) as { item: { summary: unknown } }).item+ .summary,+ ).toEqual([]);+ expect(+ (JSON.parse(frames[1]!.slice(6)) as { item: { content: unknown } }).item+ .content,+ ).toEqual([]);+ expect(frames[2]).toBe(`data: ${TEXT_DELTA}`);+ expect(frames[3]).toBe("data: [DONE]");+ expect(output.match(/\r?\n\r?\n/g)).toEqual([+ "\n\r\n",+ "\r\n\n",+ "\r\n\r\n",+ "\n\n",+ ]);+ });++ it("re-emits a mixed-newline stream byte for byte when nothing needs repair", async () => {+ const input = `data: ${TEXT_DELTA}\n\r\n: ping\r\n\ndata: ${TEXT_DELTA}\r\n\r\ndata: [DONE]\n\n`;+ expect(await pump(new ResponsesNullArrayRepairTransform(), [input])).toBe(+ input,+ );+ });++ it("does not treat a CR split across chunks as a boundary too early", async () => {+ const whole = `data: ${MESSAGE_ADDED_NULL}\r\n\r\ndata: ${TEXT_DELTA}\n\n`;+ const cut = whole.indexOf("\r\n\r\n") + 3; // pending ends with "\r\n\r"+ const output = await pump(new ResponsesNullArrayRepairTransform(), [+ whole.slice(0, cut),+ whole.slice(cut),+ ]);+ const frames = output.split(/\r?\n\r?\n/).filter(Boolean);+ expect(frames).toHaveLength(2);+ expect(+ (JSON.parse(frames[0]!.slice(6)) as { item: { content: unknown } }).item+ .content,+ ).toEqual([]);+ expect(frames[1]).toBe(`data: ${TEXT_DELTA}`);+ });++ it("repairs a trailing frame without a delimiter at end of stream", async () => {+ const output = await pump(new ResponsesNullArrayRepairTransform(), [+ `data: ${REASONING_ADDED_NULL}`,+ ]);+ expect(+ (JSON.parse(output.slice(6)) as { item: { summary: unknown } }).item+ .summary,+ ).toEqual([]);+ expect(output.endsWith("\n")).toBe(false);+ });+});++describe("createResponsesNullArrayRepairTransform", () => {+ it("only wraps uncompressed SSE responses", () => {+ expect(+ createResponsesNullArrayRepairTransform({+ contentType: "text/event-stream; charset=utf-8",+ contentEncoding: "",+ }),+ ).toBeInstanceOf(ResponsesNullArrayRepairTransform);+ expect(+ createResponsesNullArrayRepairTransform({+ contentType: "Text/Event-Stream",+ contentEncoding: "identity",+ }),+ ).toBeInstanceOf(ResponsesNullArrayRepairTransform);+ expect(+ createResponsesNullArrayRepairTransform({+ contentType: "application/json",+ contentEncoding: "",+ }),+ ).toBeNull();+ expect(+ createResponsesNullArrayRepairTransform({+ contentType: "text/event-stream",+ contentEncoding: "gzip",+ }),+ ).toBeNull();+ expect(+ createResponsesNullArrayRepairTransform({+ contentType: "",+ contentEncoding: "",+ }),+ ).toBeNull();+ });+});++describe("chainResponseTransforms", () => {+ const upper = () =>+ new Transform({+ transform(chunk: Buffer, _encoding, callback) {+ callback(+ null,+ Buffer.from(chunk.toString("utf8").toUpperCase(), "utf8"),+ );+ },+ });+ const suffix = (text: string) =>+ new Transform({+ transform(chunk: Buffer, _encoding, callback) {+ callback(null, chunk);+ },+ flush(callback) {+ callback(null, Buffer.from(text, "utf8"));+ },+ });++ it("returns null for no stages and the stage itself for a single stage", () => {+ expect(chainResponseTransforms()).toBeNull();+ expect(chainResponseTransforms(null, undefined)).toBeNull();+ const only = upper();+ expect(chainResponseTransforms(null, only)).toBe(only);+ });++ it("runs stages in order and ends after the last stage flushes", async () => {+ const chained = chainResponseTransforms(upper(), null, suffix("!"));+ expect(chained).not.toBeNull();+ expect(await pump(chained!, ["ab", "c"])).toBe("ABC!");+ });++ it("feeds repaired frames into a downstream stage", async () => {+ const seen: string[] = [];+ const observer = new Transform({+ transform(chunk: Buffer, _encoding, callback) {+ seen.push(chunk.toString("utf8"));+ callback(null, chunk);+ },+ });+ const chained = chainResponseTransforms(+ new ResponsesNullArrayRepairTransform(),+ observer,+ )!;+ await pump(chained, [`data: ${MESSAGE_ADDED_NULL}\n\n`]);+ expect(seen.join("")).toContain('"content":[]');+ });++ it("pauses the inner stages while the consumer is not reading and resumes on demand", async () => {+ const tail = new PassThrough();+ const chained = chainResponseTransforms(new PassThrough(), tail)!;+ const chunk = Buffer.alloc(8 * 1024, 0x61);+ // Write far more than the readable high-water mark with nobody consuming.+ for (let index = 0; index < 32; index += 1) chained.write(chunk);+ await new Promise((resolve) => setImmediate(resolve));+ expect(tail.isPaused()).toBe(true);+ expect(chained.readableLength).toBeLessThanOrEqual(+ chained.readableHighWaterMark + chunk.length,+ );+ // Consuming drains the outer buffer, resumes the tail and lets the rest through.+ let received = 0;+ const ended = new Promise<void>((resolve) => chained.on("end", resolve));+ chained.on("data", (data: Buffer) => {+ received += data.length;+ });+ chained.end();+ await ended;+ expect(received).toBe(32 * chunk.length);+ expect(tail.isPaused()).toBe(false);+ });++ it("fails the chain when any stage errors", async () => {+ const failing = new Transform({+ transform(_chunk, _encoding, callback) {+ callback(new Error("stage failed"));+ },+ });+ const chained = chainResponseTransforms(new PassThrough(), failing)!;+ const errored = new Promise<Error>((resolve) =>+ chained.on("error", resolve),+ );+ chained.write("x");+ expect((await errored).message).toBe("stage failed");+ });+});diff --git a/packages/responses-chat-bridge/src/index.ts b/packages/responses-chat-bridge/src/index.tsindex aaab95a60a..b6eb6c1a5f 100644--- a/packages/responses-chat-bridge/src/index.ts+++ b/packages/responses-chat-bridge/src/index.ts@@ -20,6 +20,13 @@ export {normalizeResponsesToolItemIds,type ResponsesCustomToolFunctionAdapter,} from './custom-tool-function-adapter.js';+export {+ chainResponseTransforms,+ createResponsesNullArrayRepairTransform,+ repairResponsesEventNullArrays,+ repairResponsesItemNullArrays,+ ResponsesNullArrayRepairTransform,+} from './responses-null-array-repair.js';export {isResponsesImageContentPartType,isUnsupportedResponsesImageErrorPayload,diff --git a/packages/responses-chat-bridge/src/responses-null-array-repair.ts b/packages/responses-chat-bridge/src/responses-null-array-repair.tsnew file mode 100644index 0000000000..47687f4b92--- /dev/null+++ b/packages/responses-chat-bridge/src/responses-null-array-repair.ts@@ -0,0 +1,245 @@+import { Transform, type TransformCallback } from "node:stream";++/**+ * Repairs Responses output items whose required array fields were serialized as `null`.+ *+ * Some third-party models proxied through a Responses passthrough emit+ * `response.output_item.added` items such as `{ type: 'reasoning', summary: null }` or+ * `{ type: 'message', content: null }`. Codex's `ResponseItem` parser tolerates missing ids and+ * unknown fields but requires these arrays, so the item is dropped and every following+ * `output_text.delta` is discarded as "without active item" (#4251). The wire contract says+ * these fields are arrays, so the only semantics-preserving repair is `null -> []`.+ *+ * Nothing else is touched: item types, ids, call ids and unknown fields pass through byte for+ * byte, and frames that need no repair are re-emitted exactly as received.+ */++interface JsonObject {+ [key: string]: unknown;+}++function isObject(value: unknown): value is JsonObject {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/** Array fields Codex requires per item type. `reasoning.content` is optional and stays as is. */+const REQUIRED_ARRAY_FIELDS: Readonly<Record<string, readonly string[]>> = {+ reasoning: ["summary"],+ message: ["content"],+};++/** Returns the repaired item, or null when the item needs no repair. */+export function repairResponsesItemNullArrays(+ item: unknown,+): JsonObject | null {+ if (!isObject(item) || typeof item.type !== "string") return null;+ const fields = REQUIRED_ARRAY_FIELDS[item.type];+ if (!fields) return null;+ let next: JsonObject | null = null;+ for (const field of fields) {+ if (item[field] !== null) continue;+ next ??= { ...item };+ next[field] = [];+ }+ return next;+}++function repairOutputList(output: unknown): unknown[] | null {+ if (!Array.isArray(output)) return null;+ let changed = false;+ const next = output.map((item) => {+ const repaired = repairResponsesItemNullArrays(item);+ if (!repaired) return item;+ changed = true;+ return repaired;+ });+ return changed ? next : null;+}++/**+ * Returns the repaired Responses SSE event, or null when the event needs no repair.+ *+ * Covers `response.output_item.added` / `response.output_item.done` (`event.item`) and every+ * event carrying a full `response.output` array (`response.completed`, `response.incomplete`,+ * non-streaming bodies wrapped by the caller).+ */+export function repairResponsesEventNullArrays(+ event: unknown,+): JsonObject | null {+ if (!isObject(event) || typeof event.type !== "string") return null;+ if (+ event.type === "response.output_item.added" ||+ event.type === "response.output_item.done"+ ) {+ const item = repairResponsesItemNullArrays(event.item);+ return item ? { ...event, item } : null;+ }+ if (isObject(event.response)) {+ const output = repairOutputList(event.response.output);+ return output+ ? { ...event, response: { ...event.response, output } }+ : null;+ }+ return null;+}++/**+ * A single SSE frame is never larger than a few KiB in practice; a frame that grows past this+ * bound without a delimiter is forwarded verbatim instead of being buffered forever. Failing+ * open here is deliberate: this transform only repairs, it must never turn a working stream+ * into a proxy error.+ */+const MAX_PENDING_FRAME_BYTES = 16 * 1024 * 1024;++/** One SSE event boundary: a line break (LF or CRLF) followed by an empty line. */+const FRAME_BOUNDARY = /\r?\n\r?\n/;++/** SSE frame rewriter; frames that need no repair are re-emitted byte for byte. */+export class ResponsesNullArrayRepairTransform extends Transform {+ private readonly decoder = new TextDecoder();+ private pending = "";++ private rewriteFrame(frame: string, delimiter: string): string {+ const lines = frame.split(/\r?\n/);+ const data = lines+ .filter((line) => line.startsWith("data:"))+ .map((line) => line.slice(5).trimStart())+ .join("\n");+ if (!data || data === "[DONE]") return frame + delimiter;+ let event: unknown;+ try {+ event = JSON.parse(data);+ } catch {+ return frame + delimiter;+ }+ const repaired = repairResponsesEventNullArrays(event);+ if (!repaired) return frame + delimiter;+ const eventLine = lines.find((line) => line.startsWith("event:"));+ return `${eventLine ? `${eventLine}\n` : ""}data: ${JSON.stringify(repaired)}${delimiter}`;+ }++ private drainFrames(): void {+ // SSE ends a line with LF or CRLF and an event with a blank line, so the four+ // boundaries `\n\n`, `\r\n\r\n`, `\n\r\n` and `\r\n\n` are all legal and may be+ // mixed by one upstream (same convention as the proxy's own frame reader).+ // The matched delimiter is re-emitted verbatim.+ for (;;) {+ const match = FRAME_BOUNDARY.exec(this.pending);+ if (!match) return;+ const delimiter = match[0];+ this.push(+ this.rewriteFrame(this.pending.slice(0, match.index), delimiter),+ );+ this.pending = this.pending.slice(match.index + delimiter.length);+ }+ }++ override _transform(+ chunk: Buffer,+ _encoding: string,+ callback: TransformCallback,+ ): void {+ this.pending += this.decoder.decode(chunk, { stream: true });+ this.drainFrames();+ if (Buffer.byteLength(this.pending, "utf8") > MAX_PENDING_FRAME_BYTES) {+ this.push(this.pending);+ this.pending = "";+ }+ callback();+ }++ override _flush(callback: TransformCallback): void {+ this.pending += this.decoder.decode();+ this.drainFrames();+ if (this.pending) this.push(this.rewriteFrame(this.pending, ""));+ this.pending = "";+ callback();+ }+}++/**+ * Builds the repair transform for one upstream response, or null when the body is not a plain+ * (uncompressed) SSE stream. Non-SSE and compressed bodies are left untouched rather than+ * rejected: the repair is best effort and must not change how such responses are delivered.+ */+export function createResponsesNullArrayRepairTransform(response: {+ contentType: string;+ contentEncoding: string;+}): Transform | null {+ const encoding = response.contentEncoding.trim().toLowerCase();+ if (encoding && encoding !== "identity") return null;+ if (+ !response.contentType.trim().toLowerCase().startsWith("text/event-stream")+ )+ return null;+ return new ResponsesNullArrayRepairTransform();+}++/**+ * Chains response transforms into one so a proxy that accepts a single transform can run+ * several. Bytes flow `head -> ... -> tail`; the chained transform ends only after the tail+ * ends, and an error in any stage fails the whole chain. Null stages are skipped.+ */+export function chainResponseTransforms(+ ...stages: Array<Transform | null | undefined>+): Transform | null {+ const present = stages.filter(+ (stage): stage is Transform => stage instanceof Transform,+ );+ if (present.length === 0) return null;+ if (present.length === 1) return present[0]!;+ return new ChainedTransform(present);+}++class ChainedTransform extends Transform {+ private readonly head: Transform;+ private readonly tail: Transform;+ private readonly stages: readonly Transform[];++ constructor(stages: readonly Transform[]) {+ super();+ this.stages = stages;+ this.head = stages[0]!;+ this.tail = stages[stages.length - 1]!;+ for (let index = 0; index < stages.length; index += 1) {+ const stage = stages[index]!;+ stage.on("error", (error: Error) => this.destroy(error));+ const next = stages[index + 1];+ if (next) stage.pipe(next);+ }+ // Readable-side backpressure: when the consumer stops reading, stop pulling+ // from the tail (pipe then throttles every earlier stage) until `_read` runs.+ this.tail.on("data", (chunk: Buffer) => {+ if (!this.push(chunk)) this.tail.pause();+ });+ }++ override _read(size: number): void {+ if (this.tail.isPaused()) this.tail.resume();+ super._read(size);+ }++ override _transform(+ chunk: Buffer,+ _encoding: string,+ callback: TransformCallback,+ ): void {+ if (this.head.write(chunk)) callback();+ else this.head.once("drain", () => callback());+ }++ override _flush(callback: TransformCallback): void {+ this.tail.once("end", () => callback());+ this.head.end();+ }++ override _destroy(+ error: Error | null,+ callback: (error: Error | null) => void,+ ): void {+ for (const stage of this.stages) {+ if (!stage.destroyed) stage.destroy();+ }+ callback(error);+ }+}