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(sse): make Responses passthrough robust for size-sensitive clients (#1580)
vanminhphe64dc3b4316d
diff --git a/open-sse/utils/stream.ts b/open-sse/utils/stream.tsindex ee4c7d5576..7d8c524353 100644--- a/open-sse/utils/stream.ts+++ b/open-sse/utils/stream.ts@@ -282,6 +282,80 @@ const STREAM_MODE = {PASSTHROUGH: "passthrough", // No translation, normalize output, extract usage};+/**+ * Lifecycle event types in OpenAI Responses API streams whose `response`+ * payload is a snapshot of the request (echoes back `instructions` + `tools`).+ */+const RESPONSES_LIFECYCLE_EVENT_TYPES = new Set([+ "response.created",+ "response.in_progress",+ "response.completed",+]);++/**+ * Backfill `parsed.response.output` on a `response.completed` event from the+ * snapshots accumulated as the stream progressed (`response.output_item.done`).+ *+ * Why: when the upstream request runs with `store: false`, OpenAI's Responses+ * API leaves `response.output` empty in the final `response.completed`+ * snapshot — clients that rebuild assistant messages from that snapshot+ * (notably the GitHub Copilot CLI 1.0.36) end up with `choices: []` and never+ * trigger tool execution. Codex CLI and others that consume per-item events+ * are unaffected; backfilling the array makes both styles work.+ *+ * Returns true when `parsed.response.output` was empty and got replaced, so+ * the caller can re-serialize.+ */+export function backfillResponsesCompletedOutput(+ parsed: unknown,+ collectedItems: readonly unknown[]+): boolean {+ if (!collectedItems.length) return false;+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;+ const obj = parsed as Record<string, unknown>;+ if (obj.type !== "response.completed") return false;+ const resp = obj.response;+ if (!resp || typeof resp !== "object" || Array.isArray(resp)) return false;+ const r = resp as Record<string, unknown>;+ const existing = r.output;+ if (Array.isArray(existing) && existing.length > 0) return false;+ r.output = collectedItems.slice();+ return true;+}++/**+ * Strip the request echo (`instructions`, `tools`) from `parsed.response`+ * on Responses API lifecycle events.+ *+ * Why: those fields can balloon the SSE message past 100 KB when the request+ * carries large tool definitions / instructions. Some clients (notably the+ * GitHub Copilot CLI) cannot process oversized SSE events and stop rendering+ * mid-stream. The fields are pure echo of the original request — clients+ * already hold the original locally — so removing them is observably safe.+ *+ * Returns true when the payload was modified and must be re-serialized.+ */+export function stripResponsesLifecycleEcho(parsed: unknown): boolean {+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;+ const obj = parsed as Record<string, unknown>;+ if (typeof obj.type !== "string" || !RESPONSES_LIFECYCLE_EVENT_TYPES.has(obj.type)) {+ return false;+ }+ const resp = obj.response;+ if (!resp || typeof resp !== "object" || Array.isArray(resp)) return false;+ const r = resp as Record<string, unknown>;+ let changed = false;+ if ("instructions" in r) {+ delete r.instructions;+ changed = true;+ }+ if ("tools" in r) {+ delete r.tools;+ changed = true;+ }+ return changed;+}+/*** Create unified SSE transform stream with idle timeout protection.* If the upstream provider stops sending data for STREAM_IDLE_TIMEOUT_MS,@@ -339,6 +413,10 @@ export function createSSEStream(options: StreamOptions = {}) {// Passthrough: accumulate content and reasoning separately for call log response bodylet passthroughAccumulatedContent = "";let passthroughAccumulatedReasoning = "";+ // Passthrough Responses SSE: snapshots of items seen via `response.output_item.done`,+ // used to backfill `response.completed.response.output` when upstream returns it+ // empty (which happens when `store: false` — see backfillResponsesCompletedOutput).+ const passthroughResponsesOutputItems: unknown[] = [];const streamStartedAt = Date.now();// Guard against duplicate [DONE] events — ensures exactly one per stream@@ -635,6 +713,29 @@ export function createSSEStream(options: StreamOptions = {}) {totalContentLength += parsed.delta.length;passthroughAccumulatedContent += parsed.delta;}+ // Capture each completed output item so the final+ // response.completed snapshot can be backfilled when upstream+ // returns an empty `output` (happens with store: false).+ if (parsed.type === "response.output_item.done" && parsed.item) {+ passthroughResponsesOutputItems.push(parsed.item);+ }+ // Two transport-level fixes for Responses passthrough:+ // 1) Strip echoed `instructions` + `tools` from lifecycle+ // events — they can balloon a single SSE event past+ // 100 KB and break parsers (e.g. GitHub Copilot CLI).+ // 2) Backfill `response.completed.response.output` when+ // upstream sent it empty (store: false) — some clients+ // build their tool-call list from that snapshot rather+ // than from per-item events.+ const stripped = stripResponsesLifecycleEcho(parsed);+ const backfilled = backfillResponsesCompletedOutput(+ parsed,+ passthroughResponsesOutputItems+ );+ if (stripped || backfilled) {+ output = `data: ${JSON.stringify(parsed)}\n`;+ injectedUsage = true;+ }} else if (isClaudeSSE) {// Claude SSE: extract usage, track content, forward as-isconst extracted = extractUsage(parsed);diff --git a/tests/unit/stream-strip-responses-lifecycle-echo.test.ts b/tests/unit/stream-strip-responses-lifecycle-echo.test.tsnew file mode 100644index 0000000000..3fb778f21f--- /dev/null+++ b/tests/unit/stream-strip-responses-lifecycle-echo.test.ts@@ -0,0 +1,233 @@+import { describe, it } from "node:test";+import assert from "node:assert/strict";++import {+ backfillResponsesCompletedOutput,+ stripResponsesLifecycleEcho,+} from "../../open-sse/utils/stream.ts";++describe("stripResponsesLifecycleEcho", () => {+ it("strips instructions + tools from response.created", () => {+ const event = {+ type: "response.created",+ response: {+ id: "resp_1",+ status: "in_progress",+ instructions: "very long system prompt".repeat(2000),+ tools: [{ type: "function", name: "view" }],+ model: "gpt-5.4",+ },+ };++ const changed = stripResponsesLifecycleEcho(event);++ assert.equal(changed, true);+ assert.equal("instructions" in event.response, false);+ assert.equal("tools" in event.response, false);+ // Other fields untouched+ assert.equal(event.response.id, "resp_1");+ assert.equal(event.response.status, "in_progress");+ assert.equal(event.response.model, "gpt-5.4");+ });++ it("strips fields from response.in_progress", () => {+ const event = {+ type: "response.in_progress",+ response: { instructions: "x", tools: [] },+ };+ assert.equal(stripResponsesLifecycleEcho(event), true);+ assert.deepEqual(event.response, {});+ });++ it("strips fields from response.completed (preserving usage)", () => {+ const event = {+ type: "response.completed",+ response: {+ id: "resp_2",+ status: "completed",+ instructions: "system prompt",+ tools: [{ name: "bash" }],+ usage: { input_tokens: 100, output_tokens: 50, total_tokens: 150 },+ },+ };++ const changed = stripResponsesLifecycleEcho(event);++ assert.equal(changed, true);+ assert.equal("instructions" in event.response, false);+ assert.equal("tools" in event.response, false);+ // Usage must survive — downstream tracking depends on it.+ assert.deepEqual(event.response.usage, {+ input_tokens: 100,+ output_tokens: 50,+ total_tokens: 150,+ });+ });++ it("returns false (no-op) when neither field is present", () => {+ const event = {+ type: "response.completed",+ response: { id: "resp_3", status: "completed" },+ };+ const before = JSON.stringify(event);+ assert.equal(stripResponsesLifecycleEcho(event), false);+ assert.equal(JSON.stringify(event), before);+ });++ it("strips only the field that exists", () => {+ const onlyTools = {+ type: "response.created",+ response: { tools: [{ name: "view" }] },+ };+ assert.equal(stripResponsesLifecycleEcho(onlyTools), true);+ assert.equal("tools" in onlyTools.response, false);++ const onlyInstr = {+ type: "response.created",+ response: { instructions: "hi" },+ };+ assert.equal(stripResponsesLifecycleEcho(onlyInstr), true);+ assert.equal("instructions" in onlyInstr.response, false);+ });++ it("does NOT touch incremental events", () => {+ const cases = [+ {+ type: "response.output_item.added",+ item: { type: "function_call", name: "view" },+ },+ {+ type: "response.function_call_arguments.delta",+ delta: '{"path":"/x"}',+ },+ {+ type: "response.output_text.delta",+ delta: "hello",+ },+ {+ type: "response.reasoning_summary_text.delta",+ delta: "thinking",+ },+ ];+ for (const event of cases) {+ const before = JSON.stringify(event);+ assert.equal(stripResponsesLifecycleEcho(event), false, `should ignore ${event.type}`);+ assert.equal(JSON.stringify(event), before, `should not mutate ${event.type}`);+ }+ });++ it("returns false for malformed payloads", () => {+ assert.equal(stripResponsesLifecycleEcho(null), false);+ assert.equal(stripResponsesLifecycleEcho(undefined), false);+ assert.equal(stripResponsesLifecycleEcho("string"), false);+ assert.equal(stripResponsesLifecycleEcho(42), false);+ assert.equal(stripResponsesLifecycleEcho([]), false);+ assert.equal(stripResponsesLifecycleEcho({ type: "response.created" }), false);+ assert.equal(stripResponsesLifecycleEcho({ type: "response.created", response: null }), false);+ assert.equal(stripResponsesLifecycleEcho({ type: "response.created", response: "x" }), false);+ assert.equal(stripResponsesLifecycleEcho({ type: "response.created", response: [] }), false);+ });++ it("ignores Chat Completions chunks", () => {+ const event = {+ choices: [{ delta: { content: "hi" }, index: 0 }],+ object: "chat.completion.chunk",+ };+ assert.equal(stripResponsesLifecycleEcho(event), false);+ });+});++describe("backfillResponsesCompletedOutput", () => {+ const items = [+ { id: "rs_1", type: "reasoning" },+ {+ id: "fc_1",+ type: "function_call",+ name: "view",+ call_id: "call_abc",+ arguments: '{"path":"/x"}',+ },+ ];++ it("backfills output when response.completed.response.output is empty", () => {+ const event = {+ type: "response.completed",+ response: { id: "resp_1", status: "completed", output: [], usage: { input_tokens: 1 } },+ };+ const changed = backfillResponsesCompletedOutput(event, items);+ assert.equal(changed, true);+ assert.deepEqual(event.response.output, items);+ // Other fields untouched+ assert.equal(event.response.id, "resp_1");+ assert.deepEqual(event.response.usage, { input_tokens: 1 });+ });++ it("backfills when output is missing entirely", () => {+ const event = {+ type: "response.completed",+ response: { id: "resp_2" },+ } as { type: string; response: { id: string; output?: unknown[] } };+ const changed = backfillResponsesCompletedOutput(event, items);+ assert.equal(changed, true);+ assert.deepEqual(event.response.output, items);+ });++ it("does NOT overwrite an already-populated output array", () => {+ const upstream = [{ id: "fc_x", type: "function_call", name: "bash" }];+ const event = {+ type: "response.completed",+ response: { id: "resp_3", output: upstream },+ };+ const changed = backfillResponsesCompletedOutput(event, items);+ assert.equal(changed, false);+ assert.deepEqual(event.response.output, upstream);+ });++ it("returns false when no items have been collected", () => {+ const event = {+ type: "response.completed",+ response: { id: "resp_4", output: [] },+ };+ const changed = backfillResponsesCompletedOutput(event, []);+ assert.equal(changed, false);+ assert.deepEqual(event.response.output, []);+ });++ it("ignores non-completed events", () => {+ for (const type of [+ "response.created",+ "response.in_progress",+ "response.output_item.added",+ "response.output_item.done",+ "response.function_call_arguments.delta",+ ]) {+ const event = { type, response: { output: [] } };+ const changed = backfillResponsesCompletedOutput(event, items);+ assert.equal(changed, false, `should ignore ${type}`);+ }+ });++ it("returns false on malformed payloads", () => {+ assert.equal(backfillResponsesCompletedOutput(null, items), false);+ assert.equal(backfillResponsesCompletedOutput(undefined, items), false);+ assert.equal(backfillResponsesCompletedOutput("string", items), false);+ assert.equal(backfillResponsesCompletedOutput([], items), false);+ assert.equal(backfillResponsesCompletedOutput({ type: "response.completed" }, items), false);+ assert.equal(+ backfillResponsesCompletedOutput({ type: "response.completed", response: null }, items),+ false+ );+ assert.equal(+ backfillResponsesCompletedOutput({ type: "response.completed", response: [] }, items),+ false+ );+ });++ it("clones the items array (callers can keep mutating their buffer)", () => {+ const buf: unknown[] = [{ id: "fc_a", type: "function_call" }];+ const event = { type: "response.completed", response: { output: [] } };+ backfillResponsesCompletedOutput(event, buf);+ buf.push({ id: "fc_b", type: "function_call" });+ assert.equal((event.response.output as unknown[]).length, 1);+ });+});