Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(adapters): retry a degenerate parallel wrapper within the same turn
Jack Rudenko48e3fc3c1b7c
diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex f6b0cf28..a19608eb 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -68,7 +68,7 @@ import {noteTargetReachable,uiLeaseValid,} from "../recovery/coordinator.js";-import { resolveRecoveryEnabled } from "../recovery/settings.js";+import { resolveRecoveryEnabled, resolveTier1DeadlineMs } from "../recovery/settings.js";import {type OpenAIImageBlock,type VisionProxyAuthHeaders,@@ -104,12 +104,16 @@ import {isContextOverflowError,isRequestShapeError,} from "./shared/request-shape.js";+import { type LegAuthBinding, createLegIssuer } from "./shared/responses-leg-issuer.js";import { sniffResponsesStreamHead } from "./shared/stream-head-sniffer.js";import { createAnthropicPassthroughStream } from "./shared/stream-parsers/anthropic-sse.js";import { createDevinConnectStream } from "./shared/stream-parsers/devin-connect.js";import { createGeminiSseStream } from "./shared/stream-parsers/gemini-sse.js";import { createOllamaJsonlStream } from "./shared/stream-parsers/ollama-jsonl.js";-import { createResponsesStreamHandler } from "./shared/stream-parsers/openai-responses-sse.js";+import {+ type ResponsesRetryOptions,+ createResponsesStreamHandler,+} from "./shared/stream-parsers/openai-responses-sse.js";import { createStreamingResponseHandler } from "./shared/stream-parsers/openai-sse.js";import { TokenTracker, type UsageCacheDetail } from "./shared/token-tracker.js";import {@@ -131,6 +135,32 @@ import { captureUpstreamError } from "./shared/upstream-error-capture.js";*/const STREAM_RETRY_DELAYS_MS = [3_000, 15_000, 30_000];+/** What `handle()` builds for a Responses turn and `handleStream` hands the parser. */+interface ResponsesTurnWiring {+ retry: ResponsesRetryOptions;+ onTurnSummary: (s: { legs: number; legRetries: number }) => void;+}++/**+ * Wait `ms`, or less if `signal` aborts first. Resolves `true` when it was+ * aborted. A retry leg passes its turn signal so a client that disconnects+ * during a 7b backoff does not hold the leg open for up to 30 s.+ */+function sleepUnlessAborted(ms: number, signal?: AbortSignal): Promise<boolean> {+ if (signal?.aborted) return Promise.resolve(true);+ return new Promise<boolean>((resolve) => {+ const onAbort = () => {+ clearTimeout(timer);+ resolve(true);+ };+ const timer = setTimeout(() => {+ signal?.removeEventListener("abort", onAbort);+ resolve(false);+ }, ms);+ signal?.addEventListener("abort", onAbort, { once: true });+ });+}+/*** One request's running account of what network recovery cost it. Mutable, and* mutated only by `recoverConnection`.@@ -2179,6 +2209,66 @@ export class ComposedHandler implements ModelHandler {// parser reports them via onApiError; capture it here so the turn is recorded// as a failure, not a success. Per-request local — safe under concurrency.let streamApiError: { code: string; message: string } | null = null;++ // Legs 2..n of a Responses turn: a degenerate `parallel` wrapper is retried+ // inside the same downstream message (responses-turn.ts). Built from THIS+ // request's header builder, body and transport hooks, so a leg is the+ // primary fetch again, with its own ceiling and the turn's abort signal.+ // Per-request locals — safe under concurrency on a shared handler.+ let legRetries = 0;+ let responsesTurn: ResponsesTurnWiring | undefined;+ if (this.resolveStreamFormat() === "openai-responses-sse") {+ // No transport returns a binding yet: legs use the no-binding path, which+ // is exactly the primary fetch's.+ let legBinding: LegAuthBinding | undefined;+ const refreshAuth = this.provider.refreshAuth?.bind(this.provider);+ const forceRefreshAuth = this.provider.forceRefreshAuth?.bind(this.provider);+ const issueLeg = createLegIssuer({+ providerDisplayName: this.provider.displayName,+ getBinding: () => legBinding,+ setBinding: (b) => {+ legBinding = b;+ },+ refreshAuth: refreshAuth+ ? async () => {+ await refreshAuth();+ return undefined;+ }+ : undefined,+ forceRefreshAuth: forceRefreshAuth+ ? async () => {+ await forceRefreshAuth();+ return undefined;+ }+ : undefined,+ getEndpoint: () => this.provider.getEndpoint(this.targetModel),+ fetchHeaders: () => fetchHeaders(),+ // `requestPayload` as it stands now: parameter recovery may have+ // dropped fields, and a leg re-sends the body that was accepted.+ serializeBody: (body) => {+ const b = body ?? requestPayload;+ const s = this.provider.serializeBody?.(b);+ return {+ body: s?.body ?? JSON.stringify(b),+ contentType: s?.contentType ?? "application/json",+ };+ },+ getRequestInit: () => (this.provider.getRequestInit?.() || {}) as Record<string, unknown>,+ enqueueRequest: this.provider.enqueueRequest+ ? (fn, o) => this.provider.enqueueRequest!(fn, o)+ : undefined,+ settleStreamHead: (res, reissue, signal) =>+ this.settleResponsesStreamHead(res, reissue, signal),+ legDeadlineAt: () => recoveryClock().now() + resolveTier1DeadlineMs(),+ });+ responsesTurn = {+ retry: { issueLeg },+ onTurnSummary: (s) => {+ legRetries = s.legRetries;+ },+ };+ }+const onStreamComplete = () => {try {const isFreeModel = this.tokenTracker.getTotalCost() === 0;@@ -2201,6 +2291,8 @@ export class ComposedHandler implements ModelHandler {fallback_attempts: fallbackMeta?.attempts,invocation_mode: this.options.invocationMode ?? "auto-route",...this.recoveryStats(recoveryTally),+ // Absent on a turn that needed no retry, like the recovery fields.+ ...(legRetries > 0 ? { leg_retries: legRetries } : {}),});} catch {// Stats must never crash claudish@@ -2226,7 +2318,8 @@ export class ComposedHandler implements ModelHandler {(code, message) => {streamApiError = { code, message };},- behaviorSession+ behaviorSession,+ responsesTurn);// A client that did not ask for a stream gets the single JSON message the@@ -2257,7 +2350,9 @@ export class ComposedHandler implements ModelHandler {*/private async settleResponsesStreamHead(initial: Response,- reissue: () => Promise<Response>+ reissue: () => Promise<Response>,+ /** A retry leg's turn signal: an abort ends the backoff wait at once. */+ signal?: AbortSignal): Promise<| { kind: "ok"; response: Response }| { kind: "exhausted"; code: string; message: string; attempts: number; unreachable?: true }@@ -2286,7 +2381,9 @@ export class ComposedHandler implements ModelHandler {`[${this.provider.displayName}] in-stream ${verdict.code} before any output — ` +`retry ${attempt + 1}/${STREAM_RETRY_DELAYS_MS.length} in ${delayMs / 1000}s`);- await new Promise((resolve) => setTimeout(resolve, delayMs));+ if (await sleepUnlessAborted(delayMs, signal)) {+ return { kind: "exhausted", code: verdict.code, message: "aborted", attempts: attempt };+ }let next: Response;try {@@ -2473,7 +2570,8 @@ export class ComposedHandler implements ModelHandler {toolNameMap?: Map<string, string>,onComplete?: () => void,onApiError?: (code: string, message: string) => void,- behaviorSession?: BehaviorSession+ behaviorSession?: BehaviorSession,+ responsesTurn?: ResponsesTurnWiring): Response {// Local mutable copy so we can null it out after firing (prevents double-firing)// without reassigning the function parameter.@@ -2588,6 +2686,12 @@ export class ComposedHandler implements ModelHandler {onAssistantText: (text, kind) => behaviorSession?.observeText(text, kind),onToolCallObserved: observeToolCall,onTurnEnd: () => behaviorSession?.finishTurn(),+ retry: responsesTurn?.retry,+ // Earlier legs of a retried turn: cost only, before the stats snapshot+ // that onTokenUpdate fires.+ onExtraBilledInput: (input, detail) =>+ this.tokenTracker.addBilledInputTokens(input, detail),+ onTurnSummary: responsesTurn?.onTurnSummary,});case "anthropic-sse":diff --git a/packages/cli/src/handlers/shared/responses-leg-issuer.ts b/packages/cli/src/handlers/shared/responses-leg-issuer.tsnew file mode 100644index 00000000..7bd95794--- /dev/null+++ b/packages/cli/src/handlers/shared/responses-leg-issuer.ts@@ -0,0 +1,201 @@+/**+ * Issue upstream legs 2..n of one Responses turn.+ *+ * The turn driver (`stream-parsers/responses/responses-turn.ts`) retries a+ * stalled or degenerate leg INSIDE the same downstream message, after the 200+ * and `message_start` were already flushed. So a leg cannot answer with a+ * status, cannot start a network-recovery hold, and must never move to another+ * credential silo: everything that goes wrong here ends as a `LegResponse`+ * error, which the driver turns into an SSE `error` event (Claude Code then+ * discards the message and retries the turn). No status is invented.+ *+ * Per leg (the contract `ai-docs/architecture/adapters.md` records):+ * 1. `refreshAuth()`; when the transport returns a binding and its arm or+ * account differs from the turn's binding, stop ("Codex sign-in changed+ * during the turn") rather than continue on another credential silo. A+ * transport that returns nothing keeps today's no-binding path;+ * 2. endpoint and headers from that binding, wire headers merged;+ * 3. its own ceiling `deadlineClamp(now + tier-1 deadline)`, merged with the+ * turn's signal and disarmed at headers;+ * 4. 401 → `forceRefreshAuth()` (same binding check) + fresh headers + one+ * re-fetch;+ * 5. any other non-200 → error carrying the upstream status and the first 500+ * bytes of the body; no parameter recovery on legs;+ * 6. 200 → the 7b stream-head settle (in-stream overload backoff);+ * 7. a throw from any network touch → classified for the log line only, then+ * error; an abort from the turn's signal ends silently (the client is gone).+ */++import { log } from "../../logger.js";+import { classifyConnectionError } from "./connection-error.js";+import { deadlineClamp, mergeSignalIntoInit } from "./transient-retry.js";++/** What `issueLeg` hands the turn driver. */+export type LegResponse =+ | { kind: "ok"; response: Response; headersAt: number }+ | { kind: "error"; message: string }+ | { kind: "aborted" };++/**+ * The part of a request's auth binding a leg checks: the credential arm and+ * the account. Transports that return nothing from `refreshAuth` have no+ * binding, and their legs use the no-binding path (identical to the primary+ * fetch).+ */+export interface LegAuthBinding {+ auth?: { arm?: string } | null;+ accountKey?: string;+}++type StreamHeadSettle =+ | { kind: "ok"; response: Response }+ | { kind: "exhausted"; code: string; message: string; attempts: number; unreachable?: true };++export interface LegIssuerDeps {+ providerDisplayName: string;+ /** The turn's current binding (undefined on the no-binding path). */+ getBinding: () => LegAuthBinding | undefined;+ setBinding: (binding: LegAuthBinding) => void;+ refreshAuth?: () => Promise<LegAuthBinding | undefined>;+ forceRefreshAuth?: () => Promise<LegAuthBinding | undefined>;+ getEndpoint: (binding: LegAuthBinding | undefined) => string;+ /** The request's own header builder (wire headers merged). */+ fetchHeaders: (binding: LegAuthBinding | undefined) => Promise<Record<string, string>>;+ /** The serialized body for a leg: `undefined` → the primary request's bytes. */+ serializeBody: (body: unknown | undefined) => { body: BodyInit; contentType: string };+ getRequestInit?: () => Record<string, unknown>;+ enqueueRequest?: (+ fn: () => Promise<Response>,+ opts?: { signal?: AbortSignal }+ ) => Promise<Response>;+ /** The 7b stream-head settle, abortable by the turn's signal. */+ settleStreamHead: (+ response: Response,+ reissue: () => Promise<Response>,+ signal: AbortSignal+ ) => Promise<StreamHeadSettle>;+ /** The absolute ceiling for one leg's connect-and-headers, on `deadlineClamp`'s clock. */+ legDeadlineAt: () => number;+ /** Wall-clock stamp for `headersAt` (the stall guard's clock). Default `Date.now`. */+ now?: () => number;+ /** Injection point for tests; default the global `fetch`. */+ fetchImpl?: typeof fetch;+}++/** Thrown inside the issuer when the credential silo changed; never escapes it. */+class BindingChanged extends Error {}++function assertSameSilo(turn: LegAuthBinding | undefined, next: LegAuthBinding): void {+ if (!turn) return;+ const armChanged = (turn.auth?.arm ?? undefined) !== (next.auth?.arm ?? undefined);+ const accountChanged = turn.accountKey !== next.accountKey;+ if (armChanged || accountChanged) throw new BindingChanged();+}++/**+ * Build `issueLeg(body, signal)` for one request. Never throws; every failure+ * is a `LegResponse`.+ */+export function createLegIssuer(+ deps: LegIssuerDeps+): (body: unknown | undefined, signal: AbortSignal) => Promise<LegResponse> {+ const now = deps.now ?? Date.now;+ const doFetch = deps.fetchImpl ?? fetch;+ let legNumber = 1;++ const adoptBinding = (next: LegAuthBinding | undefined) => {+ if (!next) return;+ assertSameSilo(deps.getBinding(), next);+ deps.setBinding(next);+ };++ return async (body, signal) => {+ legNumber++;+ const leg = legNumber;+ if (signal.aborted) return { kind: "aborted" };+ try {+ if (deps.refreshAuth) adoptBinding(await deps.refreshAuth());+ let binding = deps.getBinding();+ const endpoint = deps.getEndpoint(binding);+ const serialized = deps.serializeBody(body);++ // One attempt: its own ceiling, composed with the turn's signal, disarmed+ // the instant headers arrive so a live body is never cut.+ let headersAt = 0;+ const send = async (headers: Record<string, string>): Promise<Response> => {+ const clamp = deadlineClamp(deps.legDeadlineAt());+ const sig = clamp.signal ? AbortSignal.any([clamp.signal, signal]) : signal;+ const attempt = () =>+ doFetch(+ endpoint,+ mergeSignalIntoInit(+ {+ method: "POST",+ headers: { ...headers, "Content-Type": serialized.contentType },+ body: serialized.body,+ ...(deps.getRequestInit?.() || {}),+ },+ sig+ )+ );+ try {+ const response = deps.enqueueRequest+ ? await deps.enqueueRequest(attempt, { signal: sig })+ : await attempt();+ headersAt = now();+ return response;+ } finally {+ clamp.disarm();+ }+ };++ let headers = await deps.fetchHeaders(binding);+ log(`[ResponsesTurn] issuing retry leg ${leg}: ${endpoint}`);+ let response = await send(headers);++ // The RAW upstream status of this leg's own fetch: no remap has happened+ // on this path, so there is nothing for extractUpstreamStatus to recover.+ if (response.status === 401 && deps.forceRefreshAuth) {+ await response.body?.cancel().catch(() => {});+ adoptBinding(await deps.forceRefreshAuth());+ binding = deps.getBinding();+ headers = await deps.fetchHeaders(binding);+ response = await send(headers);+ }++ if (!response.ok) {+ const text = await response.text().catch(() => "");+ const message = `HTTP ${response.status} on retry leg ${leg}: ${text.slice(0, 500)}`;+ log(`[ResponsesTurn] ${message}`);+ return { kind: "error", message };+ }++ const settled = await deps.settleStreamHead(response, () => send(headers), signal);+ if (signal.aborted) {+ if (settled.kind === "ok") await settled.response.body?.cancel().catch(() => {});+ return { kind: "aborted" };+ }+ if (settled.kind === "exhausted") {+ const message = `${deps.providerDisplayName} is overloaded upstream on retry leg ${leg} (${settled.code}): ${settled.message}`;+ log(`[ResponsesTurn] ${message}`);+ return { kind: "error", message };+ }+ return { kind: "ok", response: settled.response, headersAt };+ } catch (err) {+ if (signal.aborted) return { kind: "aborted" };+ if (err instanceof BindingChanged) {+ log(`[ResponsesTurn] Codex sign-in changed during the turn (retry leg ${leg})`);+ return { kind: "error", message: "Codex sign-in changed during the turn" };+ }+ // Classified for the log only: after the flush there is no status to+ // choose and no recovery hold to start.+ const conn = classifyConnectionError(err);+ const what = conn ? `${conn.kind} (${conn.code})` : "error";+ log(`[ResponsesTurn] retry leg ${leg} failed: ${what}: ${err}`);+ return {+ kind: "error",+ message: `retry leg ${leg} could not reach ${deps.providerDisplayName}: ${err}`,+ };+ }+ };+}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 bc659a13..bf45e1c2 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@@ -12,15 +12,31 @@import type { Context } from "hono";import { wrapAnthropicError } from "../anthropic-error.js";+import type { UsageCacheDetail } from "../token-tracker.js";import { ClaudeSseSink } from "./responses/claude-sse-sink.js";-import { runResponsesTurn } from "./responses/responses-turn.js";+import { type ResponsesRetryOptions, runResponsesTurn } from "./responses/responses-turn.js";++export type { ResponsesRetryOptions } from "./responses/responses-turn.js";export function createResponsesStreamHandler(c: Context,response: Response,opts: {modelName: string;+ /**+ * Fires the request's stats record, LAST at turn end: the final leg's input+ * (the context figure) and every leg's output.+ */onTokenUpdate?: (input: number, output: number) => void;+ /**+ * Retry a degenerate leg inside the same downstream message (see+ * responses/responses-turn.ts). Absent ⇒ one leg per turn, exactly as before.+ */+ retry?: ResponsesRetryOptions;+ /** Fires FIRST at turn end: input of earlier legs that reported usage (cost only). */+ onExtraBilledInput?: (inputTokens: number, detail?: UsageCacheDetail) => void;+ /** Fires after onExtraBilledInput, before onTokenUpdate. */+ onTurnSummary?: (s: { legs: number; legRetries: number }) => void;toolNameMap?: Map<string, string>;/*** Real per-provider context window (tokens) for the model on THIS backend,@@ -110,6 +126,9 @@ export function createResponsesStreamHandler(onApiError: opts.onApiError,onTokenUpdate: opts.onTokenUpdate,onTurnEnd: opts.onTurnEnd,+ retry: opts.retry,+ onExtraBilledInput: opts.onExtraBilledInput,+ onTurnSummary: opts.onTurnSummary,});},// Downstream went away (client disconnect, abort, or timeout). Thediff --git a/packages/cli/src/handlers/shared/stream-parsers/responses/responses-leg.ts b/packages/cli/src/handlers/shared/stream-parsers/responses/responses-leg.tsindex 2ba596d5..7bbe991b 100644--- a/packages/cli/src/handlers/shared/stream-parsers/responses/responses-leg.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/responses/responses-leg.ts@@ -199,7 +199,8 @@ class ResponsesLeg {}if (stop) {this.closeAll();- reader.cancel().catch(() => {});+ // Awaited: the next leg is never issued while this stream is open.+ await reader.cancel().catch(() => {});return stop.stop;}}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.tsindex 04c6992c..bb6fa9d4 100644--- a/packages/cli/src/handlers/shared/stream-parsers/responses/responses-turn.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/responses/responses-turn.ts@@ -6,9 +6,59 @@* 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.+ *+ * ── RETRY WITHIN THE TURN ────────────────────────────────────────────────────+ *+ * About 1% of ChatGPT Codex turns end with a degenerate `parallel` wrapper+ * (parallel-wrapper.ts). When the caller passes `retry`, such a leg is retried+ * by issuing the same body again while the downstream message stays open; the+ * next leg continues at the next block index. A leg is issued only while no+ * tool_use has been emitted in this message:+ *+ * | state of the message when the trigger fires | action |+ * |----------------------------------------------------|---------------------------|+ * | message_start + pings, or closed text/thinking only | retry |+ * | ≥ 1 tool_use stopped with its arguments, none cut | no retry: end `tool_use` |+ * | off (re-emitting could run a side-effecting Bash | for the stopped calls |+ * | twice) | |+ * | any tool_use started but cut off | no retry: SSE `error` |+ * | retries exhausted | SSE `error` |+ *+ * NOT done in 7b (the status is already flushed), NOT in FallbackHandler (a+ * model fault must never move a subscription user onto a metered hop), NOT in+ * the transport. After the flush every failure ends with an SSE `error`.*/+/** Retries per leg position: 3 attempts in all. */+export const MAX_LEG_RETRIES = 2;++type RetryDecision =+ | { action: "finish" }+ | { action: "retry" }+ | { action: "end-tool-use" }+ | { action: "error"; message: string };++/** The trigger in words, for the log line and the exhaustion error. */+function triggerLabel(outcome: LegOutcome): string {+ if (outcome.kind === "stall") return `stall ${Math.round(outcome.afterMs / 1000)}s`;+ if (outcome.kind === "degenerate-wrapper") return `degenerate ${outcome.bytes}B`;+ return outcome.kind;+}++function exhaustedMessage(outcome: LegOutcome, attempts: number): string {+ if (outcome.kind === "stall") {+ return `no output for ${Math.round(outcome.afterMs / 1000)} s after ${attempts} attempts`;+ }+ return `degenerate parallel tool wrapper after ${attempts} attempts`;+}++function sum(values: number[]): number {+ return values.reduce((a, b) => a + b, 0);+}+import { log } from "../../../../logger.js";+import type { LegResponse } from "../../responses-leg-issuer.js";+import type { UsageCacheDetail } from "../../token-tracker.js";import type { ClaudeSseSink } from "./claude-sse-sink.js";import {type LegOutcome,@@ -25,9 +75,29 @@ export interface ResponsesTurnOptions extends Omit<ResponsesLegContext, "sink">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. */+ /**+ * Fires the request's stats record; called at most once per turn, LAST, with+ * the final leg's input (the context figure) and the output of every leg.+ */onTokenUpdate?: (input: number, output: number) => void;onTurnEnd?: () => void;+ /** Absent ⇒ one leg per turn, exactly as before retries existed. */+ retry?: ResponsesRetryOptions;+ /**+ * Fires FIRST at turn end, only when earlier legs of a retried turn reported+ * usage: their summed input (and cache detail). Each was a separate upstream+ * request the provider billed in full; nothing else will ever charge it.+ */+ onExtraBilledInput?: (inputTokens: number, detail?: UsageCacheDetail) => void;+ /** Fires after onExtraBilledInput and before onTokenUpdate. */+ onTurnSummary?: (s: { legs: number; legRetries: number }) => void;+}++export interface ResponsesRetryOptions {+ /** Issue leg 2..n of this turn: `undefined` body ⇒ the primary request's body. */+ issueLeg: (body: unknown | undefined, signal: AbortSignal) => Promise<LegResponse>;+ /** Retries per leg position. Default {@link MAX_LEG_RETRIES}. */+ maxLegRetries?: number;}/** The in-band text for an in-stream API error; context overflow gets an actionable message. */@@ -77,42 +147,93 @@ function stopReasonFor(incomplete: string | undefined, hasToolUse: boolean): str}class ResponsesTurn {- private usage: Usage | undefined;- private tokensReported = false;+ /** One entry per leg, in order; undefined for a leg that reported no usage. */+ private readonly legUsages: Array<Usage | undefined> = [];+ private legRetries = 0;+ private usageReported = false;constructor(private readonly sink: ClaudeSseSink,private readonly opts: ResponsesTurnOptions) {}+ private get lastUsage(): Usage | undefined {+ return this.legUsages[this.legUsages.length - 1];+ }++ private get totalOutputTokens(): number {+ return sum(this.legUsages.map((u) => u?.outputTokens ?? 0));+ }++ /** Context figure = the final leg's input; output = every leg's output. */private get wireUsage(): { input_tokens: number; output_tokens: number } {return {- input_tokens: this.usage?.inputTokens ?? 0,- output_tokens: this.usage?.outputTokens ?? 0,+ input_tokens: this.lastUsage?.inputTokens ?? 0,+ output_tokens: this.totalOutputTokens,};}/**- * 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:+ * Report the turn's usage, once, in this order:+ * 1. `onExtraBilledInput` with the input of EARLIER legs that reported usage;+ * 2. `onTurnSummary`;+ * 3. `onTokenUpdate(final leg's input, every leg's output)`, which fires the+ * request's one stats record — so that record already holds 1 and 2.+ * After a client disconnect nothing fires unless 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) {+ private reportUsage(): void {+ if (this.usageReported) return;+ this.usageReported = true;+ const reported = this.legUsages.filter((u): u is Usage => u !== undefined);+ if (this.sink.isCancelled && reported.length === 0) {log("[ResponsesSSE] client disconnected before usage arrived; no token update");return;}- this.opts.onTokenUpdate?.(this.usage?.inputTokens ?? 0, this.usage?.outputTokens ?? 0);+ const earlier = this.legUsages.slice(0, -1).filter((u): u is Usage => u !== undefined);+ const extraInput = sum(earlier.map((u) => u.inputTokens));+ if (extraInput > 0) {+ const cacheRead = sum(earlier.map((u) => u.cacheDetail?.cacheReadTokens ?? 0));+ const cacheCreation = sum(earlier.map((u) => u.cacheDetail?.cacheCreationTokens ?? 0));+ this.opts.onExtraBilledInput?.(+ extraInput,+ cacheRead > 0 || cacheCreation > 0+ ? { cacheReadTokens: cacheRead, cacheCreationTokens: cacheCreation }+ : undefined+ );+ }+ this.opts.onTurnSummary?.({ legs: this.legUsages.length, legRetries: this.legRetries });+ this.opts.onTokenUpdate?.(this.lastUsage?.inputTokens ?? 0, this.totalOutputTokens);}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);+ let response = firstResponse;+ while (true) {+ const outcome = await parseResponsesLeg(response, { ...this.opts, sink: this.sink });+ this.legUsages.push("usage" in outcome ? outcome.usage : undefined);+ const decision = this.retryDecision(outcome);+ if (decision.action === "finish") {+ await this.finish(outcome);+ return;+ }+ if (decision.action === "end-tool-use") {+ // The calls already stopped stand; the trigger's leg is dropped.+ log(`[ResponsesTurn] ${triggerLabel(outcome)} after tool_use blocks — ending tool_use`);+ await this.finishCompleted("tool_use");+ return;+ }+ if (decision.action === "error") {+ log(`[ResponsesTurn] ${decision.message} → error event`);+ this.sink.endWithError(decision.message);+ this.reportUsage();+ return;+ }+ const next = await this.issueRetry(outcome);+ if (!next) return;+ response = next;+ }} catch (error) {// Only a throwing callback can land here; the leg itself never throws.log(`[ResponsesSSE] Stream error: ${error}`);@@ -121,6 +242,58 @@ class ResponsesTurn {}}+ private retryDecision(outcome: LegOutcome): RetryDecision {+ if (outcome.kind !== "degenerate-wrapper" && outcome.kind !== "stall") {+ return { action: "finish" };+ }+ const retry = this.opts.retry;+ if (!retry) return { action: "finish" };+ if (this.sink.hasIncompleteToolBlock) {+ // Never a tool_use finish over an incomplete block: the cut-off rule.+ return {+ action: "error",+ message: `${triggerLabel(outcome)} with a tool call cut off`,+ };+ }+ if (this.sink.hasCompletedToolBlock) return { action: "end-tool-use" };+ const max = retry.maxLegRetries ?? MAX_LEG_RETRIES;+ if (this.legRetries >= max) {+ return { action: "error", message: exhaustedMessage(outcome, this.legRetries + 1) };+ }+ return { action: "retry" };+ }++ /** Issue the next leg; undefined when the turn has ended instead. */+ private async issueRetry(outcome: LegOutcome): Promise<Response | undefined> {+ const retry = this.opts.retry;+ if (!retry) return undefined;+ this.legRetries++;+ const max = retry.maxLegRetries ?? MAX_LEG_RETRIES;+ log(`[ResponsesTurn] ${triggerLabel(outcome)} — retry ${this.legRetries}/${max}`);+ if (this.sink.signal.aborted) {+ this.reportUsage();+ return undefined;+ }+ const leg = await retry.issueLeg(undefined, this.sink.signal);+ if (leg.kind === "ok") return leg.response;+ if (leg.kind === "error") this.sink.endWithError(leg.message);+ this.reportUsage();+ return undefined;+ }++ /** A completed turn: `message_delta` + `message_stop`, usage, then the turn hooks. */+ private async finishCompleted(stopReason: string): Promise<void> {+ this.sink.endMessage(stopReason, this.wireUsage);+ this.reportUsage();+ if (this.opts.middlewareManager) {+ await this.opts.middlewareManager.afterStreamComplete(+ this.opts.modelName,+ this.opts.streamMetadata+ );+ }+ this.opts.onTurnEnd?.();+ }+private async finish(outcome: LegOutcome): Promise<void> {switch (outcome.kind) {case "done": {@@ -130,15 +303,7 @@ class ResponsesTurn {`[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?.();+ await this.finishCompleted(stopReason);return;}case "api-error":@@ -149,7 +314,7 @@ class ResponsesTurn {apiErrorText(outcome.code, outcome.message, this.opts),this.wireUsage);- this.reportTokens();+ this.reportUsage();return;case "stream-error":// A tool block that was open when the socket died had its argument JSON@@ -167,23 +332,24 @@ class ResponsesTurn {} else {this.sink.endWithText(`\n\n[Stream error: ${outcome.error}]`, this.wireUsage);}- this.reportTokens();+ this.reportUsage();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.+ // Only reached without `retry`. 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();+ this.reportUsage();return;case "stall":this.sink.endWithError(`no output for ${Math.round(outcome.afterMs / 1000)} s`);- this.reportTokens();+ this.reportUsage();return;case "cancelled":- this.reportTokens();+ this.reportUsage();return;}}diff --git a/packages/cli/src/handlers/shared/token-tracker.ts b/packages/cli/src/handlers/shared/token-tracker.tsindex eaa69e91..4bcb3c21 100644--- a/packages/cli/src/handlers/shared/token-tracker.ts+++ b/packages/cli/src/handlers/shared/token-tracker.ts@@ -298,6 +298,34 @@ export class TokenTracker {this.writeFile(this.sessionInputTokens, this.sessionOutputTokens, pricing.isEstimate);}+ /**+ * Charge input that an EARLIER upstream leg of the current request already+ * consumed: cost and the billed-input counter only.+ *+ * A Responses turn whose leg was retried (a stalled or degenerate leg, see+ * `responses-turn.ts`) sent the same body more than once. The last leg is+ * charged by the strategy as usual (`onTokenUpdate`); each earlier leg was a+ * separate upstream request that the provider billed in full (minus cache),+ * and nothing else in the session will ever charge it. Strategy-independent+ * on purpose: under `delta-aware` the last leg is still charged only its+ * growth over the session high-water, which is that strategy's model of the+ * conversation, not of a retry.+ *+ * Never touches the context figures (`sessionInputTokens`, `lastInputTokens`)+ * or output, and does not write the token file: the strategy update that+ * follows does. The cache discount uses the same clamp as `update()`, so a+ * retry that re-sent a cached body is charged as cached.+ */+ addBilledInputTokens(inputTokens: number, detail?: UsageCacheDetail): void {+ if (!(inputTokens > 0)) return;+ this.sessionBilledInputTokens += inputTokens;+ this.sessionCacheReadTokens += detail?.cacheReadTokens ?? 0;+ const pricing = this.getPricing();+ this.sessionTotalCost +=+ (inputTokens / 1_000_000) * pricing.inputCostPer1M -+ this.cacheReadDiscount(pricing, inputTokens, detail);+ }+/*** Delta-aware update with race-condition detection for concurrent conversations.* Used by OpenAI handler where multiple conversations may share one handler.diff --git a/packages/cli/src/stats-otlp.ts b/packages/cli/src/stats-otlp.tsindex 70a2ece6..9545cda9 100644--- a/packages/cli/src/stats-otlp.ts+++ b/packages/cli/src/stats-otlp.ts@@ -113,6 +113,14 @@ export interface StatsEvent {/** How the episode ended for this request. */recovery_outcome?: RecoveryOutcome;+ /**+ * Upstream legs this Responses turn RE-ISSUED inside the same downstream+ * message (a degenerate `parallel` wrapper or a stalled leg; see+ * `responses-turn.ts`). Absent on a turn that needed no retry. The earlier+ * legs' billed input is already inside `estimated_cost`.+ */+ leg_retries?: number;+// Invocationinvocation_mode: string; // "profile" | "explicit-model" | "auto-route" | "env-var" | "model-map"@@ -304,6 +312,9 @@ export function eventToLogRecord(event: StatsEvent): OtlpLogRecord {if (event.recovery_outcome !== undefined) {attributes.push(stringAttr("llm.recovery_outcome", event.recovery_outcome));}+ if (event.leg_retries !== undefined) {+ attributes.push(intAttr("llm.leg_retries", event.leg_retries));+ }return {timeUnixNano,diff --git a/packages/cli/src/stats.ts b/packages/cli/src/stats.tsindex 0244d871..11ac9b24 100644--- a/packages/cli/src/stats.ts+++ b/packages/cli/src/stats.ts@@ -216,6 +216,8 @@ export function recordStats(partial: Partial<StatsEvent>): void {if (partial.recovery_client_retry !== undefined)event.recovery_client_retry = partial.recovery_client_retry;if (partial.recovery_outcome !== undefined) event.recovery_outcome = partial.recovery_outcome;+ // Same half-the-job rule: also pushed in `eventToLogRecord`.+ if (partial.leg_retries !== undefined) event.leg_retries = partial.leg_retries;appendEvent(event);