Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(model-compat): 补齐 Responses added 事件缺失的初始化字段 (#4511)

FicoWangab0a5bbe164e
diff --git a/packages/model-compat/README.md b/packages/model-compat/README.md
index d30b3aa69c..e2cecc1a1e 100644
--- a/packages/model-compat/README.md
+++ b/packages/model-compat/README.md
@@ -53,6 +53,16 @@ implementations. Protocol bridges remain bridges; they are not replaced with Ope
configuration files, or account manager. Cindy's collision-safe `exec` conversion is retained ahead
of upstream's generic conversion, with reverse transforms applied in reverse order.
+## Responses initial item repair
+
+The existing uncompressed SSE passthrough repair also fills absent initialization fields on
+`response.output_item.added`: reasoning `summary` / message `content` become empty arrays,
+message `output_text.text` and function/custom tool argument buffers become empty strings.
+Later deltas still carry the actual content. Existing values, types, IDs and call IDs are retained.
+Missing fields on terminal items are not filled, and no `done` events or tool calls are invented.
+This addresses item registration failures from #4509, not the separate missing-terminal-event,
+wrong-tool-type or upstream multi-turn 502 failures. Existing null-array repairs remain unchanged.
+
## Imported provider policy
`src/upstream-profiles.json` contains compatibility declarations extracted statically from all
@@ -134,3 +144,7 @@ Run package conformance tests and all affected bridge/host tests, package typech
repository's `pnpm test:unit:related` gate before delivery. Original Bun tests are transpiled to
JavaScript with only their runner/import paths changed; their assertions are retained. Live-account
checks are separate and must be reported separately from deterministic request/stream tests.
+
+When a frame requires repair, only its data payload is rewritten. SSE event IDs, retry hints,
+comments, extension fields and original line endings are retained; subsequent data lines
+remain empty (trailing JSON whitespace). Frames requiring no repair remain byte-identical.
diff --git a/packages/model-compat/src/cindy/responses-null-array-repair.ts b/packages/model-compat/src/cindy/responses-null-array-repair.ts
index 47687f4b92..fc7d6c5b4d 100644
--- a/packages/model-compat/src/cindy/responses-null-array-repair.ts
+++ b/packages/model-compat/src/cindy/responses-null-array-repair.ts
@@ -10,7 +10,9 @@ import { Transform, type TransformCallback } from "node:stream";
* `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
+ * Added events also initialize absent summary/content arrays, output_text.text, and
+ * function/custom tool argument buffers (#4509). Terminal missing fields are never invented.
+ * 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.
*/
@@ -44,6 +46,40 @@ export function repairResponsesItemNullArrays(
return next;
}
+/** Only added items may initialize missing fields before later deltas populate them.
+ * Never apply this to terminal items: empty tool arguments there could execute a
+ * different command, and empty text could hide missing upstream output.
+ */
+function repairAddedItem(item: unknown): JsonObject | null {
+ if (!isObject(item) || typeof item.type !== "string") return null;
+ let next = repairResponsesItemNullArrays(item);
+ for (const field of REQUIRED_ARRAY_FIELDS[item.type] ?? []) {
+ if (item[field] === undefined) {
+ next ??= { ...item };
+ next[field] = [];
+ }
+ }
+ const field = item.type === "function_call" ? "arguments"
+ : item.type === "custom_tool_call" ? "input" : null;
+ if (field && item[field] === undefined) {
+ next ??= { ...item };
+ next[field] = "";
+ }
+ if (item.type === "message" && Array.isArray(item.content)) {
+ let changed = false;
+ const content = item.content.map((part: unknown) => {
+ if (!isObject(part) || part.type !== "output_text" || part.text !== undefined) return part;
+ changed = true;
+ return { ...part, text: "" };
+ });
+ if (changed) {
+ next ??= { ...item };
+ next.content = content;
+ }
+ }
+ return next;
+}
+
function repairOutputList(output: unknown): unknown[] | null {
if (!Array.isArray(output)) return null;
let changed = false;
@@ -71,7 +107,9 @@ export function repairResponsesEventNullArrays(
event.type === "response.output_item.added" ||
event.type === "response.output_item.done"
) {
- const item = repairResponsesItemNullArrays(event.item);
+ const item = event.type === "response.output_item.added"
+ ? repairAddedItem(event.item)
+ : repairResponsesItemNullArrays(event.item);
return item ? { ...event, item } : null;
}
if (isObject(event.response)) {
@@ -114,8 +152,14 @@ export class ResponsesNullArrayRepairTransform extends Transform {
}
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}`;
+ let firstData = true;
+ // Preserve id/retry/comments/extension lines and their original line endings.
+ // Empty later data lines add only trailing JSON whitespace to the SSE data.
+ return frame.replace(/^data:[^\r\n]*/gm, () => {
+ if (!firstData) return "data:";
+ firstData = false;
+ return `data: ${JSON.stringify(repaired)}`;
+ }) + delimiter;
}
private drainFrames(): void {
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.ts
index f5be51356a..3a01f9b45b 100644
--- 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.ts
@@ -238,7 +238,7 @@ describe("ResponsesNullArrayRepairTransform", () => {
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(
+ expect(output.startsWith("event: response.output_item.added\r\ndata: ")).toBe(
true,
);
expect(output.endsWith("\r\n\r\n")).toBe(true);
@@ -467,3 +467,61 @@ describe("chainResponseTransforms", () => {
expect((await errored).message).toBe("stage failed");
});
});
+
+
+describe("missing initialization fields (#4509)", () => {
+ it.each([
+ [{ type: "reasoning", id: "rs_1" }, { type: "reasoning", id: "rs_1", summary: [] }],
+ [{ type: "message", id: "msg_2", role: "assistant" }, { type: "message", id: "msg_2", role: "assistant", content: [] }],
+ [{ type: "message", content: [{ type: "output_text", annotations: [] }] }, { type: "message", content: [{ type: "output_text", annotations: [], text: "" }] }],
+ [{ type: "function_call", name: "exec", call_id: "c1" }, { type: "function_call", name: "exec", call_id: "c1", arguments: "" }],
+ [{ type: "custom_tool_call", name: "exec", call_id: "c2" }, { type: "custom_tool_call", name: "exec", call_id: "c2", input: "" }],
+ ])("initializes added item %j without changing its identity/type", (item, expected) => {
+ const event = { type: "response.output_item.added", output_index: 0, item };
+ expect(repairResponsesEventNullArrays(event)).toEqual({ ...event, item: expected });
+ expect(event.item).toEqual(item);
+ });
+
+ it("does not invent final content/arguments or modify malformed values", () => {
+ for (const item of [
+ { type: "function_call", name: "exec", call_id: "c1" },
+ { type: "custom_tool_call", name: "exec", call_id: "c2" },
+ { type: "message", content: [{ type: "output_text" }] },
+ { type: "reasoning" },
+ ]) {
+ expect(repairResponsesEventNullArrays({ type: "response.output_item.done", item })).toBeNull();
+ expect(repairResponsesEventNullArrays({ type: "response.completed", response: { output: [item] } })).toBeNull();
+ }
+ for (const item of [
+ { type: "function_call", arguments: null },
+ { type: "function_call", arguments: 42 },
+ { type: "custom_tool_call", input: { unsafe: true } },
+ { type: "message", content: [{ type: "output_text", text: null }, { type: "image", data: "x" }] },
+ { type: "unknown_tool" },
+ ]) expect(repairResponsesEventNullArrays({ type: "response.output_item.added", item })).toBeNull();
+ });
+
+ it("preserves deltas and done frames byte for byte in the issue's split SSE sequence", async () => {
+ const added = { type: "response.output_item.added", output_index: 0,
+ item: { id: "msg_1", type: "message", status: "in_progress", role: "assistant", content: [{ type: "output_text" }] } };
+ const frame = (event: unknown) => `data: ${JSON.stringify(event)}\n\n`;
+ const rest = frame({ type: "response.output_text.delta", item_id: "msg_1", output_index: 0, delta: "HELLO" })
+ + frame({ type: "response.output_text.delta", item_id: "msg_1", output_index: 0, delta: " WORLD" })
+ + frame({ type: "response.output_item.done", output_index: 0, item: { ...added.item, status: "completed" } });
+ const wire = frame(added) + rest;
+ const result = await pump(new ResponsesNullArrayRepairTransform(), [wire.slice(0, 37), wire.slice(37)]);
+ expect(result).toBe(frame({ ...added, item: { ...added.item, content: [{ type: "output_text", text: "" }] } }) + rest);
+ });
+});
+
+
+it.each(["\n", "\r\n"])("preserves SSE metadata and line endings when repairing multiline data (%j)", async newline => {
+ const prefix = [": keepalive", "id: evt-123", "retry: 1500", "event: response.output_item.added", "x-vendor: keep"].join(newline) + newline;
+ const item = { type: "message", content: [{ type: "output_text" }] };
+ const event = { type: "response.output_item.added", item };
+ const wire = prefix + 'data: {"type":"response.output_item.added",' + newline
+ + ": between data lines" + newline + `data: "item":${JSON.stringify(item)}}` + newline + newline;
+ const repaired = { ...event, item: { ...item, content: [{ type: "output_text", text: "" }] } };
+ expect(await pump(new ResponsesNullArrayRepairTransform(), [wire])).toBe(prefix
+ + `data: ${JSON.stringify(repaired)}` + newline + ": between data lines" + newline + "data:" + newline + newline);
+});