Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
refactor(adapters): split Responses parsing into leg and turn modules
Jack Rudenko62e9d6b634ca
diff --git a/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.ts b/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.tsindex 181a8b78..bc659a13 100644--- a/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.ts@@ -1,31 +1,19 @@/**- * OpenAI Responses API SSE → Claude SSE stream parser.+ * OpenAI Responses API SSE → Claude SSE stream parser (module entry point).** Handles Codex models that use /v1/responses instead of /v1/chat/completions.- * The Responses API has different event types:- * response.output_text.delta → content text- * response.output_item.added → new item (function_call, reasoning)- * response.function_call_arguments.delta → tool argument streaming- * response.reasoning_summary_text.delta / reasoning_text.delta → thinking output- * response.output_item.done → close tool_use block- * response.completed / response.done → final usage+ * The work is split in three, under `responses/`:+ * - `claude-sse-sink.ts`: the one writer of Claude SSE for one downstream+ * message (lifecycle, block index, ping, tool block states, disconnect);+ * - `responses-leg.ts`: one upstream body → Claude SSE events → LegOutcome;+ * - `responses-turn.ts`: how the message ends, and the usage callback.+ * `composed-handler.ts` imports only this file.*/import type { Context } from "hono";-import {- type CachedReasoningItem,- rememberReasoningForCall,-} from "../../../adapters/reasoning-cache.js";-import { getLogLevel, log } from "../../../logger.js";import { wrapAnthropicError } from "../anthropic-error.js";-import { messageStartUsage } from "./message-start-usage.js";-import { formatRawSseLogPayload } from "./openai-sse.js";-import {- type ParallelWrapperCall,- isParallelWrapperName,- parseParallelWrapper,-} from "./responses/parallel-wrapper.js";-import { sseDataPayload } from "./sse-line.js";+import { ClaudeSseSink } from "./responses/claude-sse-sink.js";+import { runResponsesTurn } from "./responses/responses-turn.js";export function createResponsesStreamHandler(c: Context,@@ -58,6 +46,7 @@ export function createResponsesStreamHandler(* the Chat Completions path has had. Previously absent, which left the Codex* models with no observation point at all.*/+ // biome-ignore lint/suspicious/noExplicitAny: MiddlewareManager is untyped on every parsermiddlewareManager?: any;/*** Behavior-layer tool-call interception. Called once per completed tool call@@ -93,788 +82,44 @@ export function createResponsesStreamHandler(declaredToolNames?: string[];}): Response {- const reader = response.body?.getReader();- if (!reader) {+ if (!response.body) {+ // biome-ignore lint/suspicious/noExplicitAny: Hono's typed json response is not a plain Responsereturn c.json(wrapAnthropicError(500, "No response body"), 500) as any;}- const encoder = new TextEncoder();- const decoder = new TextDecoder();-- let buffer = "";- // Monotonic content-block index. Every block (thinking, text, tool_use) takes- // the next index — Claude's SSE contract requires contiguous indices, and a- // block index must never be reused once its block is closed.- let curIdx = 0;- let textIdx = -1;- let reasoningIdx = -1;- // OpenAI splits a reasoning summary into parts (summary_index 0, 1, 2, …),- // each a bolded section. The paragraph break between parts is structural —- // it is NOT in the text deltas — so tracking the index lets us re-insert it,- // otherwise "**A**" + "**B**" render as one smashed "**A****B**".- let lastSummaryIndex = -1;- // Set when OpenAI reports the response was cut short (response.incomplete).- // Must reach the client as a truthful stop_reason: when the model runs out of- // output budget mid-tool-call, OpenAI still emits the partial arguments, and- // claiming stop_reason "tool_use" tells the client to execute a tool whose- // JSON is truncated.- let incompleteReason: string | null = null;- // Reasoning items seen since the last function call. OpenAI emits them just- // before the call they informed; we hand them to the cache keyed by that call- // so the next request can replay them (see reasoning-cache.ts).- let pendingReasoning: CachedReasoningItem[] = [];- let inputTokens = 0;- let outputTokens = 0;- let hasToolUse = false;- let lastActivity = Date.now();- let pingInterval: ReturnType<typeof setInterval> | null = null;- let isClosed = false;- // Set by cancel() (the client went away) and by a usage-bearing event.- let cancelledByClient = false;- let usageReported = false;-- /**- * Hand the turn's usage to the caller, which fires the request's stats record.- * After a client disconnect it does so only if the upstream had already- * reported usage: what was billed is billed, but a turn cut off before any- * usage arrived has no figure worth recording.- */- const reportTokens = () => {- if (cancelledByClient && !usageReported) {- log("[ResponsesSSE] client disconnected before usage arrived; no token update");- return;- }- opts.onTokenUpdate?.(inputTokens, outputTokens);- };-- type FnCall = {- name: string;- arguments: string;- index: number;- claudeId?: string;- /** Withhold input_json_delta until the call completes so it can be repaired. */- buffered?: boolean;- /**- * Bytes of `arguments` already sent downstream as `input_json_delta`. Zero- * for a buffered call until it completes, and zero for every call of a Codex- * multi-call turn, which streams no argument deltas at all.- */- forwardedBytes: number;- /** `response.function_call_arguments.done`'s complete argument string. */- doneArgs?: string;- };-- /** Shared across every chunk hook in this stream; handed to afterStreamComplete. */- const streamMetadata = new Map<string, any>();-- // Track function calls being streamed. Keyed by BOTH call_id and item_id, so- // the same FnCall object appears under two keys — never derive a count from- // this map's size; use openToolBlocks / hasToolUse instead.- const functionCalls: Map<string, FnCall> = new Map();-- // Tool blocks that have been started but not yet stopped, in emission order.- const openToolBlocks = new Set<FnCall>();-- /**- * A `parallel` wrapper call being accumulated without a content_block_start- * (see responses/parallel-wrapper.ts). Keyed by call_id and item_id, like- * `functionCalls`; removed at its output_item.done.- */- type HeldWrapper = {- claudeBaseId: string;- arguments: string;- doneArgs?: string;- /** The reasoning that led to the wrapper, bound to its first expanded call only. */- reasoning: CachedReasoningItem[];- };- const heldWrappers: Map<string, HeldWrapper> = new Map();- const declaredToolNames: string[] = opts.declaredToolNames ?? [- ...(opts.toolNameMap?.values() ?? []),- ];- const decodeToolName = (name: string) => opts.toolNameMap?.get(name) || name;-- const stream = new ReadableStream({- /*- * The SSE event dispatch below has been far over the complexity limit since- * this parser was written. The rule only started REPORTING a score once this- * fix removed enough nesting for biome to compute one — before that it bailed- * with "too complex to score", which downgrades to a warning. Splitting the- * dispatch means threading ~20 closure variables through a new function: a- * refactor in its own right, not a rider on a stream-truncation fix.- */- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: pre-existing, see above+ let sink: ClaudeSseSink | undefined;+ const stream = new ReadableStream<Uint8Array>({start: async (controller) => {- const send = (event: string, data: any) => {- if (!isClosed) {- controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));- }- };-- // cancel() (downstream disconnect) closes the controller without running any- // of the normal completion paths, so those paths can still reach a close()- // on an already-closed controller — `ERR_INVALID_STATE`. Harmless in itself,- // but it surfaces as a bogus "[ResponsesSSE] Stream error" in the debug log- // that reads like a translation failure. Every close goes through here.- const safeClose = () => {- try {- controller.close();- } catch {- // Already closed by cancel(); nothing left to do.- }- };-- const closeReasoning = () => {- if (reasoningIdx >= 0) {- send("content_block_stop", { type: "content_block_stop", index: reasoningIdx });- reasoningIdx = -1;- }- };- const closeText = () => {- if (textIdx >= 0) {- send("content_block_stop", { type: "content_block_stop", index: textIdx });- textIdx = -1;- }- };- const closeTools = () => {- for (const fnCall of openToolBlocks) {- // A buffered call that never reached output_item.done (truncated or- // failed stream) still has to emit what it accumulated. Withholding it- // would turn "partial arguments" into "no arguments", which is strictly- // worse — the non-buffered path would already have streamed the same- // fragments. What the client then DOES with malformed JSON is decided- // by how the turn ends, not here: only an `error` event reliably stops- // Claude Code executing the fragment (see the catch block below).- const accumulated = fnCall.doneArgs ?? fnCall.arguments;- if (fnCall.buffered && accumulated) {- send("content_block_delta", {- type: "content_block_delta",- index: fnCall.index,- delta: { type: "input_json_delta", partial_json: accumulated },- });- }- send("content_block_stop", { type: "content_block_stop", index: fnCall.index });- }- openToolBlocks.clear();- };-- /**- * At `output_item.done` of a non-buffered call, send whatever part of the- * final arguments the deltas did not carry. The Codex backend sends every- * call of a multi-call turn with ZERO argument deltas: the arguments exist- * only in `function_call_arguments.done` and the done item, so forwarding- * from deltas alone handed Claude Code `{}` and it answered- * `InputValidationError: ... The required parameter 'file_path' is missing`.- * A native `openai@` call streams every byte as deltas, and its final string- * equals what was forwarded, so nothing more goes out for it.- */- const emitUnforwardedArguments = (fnCall: FnCall, final: string, source: "done" | "item") => {- const emit = (partial: string) => {- send("content_block_delta", {- type: "content_block_delta",- index: fnCall.index,- delta: { type: "input_json_delta", partial_json: partial },- });- fnCall.forwardedBytes += partial.length;- };- if (fnCall.forwardedBytes === 0) {- if (final) {- emit(final);- log(- `[ResponsesSSE] zero-delta function_call ${fnCall.name}: emitted ${final.length} bytes from ${source}`- );- }- return;- }- const forwarded = fnCall.arguments;- if (final === forwarded) return;- if (final.startsWith(forwarded)) {- const suffix = final.slice(forwarded.length);- emit(suffix);- log(- `[ResponsesSSE] function_call ${fnCall.name}: emitted ${suffix.length}-byte suffix the deltas did not carry`- );- return;- }- log(`[ResponsesSSE] done arguments diverge from streamed deltas for ${fnCall.name}`);- };-- /**- * End the turn with an SSE `error` event: Claude Code discards the message- * (no tool_use of it runs) and retries the turn. Open blocks are closed- * first, because their starts are already on the wire. The upstream reader- * is cancelled: nothing more of this response will be used.- */- const endTurnWithStreamError = (message: string) => {- closeReasoning();- closeText();- closeTools();- send("error", { type: "error", error: { type: "api_error", message } });- isClosed = true;- if (pingInterval) {- clearInterval(pingInterval);- pingInterval = null;- }- reportTokens();- reader.cancel().catch(() => {});- safeClose();- };-- /** A degenerate `parallel` wrapper: never shown to Claude Code. */- const endTurnOnDegenerateWrapper = (reason: string, bytes: number) => {- log(`[ResponsesSSE] degenerate parallel wrapper (${reason}, ${bytes} bytes) → error event`);- endTurnWithStreamError(`degenerate parallel tool wrapper (${reason}, ${bytes} bytes)`);- };-- /**- * Emit a valid wrapper's entries as ordinary tool_use blocks, one complete- * argument delta each (a buffered tool goes through onToolCall first). The- * wrapper's reasoning is remembered under the FIRST expanded id only, so the- * next request replays it exactly once, before that call.- */- const repairBufferedCall = (name: string, args: string): string => {- if (opts.shouldBufferTool?.(name) !== true) return args;- try {- const repaired = opts.onToolCall?.(name, args);- if (typeof repaired === "string" && repaired !== args) {- log(`[ResponsesSSE] tool call repaired: ${name}`);- return repaired;- }- } catch (err) {- log(`[ResponsesSSE] onToolCall threw for ${name}: ${err}`);- }- return args;- };- const emitExpandedWrapper = (held: HeldWrapper, calls: ParallelWrapperCall[]) => {- closeReasoning();- closeText();- calls.forEach((call, k) => {- const id = `${held.claudeBaseId}_p${k}`;- const args = repairBufferedCall(call.name, call.arguments);- const index = curIdx++;- opts.onToolCallObserved?.(call.name);- send("content_block_start", {- type: "content_block_start",- index,- content_block: { type: "tool_use", id, name: call.name, input: {} },- });- send("content_block_delta", {- type: "content_block_delta",- index,- delta: { type: "input_json_delta", partial_json: args },- });- send("content_block_stop", { type: "content_block_stop", index });- if (k === 0 && held.reasoning.length > 0) {- rememberReasoningForCall(id, held.reasoning);- }- });- hasToolUse = true;- log(`[ResponsesSSE] parallel wrapper expanded into ${calls.length} tool_use block(s)`);- };-- /**- * The five-event tail both in-band error paths emit: a text block carrying- * the message, then a normal `end_turn`. Shared so the two callers cannot- * drift, and so `start` keeps a computable complexity score.- */- const endTurnWithText = (text: string) => {- const idx = curIdx++;- send("content_block_start", {- type: "content_block_start",- index: idx,- content_block: { type: "text", text: "" },- });- send("content_block_delta", {- type: "content_block_delta",- index: idx,- delta: { type: "text_delta", text },- });- send("content_block_stop", { type: "content_block_stop", index: idx });- send("message_delta", {- type: "message_delta",- delta: { stop_reason: "end_turn", stop_sequence: null },- usage: { input_tokens: inputTokens, output_tokens: outputTokens },- });- send("message_stop", { type: "message_stop" });- };-- send("message_start", {- type: "message_start",- message: {- id: `msg_${Date.now()}`,- type: "message",- role: "assistant",- content: [],- model: opts.modelName,- stop_reason: null,- stop_sequence: null,- usage: messageStartUsage(opts.priorInputTokens),- },+ sink = new ClaudeSseSink(controller, {+ modelName: opts.modelName,+ priorInputTokens: opts.priorInputTokens,+ onToolCallObserved: opts.onToolCallObserved,+ });+ sink.start();+ // runResponsesTurn never rejects and closes the sink when it resolves.+ await runResponsesTurn(sink, response, {+ modelName: opts.modelName,+ toolNameMap: opts.toolNameMap,+ declaredToolNames: opts.declaredToolNames ?? [...(opts.toolNameMap?.values() ?? [])],+ middlewareManager: opts.middlewareManager,+ streamMetadata: new Map(),+ onToolCall: opts.onToolCall,+ shouldBufferTool: opts.shouldBufferTool,+ onAssistantText: opts.onAssistantText,+ contextWindow: opts.contextWindow,+ onApiError: opts.onApiError,+ onTokenUpdate: opts.onTokenUpdate,+ onTurnEnd: opts.onTurnEnd,});- send("ping", { type: "ping" });-- pingInterval = setInterval(() => {- if (!isClosed && Date.now() - lastActivity > 1000) {- send("ping", { type: "ping" });- }- }, 1000);-- try {- while (true) {- const { done, value } = await reader.read();- if (done) break;- lastActivity = Date.now();-- buffer += decoder.decode(value, { stream: true });- const lines = buffer.split("\n");- buffer = lines.pop() || "";-- for (const line of lines) {- const data = sseDataPayload(line);- if (data === null) continue;- if (data === "[DONE]") continue;-- // Raw capture, greppable into test fixtures — same contract as- // [SSE:openai] / [SSE:anthropic] in the sibling parsers.- if (getLogLevel() === "debug") {- log(`[SSE:responses] ${formatRawSseLogPayload(data)}`);- }-- try {- const event = JSON.parse(data);-- // Response-side observation point. The Responses API has no- // `delta` object of its own, so the event stands in for both —- // observers here key off `event.type`.- if (opts.middlewareManager) {- await opts.middlewareManager.afterStreamChunk({- modelId: opts.modelName,- chunk: event,- delta: event,- metadata: streamMetadata,- });- }-- if (getLogLevel() === "debug" && event.type) {- log(`[ResponsesSSE] Event: ${event.type}`);- }-- if (event.type === "response.output_text.delta") {- opts.onAssistantText?.(event.delta ?? "", "text");- closeReasoning();- if (textIdx < 0) {- textIdx = curIdx++;- send("content_block_start", {- type: "content_block_start",- index: textIdx,- content_block: { type: "text", text: "" },- });- }- send("content_block_delta", {- type: "content_block_delta",- index: textIdx,- delta: { type: "text_delta", text: event.delta || "" },- });- } else if (event.type === "response.output_item.added") {- if (event.item?.type === "function_call") {- const itemId = event.item.id;- const openaiCallId = event.item.call_id || itemId;- const callId = openaiCallId.startsWith("toolu_")- ? openaiCallId- : `toolu_${openaiCallId.replace(/^fc_/, "")}`;- const rawFnName = event.item.name || "";- const fnName = decodeToolName(rawFnName);-- if (isParallelWrapperName(fnName, declaredToolNames)) {- // HOLD: no content_block_start until the arguments are judged.- // The reasoning so far belongs to the wrapper, not to a later call.- const held: HeldWrapper = {- claudeBaseId: callId,- arguments: "",- reasoning: pendingReasoning,- };- pendingReasoning = [];- heldWrappers.set(openaiCallId, held);- if (itemId && itemId !== openaiCallId) heldWrappers.set(itemId, held);- log(`[ResponsesSSE] holding parallel wrapper ${rawFnName}`);- continue;- }-- closeReasoning();- closeText();-- const fnCallData: FnCall = {- name: fnName,- arguments: "",- index: curIdx++,- claudeId: callId,- buffered: opts.shouldBufferTool?.(fnName) === true,- forwardedBytes: 0,- };-- functionCalls.set(openaiCallId, fnCallData);- if (itemId && itemId !== openaiCallId) {- functionCalls.set(itemId, fnCallData);- }- openToolBlocks.add(fnCallData);- opts.onToolCallObserved?.(fnName);-- // Bind the reasoning that led to this call, keyed by the id the- // client will echo back, so the next request can replay it.- if (pendingReasoning.length > 0) {- rememberReasoningForCall(callId, pendingReasoning);- pendingReasoning = [];- }-- send("content_block_start", {- type: "content_block_start",- index: fnCallData.index,- content_block: { type: "tool_use", id: callId, name: fnName, input: {} },- });- hasToolUse = true;- }- } else if (- event.type === "response.reasoning_summary_text.delta" ||- // The RAW reasoning text (DashScope, open-weight models) rather- // than a summary of it; a thinking block all the same.- event.type === "response.reasoning_text.delta"- ) {- opts.onAssistantText?.(event.delta ?? "", "reasoning");- // Reasoning is the model's chain of thought, not its answer — it- // belongs in a thinking block, or Claude Code renders it as the reply.- const summaryIndex =- typeof event.summary_index === "number"- ? event.summary_index- : typeof event.content_index === "number"- ? event.content_index- : 0;- if (reasoningIdx < 0) {- closeText();- reasoningIdx = curIdx++;- lastSummaryIndex = summaryIndex;- send("content_block_start", {- type: "content_block_start",- index: reasoningIdx,- content_block: { type: "thinking", thinking: "" },- });- } else if (summaryIndex !== lastSummaryIndex) {- // New summary section — restore the paragraph break OpenAI- // represents structurally rather than in the text stream.- lastSummaryIndex = summaryIndex;- send("content_block_delta", {- type: "content_block_delta",- index: reasoningIdx,- delta: { type: "thinking_delta", thinking: "\n\n" },- });- }- send("content_block_delta", {- type: "content_block_delta",- index: reasoningIdx,- delta: { type: "thinking_delta", thinking: event.delta || "" },- });- } else if (event.type === "response.function_call_arguments.delta") {- const callId = event.call_id || event.item_id;- const fnCall = functionCalls.get(callId);- const held = fnCall ? undefined : heldWrappers.get(callId);- if (held) held.arguments += event.delta || "";- if (fnCall) {- fnCall.arguments += event.delta || "";- // Buffered calls emit nothing here — the whole argument object- // goes out in one delta at output_item.done, after any repair.- if (!fnCall.buffered) {- send("content_block_delta", {- type: "content_block_delta",- index: fnCall.index,- delta: { type: "input_json_delta", partial_json: event.delta || "" },- });- fnCall.forwardedBytes += (event.delta || "").length;- }- }- } else if (event.type === "response.function_call_arguments.done") {- // The complete argument string. The Codex backend sends a multi-call- // turn with NO argument deltas, so for those calls this (or the- // item at output_item.done) is the only copy of the arguments.- const fnCall = functionCalls.get(event.call_id) || functionCalls.get(event.item_id);- const held = heldWrappers.get(event.call_id) || heldWrappers.get(event.item_id);- if (typeof event.arguments === "string") {- if (fnCall) fnCall.doneArgs = event.arguments;- else if (held) held.doneArgs = event.arguments;- }- } else if (event.type === "response.output_item.done") {- if (event.item?.type === "reasoning" && event.item.encrypted_content) {- // Keep the item verbatim (minus the id, which the Responses API- // does not require on replay and which buildPayload strips).- pendingReasoning.push({- type: "reasoning",- content: event.item.content ?? [],- encrypted_content: event.item.encrypted_content,- summary: event.item.summary ?? [],- });- }- if (event.item?.type === "function_call") {- const callId = event.item.call_id || event.item.id;- const held = heldWrappers.get(callId) || heldWrappers.get(event.item.id);- if (held) {- heldWrappers.delete(callId);- heldWrappers.delete(event.item.id);- const itemArgs =- typeof event.item.arguments === "string" ? event.item.arguments : undefined;- const final = held.doneArgs ?? itemArgs ?? held.arguments;- const parsed = parseParallelWrapper(final, decodeToolName);- if (!parsed.ok) {- endTurnOnDegenerateWrapper(parsed.reason, final.length);- return;- }- emitExpandedWrapper(held, parsed.calls);- continue;- }- const fnCall = functionCalls.get(callId) || functionCalls.get(event.item.id);- if (fnCall && openToolBlocks.has(fnCall)) {- const itemArgs =- typeof event.item.arguments === "string" ? event.item.arguments : undefined;- const final = fnCall.doneArgs ?? itemArgs ?? fnCall.arguments;- if (fnCall.buffered) {- // Give the behavior layer its one chance to rewrite the call,- // then emit the complete argument object as a single delta.- let finalArgs = final;- try {- const repaired = opts.onToolCall?.(fnCall.name, finalArgs);- if (typeof repaired === "string" && repaired !== finalArgs) {- log(`[ResponsesSSE] tool call repaired: ${fnCall.name}`);- finalArgs = repaired;- }- } catch (err) {- // A failing rule must never corrupt the stream — emit the- // model's original arguments and carry on.- log(`[ResponsesSSE] onToolCall threw for ${fnCall.name}: ${err}`);- }- send("content_block_delta", {- type: "content_block_delta",- index: fnCall.index,- delta: { type: "input_json_delta", partial_json: finalArgs },- });- fnCall.forwardedBytes = finalArgs.length;- } else {- emitUnforwardedArguments(- fnCall,- final,- fnCall.doneArgs !== undefined ? "done" : "item"- );- }- send("content_block_stop", { type: "content_block_stop", index: fnCall.index });- openToolBlocks.delete(fnCall);- }- }- } else if (event.type === "response.incomplete") {- // The reason lives at response.incomplete_details.reason — reading- // event.reason always yielded "unknown".- incompleteReason =- event.response?.incomplete_details?.reason ?? event.reason ?? "unknown";- log(`[ResponsesSSE] Response incomplete: ${incompleteReason}`);- if (event.response?.usage) {- inputTokens = event.response.usage.input_tokens || inputTokens;- outputTokens = event.response.usage.output_tokens || outputTokens;- usageReported = true;- }- // A wrapper still held when the response is cut short never got- // its arguments judged: degenerate by definition.- const pending = heldWrappers.values().next().value;- if (pending) {- endTurnOnDegenerateWrapper(- "incomplete",- (pending.doneArgs ?? pending.arguments).length- );- return;- }- } else if (event.type === "response.completed" || event.type === "response.done") {- if (event.response?.usage) {- inputTokens = event.response.usage.input_tokens || 0;- outputTokens = event.response.usage.output_tokens || 0;- usageReported = true;- } else if (event.usage) {- inputTokens = event.usage.input_tokens || 0;- outputTokens = event.usage.output_tokens || 0;- usageReported = true;- }- } else if (event.type === "error" || event.type === "response.failed") {- const err = event.error || event.response?.error || {};- const errMsg = err.message || event.message || "Unknown API error";- const errCode = err.code || event.code || "";- log(`[ResponsesSSE] API error: ${errCode} - ${errMsg}`);-- // Signal the terminal error so the caller records this turn as a- // failure (the error rides an HTTP 200 stream, invisible to status).- opts.onApiError?.(errCode, errMsg);-- closeReasoning();- closeText();- closeTools();-- // Context-overflow gets an actionable message (with the real- // per-backend cap when known) instead of the bare error code —- // otherwise the user just sees a cryptic `context_length_exceeded`- // and a stuck session (/compact re-sends the same oversized input).- const isCtxOverflow =- errCode === "context_length_exceeded" ||- /context (length|window)|exceeds? the context|too long|maximum context/i.test(- errMsg- );- let errorText = `\n\n[API Error: ${errCode} ${errMsg}]`;- if (isCtxOverflow) {- const cap =- opts.contextWindow && opts.contextWindow > 0- ? ` ~${Math.round(opts.contextWindow / 1000)}K tokens`- : "";- errorText =- `\n\n[Context limit reached] This model's backend enforces a smaller context window${cap} than its API spec. ` +- "Run /clear to start fresh (/compact will also fail — it re-sends the full conversation), " +- `or route the model via \`oai@${opts.modelName}\` to use the full-size window.`;- }-- endTurnWithText(errorText);- isClosed = true;- if (pingInterval) {- clearInterval(pingInterval);- pingInterval = null;- }- reportTokens();- safeClose();- return;- }- } catch (parseError) {- log(`[ResponsesSSE] Parse error: ${parseError}`);- }- }- }-- // The stream ended while a wrapper was still held: its arguments were- // never completed, so there is nothing valid to expand.- const unfinished = heldWrappers.values().next().value;- if (unfinished) {- endTurnOnDegenerateWrapper(- "incomplete",- (unfinished.doneArgs ?? unfinished.arguments).length- );- return;- }-- if (pingInterval) {- clearInterval(pingInterval);- pingInterval = null;- }-- closeReasoning();- closeText();- closeTools();-- // A truncated turn must NOT be reported as a finished tool call. OpenAI- // emits the partial function_call arguments it managed to produce, so- // "tool_use" makes the client execute a tool with malformed JSON- // (InputValidationError). Anthropic's contract for a cut-off turn is- // stop_reason "max_tokens", which is the honest label here.- //- // KNOWN GAP: "max_tokens" does not actually stop Claude Code executing- // the partial block. Verified against 2.1.217 (passflow session,- // 2026-07-22, six days after v7.12.7 shipped this): the client ran the- // truncated Write and reported InputValidationError anyway. The catch- // block below uses an `error` event, which does stop it — but that is- // only safe there because a dead socket is transient. max_output_tokens- // is deterministic, so an error event would make the client retry a- // request that truncates again. Capping the budget is the real fix and- // the codex backend rejects max_output_tokens ("Unsupported parameter"),- // so the label stays honest and the execution stays unprevented.- const stopReason = incompleteReason- ? incompleteReason === "content_filter"- ? "refusal"- : "max_tokens"- : hasToolUse- ? "tool_use"- : "end_turn";- if (incompleteReason) {- log(- `[ResponsesSSE] Truncated response (${incompleteReason}) → stop_reason=${stopReason}`- );- }- send("message_delta", {- type: "message_delta",- delta: { stop_reason: stopReason, stop_sequence: null },- usage: { input_tokens: inputTokens, output_tokens: outputTokens },- });- send("message_stop", { type: "message_stop" });-- isClosed = true;- reportTokens();- if (opts.middlewareManager) {- await opts.middlewareManager.afterStreamComplete(opts.modelName, streamMetadata);- }- opts.onTurnEnd?.();- safeClose();- } catch (error) {- if (pingInterval) {- clearInterval(pingInterval);- pingInterval = null;- }- log(`[ResponsesSSE] Stream error: ${error}`);-- if (!isClosed) {- try {- closeReasoning();- closeText();- // A tool block still open here had its argument JSON cut mid-object:- // the socket died between `output_item.added` and `output_item.done`.- // closeTools() still has to emit it, because its content_block_start- // is already on the wire — so how the turn ENDS decides what the- // client does with the fragment, and `end_turn` makes Claude Code run- // the tool on truncated JSON:- // InputValidationError: Write was called with input that could not- // be parsed as JSON. You sent (first 200 of 9437 bytes): {"file_pa…- // `max_tokens` does not rescue it either: Claude Code 2.1.217 ran a- // max_tokens-terminated tool call anyway (passflow session,- // 2026-07-22, six days after v7.12.7 shipped that mitigation). Only- // an `error` event ends the message with no completed tool_use, and- // it is the honest report — the turn did fail. devin-connect ends a- // mid-stream fault the same way, for the same reason.- const toolCallCutOff = openToolBlocks.size > 0;- closeTools();-- if (toolCallCutOff) {- log("[ResponsesSSE] tool arguments cut off mid-stream → error event");- send("error", {- type: "error",- error: { type: "api_error", message: `Stream error: ${error}` },- });- } else {- endTurnWithText(`\n\n[Stream error: ${error}]`);- }- } catch {}-- isClosed = true;- reportTokens();- safeClose();- }- }},// Downstream went away (client disconnect, abort, or timeout). The// controller is already closed here, but none of the normal close paths- // above ran — so without this, `isClosed` stays false and the keep-alive- // `pingInterval` keeps calling `send()` → `controller.enqueue()` on a- // closed controller. That throws `Invalid state: Controller is already- // closed` from inside a timer callback, where nothing catches it, and the- // proxy process dies (the next request then fails with ConnectionRefused).- // Every sibling parser already has this handler; this one was missing it.- //- // The upstream reader is cancelled too. Without it a disconnected client- // left the upstream response streaming to completion (minutes, for a long- // reasoning turn or a stalled one) with nobody reading the result. The- // pending `reader.read()` in `start` then settles `done` (or throws), and- // every path out of `start` is a no-op on a closed stream.+ // ran — so the sink marks itself closed (the keep-alive ping would+ // otherwise enqueue on a closed controller and throw from a timer callback,+ // killing the proxy process), and aborts the turn: the upstream reader is+ // cancelled rather than left streaming to completion with nobody reading.cancel() {- isClosed = true;- cancelledByClient = true;- if (pingInterval) {- clearInterval(pingInterval);- pingInterval = null;- }- reader.cancel().catch(() => {});+ sink?.cancel();},});diff --git a/packages/cli/src/handlers/shared/stream-parsers/responses/claude-sse-sink.ts b/packages/cli/src/handlers/shared/stream-parsers/responses/claude-sse-sink.tsnew file mode 100644index 00000000..451d9e43--- /dev/null+++ b/packages/cli/src/handlers/shared/stream-parsers/responses/claude-sse-sink.ts@@ -0,0 +1,233 @@+/**+ * The one writer of Claude SSE on the Responses path.+ *+ * One sink is one downstream Claude message: `message_start` once, a+ * monotonic content-block index shared by every upstream leg of the turn, the+ * keepalive ping, the tool blocks' states, and exactly one ending+ * (`message_delta` + `message_stop`, an SSE `error`, or a client disconnect).+ * The leg parser (`responses-leg.ts`) and the turn driver+ * (`responses-turn.ts`) write only through it, so a second upstream leg+ * continues at the next block index and can never reopen or reuse a block.+ *+ * `cancel()` is the downstream disconnect: it marks the sink closed, stops the+ * ping, and aborts the turn's AbortController, whose signal the leg uses to+ * cancel its upstream reader and the driver checks before issuing anything.+ */++import { log } from "../../../../logger.js";+import { messageStartUsage } from "../message-start-usage.js";++/** STARTED → ARGS-COMPLETE → STOPPED. A block stopped without ARGS-COMPLETE was cut off. */+interface ToolBlockState {+ name: string;+ argsComplete: boolean;+ stopped: boolean;+}++export interface ClaudeSseSinkOptions {+ modelName: string;+ /** Seeds `message_start.usage`; see message-start-usage.ts. */+ priorInputTokens?: number;+ /** Fired at every tool_use `content_block_start`: observation and dispatch are one event. */+ onToolCallObserved?: (name: string) => void;+}++export class ClaudeSseSink {+ private readonly encoder = new TextEncoder();+ private curIdx = 0;+ private closed = false;+ private ended = false;+ private pingTimer: ReturnType<typeof setInterval> | null = null;+ private lastActivity = Date.now();+ private readonly toolBlocks = new Map<number, ToolBlockState>();+ private readonly abort = new AbortController();++ constructor(+ private readonly controller: ReadableStreamDefaultController<Uint8Array>,+ private readonly opts: ClaudeSseSinkOptions+ ) {}++ /** Aborted when the client disconnects. */+ get signal(): AbortSignal {+ return this.abort.signal;+ }++ /** True once the downstream is closed (an ending was written, or the client left). */+ get isClosed(): boolean {+ return this.closed;+ }++ /** True when the client disconnected (as opposed to the turn ending normally). */+ get isCancelled(): boolean {+ return this.abort.signal.aborted;+ }++ /** Any tool_use block of this message has been started. */+ get hasToolUse(): boolean {+ return this.toolBlocks.size > 0;+ }++ /** A tool block was started and either is still open or was stopped without its final arguments. */+ get hasIncompleteToolBlock(): boolean {+ for (const t of this.toolBlocks.values()) if (!t.argsComplete) return true;+ return false;+ }++ /** At least one tool block was stopped with its final arguments sent. */+ get hasCompletedToolBlock(): boolean {+ for (const t of this.toolBlocks.values()) if (t.argsComplete && t.stopped) return true;+ return false;+ }++ send(event: string, data: unknown): void {+ if (this.closed) return;+ this.controller.enqueue(+ this.encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)+ );+ }++ /** Upstream bytes arrived: the ping only fires after a second of upstream silence. */+ touch(): void {+ this.lastActivity = Date.now();+ }++ /** The next content-block index. Never reused, across every leg of the turn. */+ nextIndex(): number {+ return this.curIdx++;+ }++ /** `message_start`, one ping, and the 1 s keepalive. */+ start(): void {+ this.send("message_start", {+ type: "message_start",+ message: {+ id: `msg_${Date.now()}`,+ type: "message",+ role: "assistant",+ content: [],+ model: this.opts.modelName,+ stop_reason: null,+ stop_sequence: null,+ usage: messageStartUsage(this.opts.priorInputTokens),+ },+ });+ this.send("ping", { type: "ping" });+ this.pingTimer = setInterval(() => {+ if (!this.closed && Date.now() - this.lastActivity > 1000) {+ this.send("ping", { type: "ping" });+ }+ }, 1000);+ }++ startBlock(index: number, contentBlock: Record<string, unknown>): void {+ this.send("content_block_start", {+ type: "content_block_start",+ index,+ content_block: contentBlock,+ });+ }++ delta(index: number, delta: Record<string, unknown>): void {+ this.send("content_block_delta", { type: "content_block_delta", index, delta });+ }++ stopBlock(index: number): void {+ this.send("content_block_stop", { type: "content_block_stop", index });+ }++ /** A tool_use `content_block_start`; the observer fires here and nowhere else. */+ startToolBlock(index: number, id: string, name: string): void {+ this.toolBlocks.set(index, { name, argsComplete: false, stopped: false });+ this.opts.onToolCallObserved?.(name);+ this.startBlock(index, { type: "tool_use", id, name, input: {} });+ }++ /** The block's final arguments have been sent. */+ markToolArgsComplete(index: number): void {+ const t = this.toolBlocks.get(index);+ if (t) t.argsComplete = true;+ }++ stopToolBlock(index: number): void {+ const t = this.toolBlocks.get(index);+ if (t) t.stopped = true;+ this.stopBlock(index);+ }++ /** `message_delta` + `message_stop`. */+ endMessage(stopReason: string, usage: { input_tokens: number; output_tokens: number }): void {+ this.send("message_delta", {+ type: "message_delta",+ delta: { stop_reason: stopReason, stop_sequence: null },+ usage,+ });+ this.send("message_stop", { type: "message_stop" });+ this.finish();+ }++ /**+ * The five-event tail of an in-band error: a text block carrying the message,+ * then a normal `end_turn`.+ */+ endWithText(text: string, usage: { input_tokens: number; output_tokens: number }): void {+ const idx = this.nextIndex();+ this.startBlock(idx, { type: "text", text: "" });+ this.delta(idx, { type: "text_delta", text });+ this.stopBlock(idx);+ this.endMessage("end_turn", usage);+ }++ /**+ * End with an SSE `error` event: Claude Code discards the message (no+ * tool_use of it runs) and retries the turn.+ */+ endWithError(message: string, type = "api_error"): void {+ this.send("error", { type: "error", error: { type, message } });+ this.finish();+ }++ /** Stop the ping and close the controller. Idempotent; safe after cancel(). */+ close(): void {+ this.stopPing();+ this.closed = true;+ try {+ this.controller.close();+ } catch {+ // Already closed by cancel(); nothing left to do.+ }+ }++ /**+ * The client went away. The controller is already closed by the runtime, so+ * nothing may be enqueued again: without `closed` the ping timer would call+ * `enqueue()` on a closed controller and throw from a timer callback, where+ * nothing catches it, killing the proxy process.+ */+ cancel(): void {+ this.closed = true;+ this.stopPing();+ if (!this.abort.signal.aborted) {+ log("[ResponsesSSE] client disconnected: cancelling the upstream reader");+ this.abort.abort();+ }+ }++ /** An ending was written: nothing more goes out, the ping stops. */+ private finish(): void {+ this.ended = true;+ this.stopPing();+ this.closed = true;+ }++ /** True once an ending (message_stop or error) was written. */+ get hasEnded(): boolean {+ return this.ended;+ }++ private stopPing(): void {+ if (this.pingTimer) {+ clearInterval(this.pingTimer);+ this.pingTimer = null;+ }+ }+}diff --git a/packages/cli/src/handlers/shared/stream-parsers/responses/responses-leg.ts b/packages/cli/src/handlers/shared/stream-parsers/responses/responses-leg.tsnew file mode 100644index 00000000..2ba596d5--- /dev/null+++ b/packages/cli/src/handlers/shared/stream-parsers/responses/responses-leg.ts@@ -0,0 +1,611 @@+/**+ * One upstream Responses body → Claude SSE events (through the sink) → one+ * LegOutcome.+ *+ * A LEG is one upstream HTTP response. A turn (one downstream Claude message,+ * `responses-turn.ts`) has one leg, or more when the driver retries a stalled or+ * degenerate leg. Everything here is per leg and discarded when the leg ends:+ * function-call accumulators, this leg's open blocks, pending reasoning, the+ * incomplete reason, held `parallel` wrappers and usage. Block indices,+ * message lifecycle and tool block states belong to the turn and live on the+ * sink.+ *+ * Every leg closes the blocks it opened before it returns, so the driver+ * always starts the next leg, or writes the ending, from a clean slate. How+ * the MESSAGE ends is the driver's decision, never the leg's.+ *+ * The Responses API events handled:+ * response.output_text.delta → content text+ * response.output_item.added → new item (function_call, reasoning)+ * response.function_call_arguments.delta / .done → tool arguments+ * response.reasoning_summary_text.delta / reasoning_text.delta → thinking output+ * response.output_item.done → close tool_use block+ * response.completed / response.done / response.incomplete → final usage+ * error / response.failed → in-stream API error+ */++import {+ type CachedReasoningItem,+ rememberReasoningForCall,+} from "../../../../adapters/reasoning-cache.js";+import { getLogLevel, log } from "../../../../logger.js";+import type { UsageCacheDetail } from "../../token-tracker.js";+import { formatRawSseLogPayload } from "../openai-sse.js";+import { sseDataPayload } from "../sse-line.js";+import type { ClaudeSseSink } from "./claude-sse-sink.js";+import {+ type ParallelWrapperCall,+ isParallelWrapperName,+ parseParallelWrapper,+} from "./parallel-wrapper.js";++/** One leg's usage, read from `response.completed` / `.incomplete`. */+export interface Usage {+ inputTokens: number;+ outputTokens: number;+ /** From `input_tokens_details.cached_tokens` when the backend reports it. */+ cacheDetail?: UsageCacheDetail;+}++export type LegOutcome =+ | { kind: "done"; usage?: Usage; incomplete?: string }+ | { kind: "stall"; afterMs: number }+ | {+ kind: "degenerate-wrapper";+ bytes: number;+ reason: "unparseable" | "shape" | "empty" | "incomplete";+ usage?: Usage;+ }+ | { kind: "api-error"; code: string; message: string; usage?: Usage }+ | { kind: "stream-error"; error: unknown; openToolBlock: boolean; usage?: Usage }+ | { kind: "cancelled"; usage?: Usage };++export interface ResponsesLegContext {+ sink: ClaudeSseSink;+ modelName: string;+ toolNameMap?: Map<string, string>;+ /** Claude Code's own tool names; see isParallelWrapperName. */+ declaredToolNames: string[];+ // biome-ignore lint/suspicious/noExplicitAny: MiddlewareManager is untyped on every parser+ middlewareManager?: any;+ /** Shared across every chunk hook of the turn; handed to afterStreamComplete. */+ // biome-ignore lint/suspicious/noExplicitAny: middleware metadata is free-form+ streamMetadata: Map<string, any>;+ onToolCall?: (name: string, argsJson: string) => string | null | undefined;+ shouldBufferTool?: (name: string) => boolean;+ onAssistantText?: (text: string, kind?: "text" | "reasoning") => void;+}++type FnCall = {+ name: string;+ arguments: string;+ index: number;+ claudeId?: string;+ /** Withhold input_json_delta until the call completes so it can be repaired. */+ buffered?: boolean;+ /**+ * Bytes of `arguments` already sent downstream as `input_json_delta`. Zero+ * for a buffered call until it completes, and zero for every call of a Codex+ * multi-call turn, which streams no argument deltas at all.+ */+ forwardedBytes: number;+ /** `response.function_call_arguments.done`'s complete argument string. */+ doneArgs?: string;+};++/**+ * A `parallel` wrapper call being accumulated without a content_block_start+ * (see parallel-wrapper.ts).+ */+type HeldWrapper = {+ claudeBaseId: string;+ arguments: string;+ doneArgs?: string;+ /** The reasoning that led to the wrapper, bound to its first expanded call only. */+ reasoning: CachedReasoningItem[];+};++/** Internal: a leg-ending decision reached inside the event dispatch. */+type Stop = { stop: LegOutcome };++// biome-ignore lint/suspicious/noExplicitAny: Responses events are untyped JSON+type ResponsesEvent = any;++/** Read `usage` from a Responses usage object; undefined when it carries none. */+function readUsage(raw: ResponsesEvent, prior?: Usage, keepPrior = false): Usage | undefined {+ if (!raw || typeof raw !== "object") return undefined;+ const input = raw.input_tokens || (keepPrior ? (prior?.inputTokens ?? 0) : 0);+ const output = raw.output_tokens || (keepPrior ? (prior?.outputTokens ?? 0) : 0);+ const cached = raw.input_tokens_details?.cached_tokens;+ const usage: Usage = { inputTokens: input, outputTokens: output };+ if (typeof cached === "number" && cached > 0) {+ usage.cacheDetail = { cacheReadTokens: cached, cacheCreationTokens: 0 };+ }+ return usage;+}++class ResponsesLeg {+ private textIdx = -1;+ private reasoningIdx = -1;+ // OpenAI splits a reasoning summary into parts (summary_index 0, 1, 2, …),+ // each a bolded section. The paragraph break between parts is structural —+ // it is NOT in the text deltas — so tracking the index lets us re-insert it,+ // otherwise "**A**" + "**B**" render as one smashed "**A****B**".+ private lastSummaryIndex = -1;+ // Set when OpenAI reports the response was cut short (response.incomplete).+ private incompleteReason: string | null = null;+ // Reasoning items seen since the last function call. OpenAI emits them just+ // before the call they informed; we hand them to the cache keyed by that call+ // so the next request can replay them (see reasoning-cache.ts).+ private pendingReasoning: CachedReasoningItem[] = [];+ private usage: Usage | undefined;+ // Keyed by BOTH call_id and item_id, so the same FnCall object appears under+ // two keys — never derive a count from this map's size.+ private readonly functionCalls = new Map<string, FnCall>();+ // Tool blocks that have been started but not yet stopped, in emission order.+ private readonly openToolBlocks = new Set<FnCall>();+ private readonly heldWrappers = new Map<string, HeldWrapper>();++ constructor(private readonly ctx: ResponsesLegContext) {}++ private get sink(): ClaudeSseSink {+ return this.ctx.sink;+ }++ private decodeToolName(name: string): string {+ return this.ctx.toolNameMap?.get(name) || name;+ }++ async run(response: Response): Promise<LegOutcome> {+ const reader = response.body?.getReader();+ if (!reader) {+ return { kind: "stream-error", error: new Error("No response body"), openToolBlock: false };+ }+ const signal = this.sink.signal;+ const onAbort = () => {+ reader.cancel().catch(() => {});+ };+ if (signal.aborted) onAbort();+ else signal.addEventListener("abort", onAbort, { once: true });++ const decoder = new TextDecoder();+ let buffer = "";+ try {+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ this.sink.touch();++ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split("\n");+ buffer = lines.pop() || "";++ for (const line of lines) {+ const data = sseDataPayload(line);+ if (data === null || data === "[DONE]") continue;+ // Raw capture, greppable into test data — same contract as+ // [SSE:openai] / [SSE:anthropic] in the sibling parsers.+ if (getLogLevel() === "debug") {+ log(`[SSE:responses] ${formatRawSseLogPayload(data)}`);+ }+ // A malformed frame, or a handler or middleware that throws on one+ // event, costs that event only, never the turn.+ let stop: Stop | undefined;+ try {+ stop = await this.dispatch(JSON.parse(data));+ } catch (parseError) {+ log(`[ResponsesSSE] Parse error: ${parseError}`);+ continue;+ }+ if (stop) {+ this.closeAll();+ reader.cancel().catch(() => {});+ return stop.stop;+ }+ }+ }+ } catch (error) {+ if (signal.aborted) return { kind: "cancelled", usage: this.usage };+ log(`[ResponsesSSE] Stream error: ${error}`);+ this.closeReasoning();+ this.closeText();+ // A tool block still open here had its argument JSON cut mid-object: the+ // socket died between `output_item.added` and `output_item.done`. Its+ // content_block_start is already on the wire, so how the turn ENDS decides+ // what the client does with the fragment (see the driver).+ const openToolBlock = this.openToolBlocks.size > 0;+ this.closeTools();+ return { kind: "stream-error", error, openToolBlock, usage: this.usage };+ } finally {+ signal.removeEventListener("abort", onAbort);+ }++ if (signal.aborted) return { kind: "cancelled", usage: this.usage };++ // The stream ended while a wrapper was still held: its arguments were never+ // completed, so there is nothing valid to expand.+ const unfinished = this.heldWrappers.values().next().value;+ if (unfinished) {+ this.closeAll();+ return this.degenerate("incomplete", (unfinished.doneArgs ?? unfinished.arguments).length);+ }++ this.closeAll();+ return {+ kind: "done",+ usage: this.usage,+ ...(this.incompleteReason ? { incomplete: this.incompleteReason } : {}),+ };+ }++ private degenerate(+ reason: "unparseable" | "shape" | "empty" | "incomplete",+ bytes: number+ ): LegOutcome {+ log(`[ResponsesSSE] degenerate parallel wrapper (${reason}, ${bytes} bytes)`);+ return { kind: "degenerate-wrapper", reason, bytes, usage: this.usage };+ }++ private async dispatch(event: ResponsesEvent): Promise<Stop | undefined> {+ // Response-side observation point. The Responses API has no `delta`+ // object of its own, so the event stands in for both — observers here key+ // off `event.type`.+ if (this.ctx.middlewareManager) {+ await this.ctx.middlewareManager.afterStreamChunk({+ modelId: this.ctx.modelName,+ chunk: event,+ delta: event,+ metadata: this.ctx.streamMetadata,+ });+ }+ if (getLogLevel() === "debug" && event.type) {+ log(`[ResponsesSSE] Event: ${event.type}`);+ }++ switch (event.type) {+ case "response.output_text.delta":+ this.onTextDelta(event);+ return undefined;+ case "response.output_item.added":+ this.onItemAdded(event);+ return undefined;+ case "response.reasoning_summary_text.delta":+ // The RAW reasoning text (DashScope, open-weight models) rather than a+ // summary of it; a thinking block all the same.+ case "response.reasoning_text.delta":+ this.onReasoningDelta(event);+ return undefined;+ case "response.function_call_arguments.delta":+ this.onArgumentsDelta(event);+ return undefined;+ case "response.function_call_arguments.done":+ this.onArgumentsDone(event);+ return undefined;+ case "response.output_item.done":+ return this.onItemDone(event);+ case "response.incomplete":+ return this.onIncomplete(event);+ case "response.completed":+ case "response.done":+ this.usage = readUsage(event.response?.usage ?? event.usage) ?? this.usage;+ return undefined;+ case "error":+ case "response.failed": {+ const err = event.error || event.response?.error || {};+ const message = err.message || event.message || "Unknown API error";+ const code = err.code || event.code || "";+ log(`[ResponsesSSE] API error: ${code} - ${message}`);+ return { stop: { kind: "api-error", code, message, usage: this.usage } };+ }+ default:+ return undefined;+ }+ }++ private onTextDelta(event: ResponsesEvent): void {+ this.ctx.onAssistantText?.(event.delta ?? "", "text");+ this.closeReasoning();+ if (this.textIdx < 0) {+ this.textIdx = this.sink.nextIndex();+ this.sink.startBlock(this.textIdx, { type: "text", text: "" });+ }+ this.sink.delta(this.textIdx, { type: "text_delta", text: event.delta || "" });+ }++ private onItemAdded(event: ResponsesEvent): void {+ if (event.item?.type !== "function_call") return;+ const itemId = event.item.id;+ const openaiCallId = event.item.call_id || itemId;+ const callId = openaiCallId.startsWith("toolu_")+ ? openaiCallId+ : `toolu_${openaiCallId.replace(/^fc_/, "")}`;+ const rawFnName = event.item.name || "";+ const fnName = this.decodeToolName(rawFnName);++ if (isParallelWrapperName(fnName, this.ctx.declaredToolNames)) {+ // HOLD: no content_block_start until the arguments are judged. The+ // reasoning so far belongs to the wrapper, not to a later call.+ const held: HeldWrapper = {+ claudeBaseId: callId,+ arguments: "",+ reasoning: this.pendingReasoning,+ };+ this.pendingReasoning = [];+ this.heldWrappers.set(openaiCallId, held);+ if (itemId && itemId !== openaiCallId) this.heldWrappers.set(itemId, held);+ log(`[ResponsesSSE] holding parallel wrapper ${rawFnName}`);+ return;+ }++ this.closeReasoning();+ this.closeText();++ const fnCall: FnCall = {+ name: fnName,+ arguments: "",+ index: this.sink.nextIndex(),+ claudeId: callId,+ buffered: this.ctx.shouldBufferTool?.(fnName) === true,+ forwardedBytes: 0,+ };+ this.functionCalls.set(openaiCallId, fnCall);+ if (itemId && itemId !== openaiCallId) this.functionCalls.set(itemId, fnCall);+ this.openToolBlocks.add(fnCall);++ // Bind the reasoning that led to this call, keyed by the id the client+ // will echo back, so the next request can replay it.+ if (this.pendingReasoning.length > 0) {+ rememberReasoningForCall(callId, this.pendingReasoning);+ this.pendingReasoning = [];+ }++ this.sink.startToolBlock(fnCall.index, callId, fnName);+ }++ private onReasoningDelta(event: ResponsesEvent): void {+ this.ctx.onAssistantText?.(event.delta ?? "", "reasoning");+ // Reasoning is the model's chain of thought, not its answer — it belongs+ // in a thinking block, or Claude Code renders it as the reply.+ const summaryIndex =+ typeof event.summary_index === "number"+ ? event.summary_index+ : typeof event.content_index === "number"+ ? event.content_index+ : 0;+ if (this.reasoningIdx < 0) {+ this.closeText();+ this.reasoningIdx = this.sink.nextIndex();+ this.lastSummaryIndex = summaryIndex;+ this.sink.startBlock(this.reasoningIdx, { type: "thinking", thinking: "" });+ } else if (summaryIndex !== this.lastSummaryIndex) {+ // New summary section — restore the paragraph break OpenAI represents+ // structurally rather than in the text stream.+ this.lastSummaryIndex = summaryIndex;+ this.sink.delta(this.reasoningIdx, { type: "thinking_delta", thinking: "\n\n" });+ }+ this.sink.delta(this.reasoningIdx, { type: "thinking_delta", thinking: event.delta || "" });+ }++ private onArgumentsDelta(event: ResponsesEvent): void {+ const callId = event.call_id || event.item_id;+ const fnCall = this.functionCalls.get(callId);+ if (!fnCall) {+ const held = this.heldWrappers.get(callId);+ if (held) held.arguments += event.delta || "";+ return;+ }+ fnCall.arguments += event.delta || "";+ // Buffered calls emit nothing here — the whole argument object goes out in+ // one delta at output_item.done, after any repair.+ if (!fnCall.buffered) {+ this.sink.delta(fnCall.index, { type: "input_json_delta", partial_json: event.delta || "" });+ fnCall.forwardedBytes += (event.delta || "").length;+ }+ }++ private onArgumentsDone(event: ResponsesEvent): void {+ // The complete argument string. The Codex backend sends a multi-call turn+ // with NO argument deltas, so for those calls this (or the item at+ // output_item.done) is the only copy of the arguments.+ if (typeof event.arguments !== "string") return;+ const fnCall = this.functionCalls.get(event.call_id) || this.functionCalls.get(event.item_id);+ if (fnCall) {+ fnCall.doneArgs = event.arguments;+ return;+ }+ const held = this.heldWrappers.get(event.call_id) || this.heldWrappers.get(event.item_id);+ if (held) held.doneArgs = event.arguments;+ }++ private onItemDone(event: ResponsesEvent): Stop | undefined {+ const item = event.item;+ if (item?.type === "reasoning" && item.encrypted_content) {+ // Keep the item verbatim (minus the id, which the Responses API does not+ // require on replay and which buildPayload strips).+ this.pendingReasoning.push({+ type: "reasoning",+ content: item.content ?? [],+ encrypted_content: item.encrypted_content,+ summary: item.summary ?? [],+ });+ }+ if (item?.type !== "function_call") return undefined;++ const callId = item.call_id || item.id;+ const itemArgs = typeof item.arguments === "string" ? item.arguments : undefined;++ const held = this.heldWrappers.get(callId) || this.heldWrappers.get(item.id);+ if (held) {+ this.heldWrappers.delete(callId);+ this.heldWrappers.delete(item.id);+ const final = held.doneArgs ?? itemArgs ?? held.arguments;+ const parsed = parseParallelWrapper(final, (n) => this.decodeToolName(n));+ if (!parsed.ok) return { stop: this.degenerate(parsed.reason, final.length) };+ this.emitExpandedWrapper(held, parsed.calls);+ return undefined;+ }++ const fnCall = this.functionCalls.get(callId) || this.functionCalls.get(item.id);+ if (!fnCall || !this.openToolBlocks.has(fnCall)) return undefined;+ const final = fnCall.doneArgs ?? itemArgs ?? fnCall.arguments;+ if (fnCall.buffered) {+ // Give the behavior layer its one chance to rewrite the call, then emit+ // the complete argument object as a single delta.+ const finalArgs = this.repairBufferedCall(fnCall.name, final);+ this.sink.delta(fnCall.index, { type: "input_json_delta", partial_json: finalArgs });+ fnCall.forwardedBytes = finalArgs.length;+ } else {+ this.emitUnforwardedArguments(fnCall, final, fnCall.doneArgs !== undefined ? "done" : "item");+ }+ this.sink.markToolArgsComplete(fnCall.index);+ this.sink.stopToolBlock(fnCall.index);+ this.openToolBlocks.delete(fnCall);+ return undefined;+ }++ private onIncomplete(event: ResponsesEvent): Stop | undefined {+ // The reason lives at response.incomplete_details.reason — reading+ // event.reason always yielded "unknown".+ this.incompleteReason = event.response?.incomplete_details?.reason ?? event.reason ?? "unknown";+ log(`[ResponsesSSE] Response incomplete: ${this.incompleteReason}`);+ if (event.response?.usage) {+ this.usage = readUsage(event.response.usage, this.usage, true);+ }+ // A wrapper still held when the response is cut short never got its+ // arguments judged: degenerate by definition.+ const pending = this.heldWrappers.values().next().value;+ if (pending) {+ return {+ stop: this.degenerate("incomplete", (pending.doneArgs ?? pending.arguments).length),+ };+ }+ return undefined;+ }++ /** The behavior layer's one chance to rewrite a buffered call. A throwing rule changes nothing. */+ private repairBufferedCall(name: string, args: string): string {+ if (this.ctx.shouldBufferTool?.(name) !== true) return args;+ try {+ const repaired = this.ctx.onToolCall?.(name, args);+ if (typeof repaired === "string" && repaired !== args) {+ log(`[ResponsesSSE] tool call repaired: ${name}`);+ return repaired;+ }+ } catch (err) {+ // A failing rule must never corrupt the stream — emit the model's+ // original arguments and carry on.+ log(`[ResponsesSSE] onToolCall threw for ${name}: ${err}`);+ }+ return args;+ }++ /**+ * Emit a valid wrapper's entries as ordinary tool_use blocks, one complete+ * argument delta each (a buffered tool goes through onToolCall first). The+ * wrapper's reasoning is remembered under the FIRST expanded id only, so the+ * next request replays it exactly once, before that call.+ */+ private emitExpandedWrapper(held: HeldWrapper, calls: ParallelWrapperCall[]): void {+ this.closeReasoning();+ this.closeText();+ calls.forEach((call, k) => {+ const id = `${held.claudeBaseId}_p${k}`;+ const args = this.repairBufferedCall(call.name, call.arguments);+ const index = this.sink.nextIndex();+ this.sink.startToolBlock(index, id, call.name);+ this.sink.delta(index, { type: "input_json_delta", partial_json: args });+ this.sink.markToolArgsComplete(index);+ this.sink.stopToolBlock(index);+ if (k === 0 && held.reasoning.length > 0) {+ rememberReasoningForCall(id, held.reasoning);+ }+ });+ log(`[ResponsesSSE] parallel wrapper expanded into ${calls.length} tool_use block(s)`);+ }++ /**+ * At `output_item.done` of a non-buffered call, send whatever part of the+ * final arguments the deltas did not carry. The Codex backend sends every+ * call of a multi-call turn with ZERO argument deltas: the arguments exist+ * only in `function_call_arguments.done` and the done item, so forwarding+ * from deltas alone handed Claude Code `{}` and it answered+ * `InputValidationError: ... The required parameter 'file_path' is missing`.+ * A native `openai@` call streams every byte as deltas, and its final string+ * equals what was forwarded, so nothing more goes out for it.+ */+ private emitUnforwardedArguments(fnCall: FnCall, final: string, source: "done" | "item"): void {+ const emit = (partial: string) => {+ this.sink.delta(fnCall.index, { type: "input_json_delta", partial_json: partial });+ fnCall.forwardedBytes += partial.length;+ };+ if (fnCall.forwardedBytes === 0) {+ if (final) {+ emit(final);+ log(+ `[ResponsesSSE] zero-delta function_call ${fnCall.name}: emitted ${final.length} bytes from ${source}`+ );+ }+ return;+ }+ const forwarded = fnCall.arguments;+ if (final === forwarded) return;+ if (final.startsWith(forwarded)) {+ const suffix = final.slice(forwarded.length);+ emit(suffix);+ log(+ `[ResponsesSSE] function_call ${fnCall.name}: emitted ${suffix.length}-byte suffix the deltas did not carry`+ );+ return;+ }+ log(`[ResponsesSSE] done arguments diverge from streamed deltas for ${fnCall.name}`);+ }++ private closeReasoning(): void {+ if (this.reasoningIdx >= 0) {+ this.sink.stopBlock(this.reasoningIdx);+ this.reasoningIdx = -1;+ }+ }++ private closeText(): void {+ if (this.textIdx >= 0) {+ this.sink.stopBlock(this.textIdx);+ this.textIdx = -1;+ }+ }++ private closeTools(): void {+ for (const fnCall of this.openToolBlocks) {+ // A buffered call that never reached output_item.done (truncated or+ // failed stream) still has to emit what it accumulated. Withholding it+ // would turn "partial arguments" into "no arguments", which is strictly+ // worse — the non-buffered path would already have streamed the same+ // fragments. What the client then DOES with malformed JSON is decided by+ // how the turn ends: only an `error` event reliably stops Claude Code+ // executing the fragment. The block stays not-ARGS-COMPLETE on the sink.+ const accumulated = fnCall.doneArgs ?? fnCall.arguments;+ if (fnCall.buffered && accumulated) {+ this.sink.delta(fnCall.index, { type: "input_json_delta", partial_json: accumulated });+ }+ this.sink.stopToolBlock(fnCall.index);+ }+ this.openToolBlocks.clear();+ }++ private closeAll(): void {+ this.closeReasoning();+ this.closeText();+ this.closeTools();+ }+}++/**+ * Parse one upstream Responses body into Claude SSE on `ctx.sink` and report+ * how the leg ended. Never throws; never writes a message ending.+ */+export function parseResponsesLeg(+ response: Response,+ ctx: ResponsesLegContext+): Promise<LegOutcome> {+ return new ResponsesLeg(ctx).run(response);+}diff --git a/packages/cli/src/handlers/shared/stream-parsers/responses/responses-turn.ts b/packages/cli/src/handlers/shared/stream-parsers/responses/responses-turn.tsnew file mode 100644index 00000000..04c6992c--- /dev/null+++ b/packages/cli/src/handlers/shared/stream-parsers/responses/responses-turn.ts@@ -0,0 +1,202 @@+/**+ * The turn driver: one downstream Claude message, built from one or more+ * upstream Responses legs.+ *+ * The leg parser (`responses-leg.ts`) turns one upstream body into Claude SSE+ * and reports how it ended; this decides how the MESSAGE ends: the stop_reason,+ * the in-band error text tail, or an SSE `error`, and fires the usage callback+ * that records the request's stats exactly once.+ */++import { log } from "../../../../logger.js";+import type { ClaudeSseSink } from "./claude-sse-sink.js";+import {+ type LegOutcome,+ type ResponsesLegContext,+ type Usage,+ parseResponsesLeg,+} from "./responses-leg.js";++export interface ResponsesTurnOptions extends Omit<ResponsesLegContext, "sink"> {+ /**+ * Real per-provider context window (tokens) for the model on THIS backend.+ * Used only to make the overflow message specific; omit/0 → left out.+ */+ contextWindow?: number;+ /** An in-stream API error (it rides an HTTP 200, invisible to status). */+ onApiError?: (code: string, message: string) => void;+ /** Fires the request's stats record; called at most once per turn. */+ onTokenUpdate?: (input: number, output: number) => void;+ onTurnEnd?: () => void;+}++/** The in-band text for an in-stream API error; context overflow gets an actionable message. */+function apiErrorText(code: string, message: string, opts: ResponsesTurnOptions): string {+ // Context-overflow gets an actionable message (with the real per-backend cap+ // when known) instead of the bare error code — otherwise the user just sees a+ // cryptic `context_length_exceeded` and a stuck session (/compact re-sends the+ // same oversized input).+ const isCtxOverflow =+ code === "context_length_exceeded" ||+ /context (length|window)|exceeds? the context|too long|maximum context/i.test(message);+ if (!isCtxOverflow) return `\n\n[API Error: ${code} ${message}]`;+ const cap =+ opts.contextWindow && opts.contextWindow > 0+ ? ` ~${Math.round(opts.contextWindow / 1000)}K tokens`+ : "";+ return (+ `\n\n[Context limit reached] This model's backend enforces a smaller context window${cap} than its API spec. ` ++ "Run /clear to start fresh (/compact will also fail — it re-sends the full conversation), " ++ `or route the model via \`oai@${opts.modelName}\` to use the full-size window.`+ );+}++/**+ * The stop_reason for a turn whose last leg completed.+ *+ * A truncated turn must NOT be reported as a finished tool call. OpenAI emits+ * the partial function_call arguments it managed to produce, so "tool_use"+ * makes the client execute a tool with malformed JSON (InputValidationError).+ * Anthropic's contract for a cut-off turn is stop_reason "max_tokens", which is+ * the honest label here.+ *+ * KNOWN GAP: "max_tokens" does not actually stop Claude Code executing the+ * partial block. Verified against 2.1.217 (passflow session, 2026-07-22, six+ * days after v7.12.7 shipped this): the client ran the truncated Write and+ * reported InputValidationError anyway. A mid-stream socket failure uses an+ * `error` event, which does stop it — but that is only safe there because a+ * dead socket is transient. max_output_tokens is deterministic, so an error+ * event would make the client retry a request that truncates again. Capping+ * the budget is the real fix and the codex backend rejects max_output_tokens+ * ("Unsupported parameter"), so the label stays honest and the execution stays+ * unprevented.+ */+function stopReasonFor(incomplete: string | undefined, hasToolUse: boolean): string {+ if (incomplete) return incomplete === "content_filter" ? "refusal" : "max_tokens";+ return hasToolUse ? "tool_use" : "end_turn";+}++class ResponsesTurn {+ private usage: Usage | undefined;+ private tokensReported = false;++ constructor(+ private readonly sink: ClaudeSseSink,+ private readonly opts: ResponsesTurnOptions+ ) {}++ private get wireUsage(): { input_tokens: number; output_tokens: number } {+ return {+ input_tokens: this.usage?.inputTokens ?? 0,+ output_tokens: this.usage?.outputTokens ?? 0,+ };+ }++ /**+ * Hand the turn's usage to the caller, which fires the request's stats+ * record. Once. After a client disconnect only if a leg had reported usage:+ * what was billed is billed, but a turn cut off before any usage arrived has+ * no figure worth recording.+ */+ private reportTokens(): void {+ if (this.tokensReported) return;+ this.tokensReported = true;+ if (this.sink.isCancelled && !this.usage) {+ log("[ResponsesSSE] client disconnected before usage arrived; no token update");+ return;+ }+ this.opts.onTokenUpdate?.(this.usage?.inputTokens ?? 0, this.usage?.outputTokens ?? 0);+ }++ async run(firstResponse: Response): Promise<void> {+ try {+ const outcome = await parseResponsesLeg(firstResponse, { ...this.opts, sink: this.sink });+ if ("usage" in outcome && outcome.usage) this.usage = outcome.usage;+ await this.finish(outcome);+ } catch (error) {+ // Only a throwing callback can land here; the leg itself never throws.+ log(`[ResponsesSSE] Stream error: ${error}`);+ } finally {+ this.sink.close();+ }+ }++ private async finish(outcome: LegOutcome): Promise<void> {+ switch (outcome.kind) {+ case "done": {+ const stopReason = stopReasonFor(outcome.incomplete, this.sink.hasToolUse);+ if (outcome.incomplete) {+ log(+ `[ResponsesSSE] Truncated response (${outcome.incomplete}) → stop_reason=${stopReason}`+ );+ }+ this.sink.endMessage(stopReason, this.wireUsage);+ this.reportTokens();+ if (this.opts.middlewareManager) {+ await this.opts.middlewareManager.afterStreamComplete(+ this.opts.modelName,+ this.opts.streamMetadata+ );+ }+ this.opts.onTurnEnd?.();+ return;+ }+ case "api-error":+ // Signal the terminal error so the caller records this turn as a+ // failure (the error rides an HTTP 200 stream, invisible to status).+ this.opts.onApiError?.(outcome.code, outcome.message);+ this.sink.endWithText(+ apiErrorText(outcome.code, outcome.message, this.opts),+ this.wireUsage+ );+ this.reportTokens();+ return;+ case "stream-error":+ // A tool block that was open when the socket died had its argument JSON+ // cut mid-object, and `end_turn` makes Claude Code run the tool on it:+ // InputValidationError: Write was called with input that could not+ // be parsed as JSON. You sent (first 200 of 9437 bytes): {"file_pa…+ // `max_tokens` does not rescue it either (Claude Code 2.1.217 ran a+ // max_tokens-terminated call anyway). Only an `error` event ends the+ // message with no completed tool_use, and it is the honest report — the+ // turn did fail. devin-connect ends a mid-stream fault the same way.+ // With no tool call in flight the inline text keeps partial prose visible.+ if (outcome.openToolBlock) {+ log("[ResponsesSSE] tool arguments cut off mid-stream → error event");+ this.sink.endWithError(`Stream error: ${outcome.error}`);+ } else {+ this.sink.endWithText(`\n\n[Stream error: ${outcome.error}]`, this.wireUsage);+ }+ this.reportTokens();+ return;+ case "degenerate-wrapper":+ // Never shown to Claude Code: the error event makes it discard the+ // message and retry the turn, and no tool_use of it runs.+ log("[ResponsesSSE] degenerate parallel wrapper → error event");+ this.sink.endWithError(+ `degenerate parallel tool wrapper (${outcome.reason}, ${outcome.bytes} bytes)`+ );+ this.reportTokens();+ return;+ case "stall":+ this.sink.endWithError(`no output for ${Math.round(outcome.afterMs / 1000)} s`);+ this.reportTokens();+ return;+ case "cancelled":+ this.reportTokens();+ return;+ }+ }+}++/**+ * Drive one downstream Claude message from `firstResponse`. Never throws; the+ * sink is closed when this resolves.+ */+export function runResponsesTurn(+ sink: ClaudeSseSink,+ firstResponse: Response,+ opts: ResponsesTurnOptions+): Promise<void> {+ return new ResponsesTurn(sink, opts).run(firstResponse);+}