From 891b319d294b786b4f0e148f726234d7f0ae1adb Mon Sep 17 00:00:00 2001 From: Vadym O Date: Fri, 13 Nov 2026 19:07:13 +0800 Subject: [PATCH] anthropic: resend once without history thinking blocks on 'Invalid signature in thinking block' 400 (AGE-2004) Co-Authored-By: Claude Code --- gui/src/i18n/de.ts | 1 + gui/src/i18n/en.ts | 1 + gui/src/i18n/fr.ts | 1 + gui/src/i18n/ja.ts | 1 + gui/src/i18n/ko.ts | 1 + gui/src/i18n/ru.ts | 1 + gui/src/i18n/tr.ts | 1 + gui/src/i18n/vi.ts | 1 + gui/src/i18n/zh-TW.ts | 1 + gui/src/i18n/zh.ts | 1 + gui/src/pages/Logs.tsx | 1 + src/adapters/anthropic.ts | 53 +++++- src/lib/request-failure-attribution.ts | 1 + src/lib/request-failure-model.ts | 3 + src/server/responses/adapter-dispatch.ts | 20 +++ src/server/responses/core-opaque-recovery.ts | 24 +++ src/types/request.ts | 2 + src/usage/telemetry-contract.ts | 1 + tests/fixtures/test-layout-expected.json | 1 + ...esponses-anthropic-thinking-replay.test.ts | 153 ++++++++++++++++++ 20 files changed, 266 insertions(+), 3 deletions(-) create mode 100644 tests/responses/responses-anthropic-thinking-replay.test.ts diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 997782dc2e5..46bd57e1f8c 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -917,6 +917,7 @@ export const de: Record = { "logs.detail.attempt.recovery.opaqueBlobRejection": "Veralteter verschlüsselter Zustand verworfen", "logs.detail.attempt.recovery.reasoningEffortDowngrade": "Reasoning-Aufwand reduziert", "logs.detail.attempt.recovery.anthropicFastDowngrade": "Schnellmodus abgelehnt, erneut mit Standardtempo versucht", + "logs.detail.attempt.recovery.anthropicThinkingReplay": "Denk-Signatur abgelehnt, erneut ohne frühere Denkblöcke versucht", "logs.detail.outcome.label": "Ergebnis", "logs.detail.outcome.completed": "Abgeschlossen", "logs.detail.outcome.failed": "Fehlgeschlagen", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 3b1bc3db41a..3e11ffe1e52 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -966,6 +966,7 @@ export const en = { "logs.detail.attempt.recovery.opaqueBlobRejection": "Stale encrypted state dropped", "logs.detail.attempt.recovery.reasoningEffortDowngrade": "Reasoning effort downgraded", "logs.detail.attempt.recovery.anthropicFastDowngrade": "Fast mode refused, retried at standard speed", + "logs.detail.attempt.recovery.anthropicThinkingReplay": "Thinking signature rejected, retried without earlier thinking blocks", "logs.detail.outcome.label": "Outcome", "logs.detail.outcome.completed": "Completed", "logs.detail.outcome.failed": "Failed", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 99b25772734..ab926140981 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -942,6 +942,7 @@ export const fr: Record = { "logs.detail.attempt.recovery.opaqueBlobRejection": "État chiffré obsolète abandonné", "logs.detail.attempt.recovery.reasoningEffortDowngrade": "Effort de raisonnement réduit", "logs.detail.attempt.recovery.anthropicFastDowngrade": "Mode rapide refusé, nouvel essai à vitesse standard", + "logs.detail.attempt.recovery.anthropicThinkingReplay": "Signature de réflexion refusée, nouvel essai sans les blocs de réflexion précédents", "logs.detail.outcome.label": "Résultat", "logs.detail.outcome.completed": "Terminé", "logs.detail.outcome.failed": "Échec", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 40a119c233c..0f07bff157f 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -877,6 +877,7 @@ export const ja: Record = { "logs.detail.attempt.recovery.opaqueBlobRejection": "古い暗号化状態を破棄", "logs.detail.attempt.recovery.reasoningEffortDowngrade": "推論強度を下げて再試行", "logs.detail.attempt.recovery.anthropicFastDowngrade": "高速モードが拒否され、標準速度で再試行", + "logs.detail.attempt.recovery.anthropicThinkingReplay": "思考ブロックの署名が拒否され、以前の思考ブロックなしで再試行", "logs.detail.outcome.label": "結果", "logs.detail.outcome.completed": "完了", "logs.detail.outcome.failed": "失敗", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 5d8f7ffeaaa..68fbf538407 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -948,6 +948,7 @@ export const ko: Record = { "logs.detail.attempt.recovery.opaqueBlobRejection": "만료된 암호화 상태 제거", "logs.detail.attempt.recovery.reasoningEffortDowngrade": "추론 강도 하향", "logs.detail.attempt.recovery.anthropicFastDowngrade": "빠른 모드 거부, 표준 속도로 재시도", + "logs.detail.attempt.recovery.anthropicThinkingReplay": "사고 서명 거부, 이전 사고 블록 없이 재시도", "logs.detail.outcome.label": "결과", "logs.detail.outcome.completed": "완료", "logs.detail.outcome.failed": "실패", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index fe1b57c4f70..1661b884b23 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -934,6 +934,7 @@ export const ru: Record = { "logs.detail.attempt.recovery.opaqueBlobRejection": "Устаревшее зашифрованное состояние отброшено", "logs.detail.attempt.recovery.reasoningEffortDowngrade": "Уровень рассуждения понижен", "logs.detail.attempt.recovery.anthropicFastDowngrade": "Быстрый режим отклонён, повтор со стандартной скоростью", + "logs.detail.attempt.recovery.anthropicThinkingReplay": "Подпись блока рассуждений отклонена, повтор без прежних блоков рассуждений", "logs.detail.outcome.label": "Итог", "logs.detail.outcome.completed": "Завершено", "logs.detail.outcome.failed": "Сбой", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index afc2fb98588..ea13f4993f3 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -953,6 +953,7 @@ export const tr: Record = { "logs.detail.attempt.recovery.opaqueBlobRejection": "Eski şifreli durum bırakıldı", "logs.detail.attempt.recovery.reasoningEffortDowngrade": "Akıl yürütme düzeyi düşürüldü", "logs.detail.attempt.recovery.anthropicFastDowngrade": "Hızlı mod reddedildi, standart hızda yeniden denendi", + "logs.detail.attempt.recovery.anthropicThinkingReplay": "Düşünme imzası reddedildi, önceki düşünme blokları olmadan yeniden denendi", "logs.detail.outcome.label": "Sonuç", "logs.detail.outcome.completed": "Tamamlandı", "logs.detail.outcome.failed": "Başarısız", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 18a7e0111a0..11e6fedf66d 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -946,6 +946,7 @@ export const vi: Record = { "logs.detail.attempt.recovery.opaqueBlobRejection": "Đã bỏ trạng thái mã hóa cũ", "logs.detail.attempt.recovery.reasoningEffortDowngrade": "Đã giảm mức suy luận", "logs.detail.attempt.recovery.anthropicFastDowngrade": "Chế độ nhanh bị từ chối, thử lại ở tốc độ chuẩn", + "logs.detail.attempt.recovery.anthropicThinkingReplay": "Chữ ký khối suy nghĩ bị từ chối, thử lại không kèm các khối suy nghĩ trước", "logs.detail.outcome.label": "Kết quả", "logs.detail.outcome.completed": "Hoàn tất", "logs.detail.outcome.failed": "Thất bại", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 6d3c7c8a6ba..dbeed5126ed 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -2494,6 +2494,7 @@ export const zhTW: Record = { "logs.detail.attempt.recovery.opaqueBlobRejection": "已捨棄過期加密狀態", "logs.detail.attempt.recovery.reasoningEffortDowngrade": "已降低推理強度", "logs.detail.attempt.recovery.anthropicFastDowngrade": "快速模式遭拒,改以標準速度重試", + "logs.detail.attempt.recovery.anthropicThinkingReplay": "思考簽章遭拒,改以不含先前思考區塊重試", "logs.detail.outcome.label": "結果", "logs.detail.outcome.completed": "已完成", "logs.detail.outcome.failed": "失敗", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 7bfd9948b19..a3c5cf93c87 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -929,6 +929,7 @@ export const zh: Record = { "logs.detail.attempt.recovery.opaqueBlobRejection": "已丢弃过期加密状态", "logs.detail.attempt.recovery.reasoningEffortDowngrade": "已降低推理强度", "logs.detail.attempt.recovery.anthropicFastDowngrade": "快速模式被拒,按标准速度重试", + "logs.detail.attempt.recovery.anthropicThinkingReplay": "思考签名被拒,去掉先前思考块后重试", "logs.detail.outcome.label": "结果", "logs.detail.outcome.completed": "已完成", "logs.detail.outcome.failed": "失败", diff --git a/gui/src/pages/Logs.tsx b/gui/src/pages/Logs.tsx index cdf9fd0c4b5..a412f3f9bb8 100644 --- a/gui/src/pages/Logs.tsx +++ b/gui/src/pages/Logs.tsx @@ -352,6 +352,7 @@ const RECOVERY_KIND_KEYS = { "opaque-blob-rejection": "logs.detail.attempt.recovery.opaqueBlobRejection", "reasoning-effort-downgrade": "logs.detail.attempt.recovery.reasoningEffortDowngrade", "anthropic-fast-downgrade": "logs.detail.attempt.recovery.anthropicFastDowngrade", + "anthropic-thinking-replay": "logs.detail.attempt.recovery.anthropicThinkingReplay", } as const satisfies Record; /** Map a metric-unavailable reason to its i18n key. */ diff --git a/src/adapters/anthropic.ts b/src/adapters/anthropic.ts index 33305ccb5a3..5ea54f044de 100644 --- a/src/adapters/anthropic.ts +++ b/src/adapters/anthropic.ts @@ -321,6 +321,40 @@ function isLikelyRealAnthropicThinkingSignature(signature: string | undefined): return /^[A-Za-z0-9+/_=-]+$/.test(signature); } +/** + * 400 recovery for "Invalid `signature` in `thinking` block" (`parsed.options.dropThinkingHistory`): + * remove every thinking/redacted_thinking block from the replayed history. Anthropic allows + * omitting them, except on the assistant turn of an open tool loop when thinking is on, so the + * return value says the LAST assistant turn lost its blocks while holding a tool_use and the + * caller must send this one call with thinking off. + */ +function dropThinkingFromMessages(messages: unknown[]): boolean { + let lostInLoop = false; + for (let i = 0; i < messages.length; i++) { + const message = messages[i] as { role?: unknown; content?: unknown } | null; + if (message?.role !== "assistant") continue; + lostInLoop = false; + if (!Array.isArray(message.content)) continue; + const kept = message.content.filter(block => { + const type = (block as { type?: unknown } | null)?.type; + return type !== "thinking" && type !== "redacted_thinking"; + }); + if (kept.length === message.content.length) continue; + if (kept.length === 0) { + messages.splice(i--, 1); + continue; + } + message.content = kept; + lostInLoop = kept.some(block => (block as { type?: unknown } | null)?.type === "tool_use"); + } + return lostInLoop; +} + +function turnThinkingOff(body: Record, modelId: string): void { + if (supportsExplicitThinkingDisable(modelId)) body.thinking = { type: "disabled" }; + else delete body.thinking; +} + /** * Bridge error fidelity (web-search/images loops): extract a display-safe summary from an * Anthropic JSON error envelope so `Provider error ` carries the upstream reason. @@ -960,7 +994,10 @@ function orphanToolResultContent(msg: OcxToolResultMessage): string | unknown[] function messagesToAnthropicFormat( parsed: OcxParsedRequest, toolNames: { toWire: (name: string) => string }, -): { system: string | undefined; messages: unknown[] } { +): { system: string | undefined; messages: unknown[]; thinkingDroppedInLoop: boolean } { + // True when the LAST assistant turn held a tool_use and lost its thinking blocks to the + // dropThinkingHistory recovery; the caller then sends the call with thinking off. + let thinkingDroppedInLoop = false; // One allocator for the whole request: a tool_result must resolve to the SAME wire id its // call got, and two distinct raw ids must never collapse into one. Conforming ids are claimed // first so a rewritten id can never squat on an id another call legitimately owns. @@ -1008,12 +1045,17 @@ function messagesToAnthropicFormat( const preface: unknown[] = []; const toolUses: unknown[] = []; const toolUseIds: string[] = []; + let droppedThinking = false; for (const part of aMsg.content) { if (part.type === "text") { const text = (part as OcxTextContent).text; if (text) preface.push({ type: "text", text }); } else if (part.type === "thinking") { const t = part as OcxThinkingContent; + if (parsed.options.dropThinkingHistory) { + droppedThinking = true; + continue; + } // Redacted blocks replay verbatim FIRST (they preceded the visible thinking block // in the original stream order preserved by the bridge envelope). for (const data of t.redacted ?? []) { @@ -1041,6 +1083,7 @@ function messagesToAnthropicFormat( // Anthropic treats text/thinking after tool_use as ending the tool turn, which makes // earlier tool_use ids look unpaired (#620 / common multi-step history shape). const content = [...preface, ...toolUses]; + thinkingDroppedInLoop = droppedThinking && toolUses.length > 0; if (content.length === 0) break; messages.push({ role: "assistant", content }); if (toolUseIds.length > 0) { @@ -1098,7 +1141,7 @@ function messagesToAnthropicFormat( messages.push({ role: "user", content: "(continue)" }); } - return { system, messages }; + return { system, messages, thinkingDroppedInLoop }; } function toolsToAnthropicFormat(parsed: OcxParsedRequest, toolNames: { toWire: (name: string) => string }): unknown[] | undefined { @@ -1218,6 +1261,9 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti if (!Array.isArray(body.messages)) { throw new Error("validated Anthropic source messages missing"); } + if (parsed.options.dropThinkingHistory && dropThinkingFromMessages(body.messages)) { + turnThinkingOff(body, parsed.modelId); + } await normalizeAnthropicImages(body.messages, { tierBias: incoming?.imageTierBias ?? 0 }); enforceAnthropicImageLimits(body.messages); @@ -1277,7 +1323,7 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti }; } - const { system, messages } = messagesToAnthropicFormat(parsed, toolNames); + const { system, messages, thinkingDroppedInLoop } = messagesToAnthropicFormat(parsed, toolNames); // Before image normalization, so the framing block is present for every downstream pass. if (isAgentRouterEndpoint(provider.baseUrl)) applyAgentRouterLanguageFraming(messages); // Primary image layer: resize/re-encode to fit Anthropic limits without dropping @@ -1365,6 +1411,7 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti delete body.temperature; delete body.top_p; } + if (thinkingDroppedInLoop) turnThinkingOff(body, parsed.modelId); const textFormat = parsed.options.textFormat; if (textFormat?.type === "json_schema" && textFormat.schema) { diff --git a/src/lib/request-failure-attribution.ts b/src/lib/request-failure-attribution.ts index de3e7331667..1624e36a0d7 100644 --- a/src/lib/request-failure-attribution.ts +++ b/src/lib/request-failure-attribution.ts @@ -99,6 +99,7 @@ const STATUS_CONFIRMED_RECOVERY_KINDS: Readonly; export function causeForRecoveryKind(kind: AttemptRecoveryKind): RequestFailureCause { diff --git a/src/server/responses/adapter-dispatch.ts b/src/server/responses/adapter-dispatch.ts index 1c4c0592aa6..6d4dd937225 100644 --- a/src/server/responses/adapter-dispatch.ts +++ b/src/server/responses/adapter-dispatch.ts @@ -66,6 +66,7 @@ import { CONSOLE_GO_UPLOAD_RETRY_DELAY_MS, reasoningEffortRejectionText, anthropicFastRefused, + anthropicThinkingSignatureRejected, } from "./core-opaque-recovery"; import { shouldAttemptImageTierRetry } from "../image-retry"; import { @@ -423,6 +424,7 @@ export async function prepareAdapterExchange( // adapter, and imageTierBias — once armed — rides EVERY subsequent rebuild so a // 413→429 rotation cannot silently undo the tightening. let imageRetryAttempted = false; + const thinkingReplayGuard: { attempted: boolean } = { attempted: false }; const opaqueBlobRecoveryGuard: OpaqueBlobRecoveryGuard = { attempted: false }; // Console Go answers a transient 400 "Invalid upload request." for bodies it accepts // moments later; at most one byte-identical replay is allowed per request. @@ -1062,6 +1064,24 @@ export async function prepareAdapterExchange( upstreamResponse = result; continue recovery; } + // Anthropic 400 "Invalid `signature` in `thinking` block": a replayed thinking block was signed + // by another model or account. Resend once without the history thinking blocks (spiral guard: + // single attempt); the adapter turns thinking off for an open tool loop. + if (await anthropicThinkingSignatureRejected( + upstreamResponse, + transportState.activeAdapter.name, + thinkingReplayGuard.attempted, + upstream.signal, + )) { + thinkingReplayGuard.attempted = true; + parsed.options.dropThinkingHistory = true; + invalidateSameTargetRequest(); + try { void upstreamResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ } + const result = await rebuildAndRefetch("anthropic-thinking-replay"); + if ("failed" in result) return result.failed; + upstreamResponse = result; + continue recovery; + } // Console Go (opencode-zen / opencode-go) intermittently rejects a body it accepts seconds // later with 400 invalid_request_error / "Invalid upload request." Replay the // byte-identical request once after the exact gateway rejection. diff --git a/src/server/responses/core-opaque-recovery.ts b/src/server/responses/core-opaque-recovery.ts index b436ebdc9e6..8253add4058 100644 --- a/src/server/responses/core-opaque-recovery.ts +++ b/src/server/responses/core-opaque-recovery.ts @@ -358,6 +358,30 @@ export async function anthropicFastRefused( } } +/** + * Anthropic answers 400 "messages.N.content.M: Invalid `signature` in `thinking` block" when a + * replayed thinking block was signed by a different model or account than the one now serving the + * turn. A signature carries no readable origin and the raw Messages lane forwards the caller's + * history byte for byte, so the proxy cannot tell beforehand; it resends once without the history + * thinking blocks. Anthropic's own docs allow omitting them; the adapter handles an open tool loop. + */ +const THINKING_SIGNATURE_REJECTION = /Invalid `signature` in `(?:redacted_)?thinking` block/; + +export async function anthropicThinkingSignatureRejected( + response: Response, + adapterName: string, + alreadyAttempted: boolean, + signal: AbortSignal, +): Promise { + if (alreadyAttempted || adapterName !== "anthropic" || response.status !== 400) return false; + try { + const body = await readBoundedResponseBody(response.clone(), { signal }); + return body.displaySafe && !body.truncated && THINKING_SIGNATURE_REJECTION.test(body.text); + } catch { + return false; + } +} + export async function opaqueBlobRejectionBodyForRecovery( response: Response, outboundBody: string | undefined, diff --git a/src/types/request.ts b/src/types/request.ts index 91569f5499c..01d838b2005 100644 --- a/src/types/request.ts +++ b/src/types/request.ts @@ -304,6 +304,8 @@ export interface OcxRequestOptions { serviceTier?: string; /** Final outbound tier action, resolved after the provider/model wire is settled. */ tierDecision?: TierDecision; + /** Internal: set by the 400 "Invalid `signature` in `thinking` block" recovery; the Anthropic adapter drops history thinking blocks. */ + dropThinkingHistory?: boolean; /** Internal B0 observation inputs; adapters combine these with the wire they actually serialize. */ tierObservation?: TierObservationContext; presencePenalty?: number; diff --git a/src/usage/telemetry-contract.ts b/src/usage/telemetry-contract.ts index fe6d83c9dd1..30bbcffb246 100644 --- a/src/usage/telemetry-contract.ts +++ b/src/usage/telemetry-contract.ts @@ -39,6 +39,7 @@ export const ATTEMPT_RECOVERY_KIND_ROSTER = Object.freeze([ "empty-completion", "reasoning-effort-downgrade", "anthropic-fast-downgrade", + "anthropic-thinking-replay", ] as const); export type AttemptRecoveryKind = typeof ATTEMPT_RECOVERY_KIND_ROSTER[number]; diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 77560e194ca..fc0c4119771 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1237,6 +1237,7 @@ "responses-account-change-scrub.test.ts": "responses", "responses-account-label.test.ts": "responses", "responses-anthropic-fast-downgrade.test.ts": "responses", + "responses-anthropic-thinking-replay.test.ts": "responses", "responses-azure-opaque-blob-recovery.test.ts": "responses", "responses-bare-echo-helper-fence.test.ts": "responses", "responses-canonical-only-top-level-fields.test.ts": "responses", diff --git a/tests/responses/responses-anthropic-thinking-replay.test.ts b/tests/responses/responses-anthropic-thinking-replay.test.ts new file mode 100644 index 00000000000..d18b1dcee05 --- /dev/null +++ b/tests/responses/responses-anthropic-thinking-replay.test.ts @@ -0,0 +1,153 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { resetWorkflowBudgetsForTest } from "../../src/lib/workflow-budget"; +import { encodeReasoningEnvelope } from "../../src/responses/reasoning-envelope"; +import { handleResponses } from "../../src/server/responses/core"; +import type { RequestLogContext } from "../../src/server/request-log"; +import type { OcxConfig } from "../../src/types"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; + +const originalFetch = globalThis.fetch; +const originalHome = process.env.OPENCODEX_HOME; +const BAD_SIGNATURE = { type: "error", error: { type: "invalid_request_error", message: "messages.3.content.0: Invalid `signature` in `thinking` block" } }; +const OTHER_400 = { type: "error", error: { type: "invalid_request_error", message: "max_tokens: must be positive" } }; +const SIG = "EqQBCkYIARgCKkD".padEnd(48, "x"); +let testDir = ""; +let releaseSpendHome: (() => void) | undefined; + +function config(): OcxConfig { + return { + defaultProvider: "anthropic-apikey", + providers: { + "anthropic-apikey": { + adapter: "anthropic", + baseUrl: "https://api.anthropic.com", + authMode: "key", + apiKey: "test-token", + models: ["claude-opus-5-5"], + }, + }, + } as OcxConfig; +} + +const reasoning = { type: "reasoning", id: "rs_1", summary: [], encrypted_content: encodeReasoningEnvelope({ sig: SIG, txt: "thought" }) }; +const user = { type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] }; +const toolLoop = [ + reasoning, + { type: "function_call", call_id: "call_1", name: "lookup", arguments: "{}" }, + { type: "function_call_output", call_id: "call_1", output: "result" }, +]; +const closedTurn = [ + reasoning, + { type: "message", role: "assistant", content: [{ type: "output_text", text: "done" }] }, + { type: "message", role: "user", content: [{ type: "input_text", text: "again" }] }, +]; + +function request(history: unknown[]): Request { + return new Request("http://localhost/v1/responses", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + model: "anthropic-apikey/claude-opus-5-5", + stream: false, + store: false, + reasoning: { effort: "high" }, + tools: [{ type: "function", name: "lookup", parameters: { type: "object", properties: {} } }], + input: [user, ...history], + }), + }); +} + +function success(): Response { + return Response.json({ + id: "msg-ok", type: "message", role: "assistant", model: "claude-opus-5-5", + content: [{ type: "text", text: "ok" }], stop_reason: "end_turn", + usage: { input_tokens: 1, output_tokens: 1 }, + }); +} + +function fakeUpstream(answer: (index: number) => Response): Array> { + const sends: Array> = []; + globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { + sends.push(JSON.parse(String(init?.body)) as Record); + return answer(sends.length); + }) as typeof fetch; + return sends; +} + +const thinkingBlocks = (send: Record): unknown[] => + send.messages.flatMap((m: any) => (Array.isArray(m.content) ? m.content : [])) + .filter((b: any) => b.type === "thinking" || b.type === "redacted_thinking"); + +beforeEach(() => { + resetWorkflowBudgetsForTest(); + testDir = mkdtempSync(join(tmpdir(), "ocx-anthropic-thinking-replay-")); + process.env.OPENCODEX_HOME = testDir; + releaseSpendHome = acquireOwnedSpendHome(); +}); + +afterEach(() => { + try { + releaseSpendHome?.(); + } finally { + releaseSpendHome = undefined; + globalThis.fetch = originalFetch; + if (originalHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = originalHome; + rmSync(testDir, { recursive: true, force: true }); + resetWorkflowBudgetsForTest(); + } +}); + +describe("Anthropic thinking-signature rejection in Responses dispatch", () => { + test("a closed turn is resent once without history thinking blocks, thinking stays on", async () => { + const sends = fakeUpstream(index => index === 1 ? Response.json(BAD_SIGNATURE, { status: 400 }) : success()); + const logCtx: RequestLogContext = { model: "", provider: "" }; + const response = await handleResponses(request(closedTurn), config(), logCtx); + await response.text(); + + expect(response.status).toBe(200); + expect(sends).toHaveLength(2); + expect(thinkingBlocks(sends[0]!)).toHaveLength(1); + expect(thinkingBlocks(sends[1]!)).toHaveLength(0); + expect(sends[1]!.thinking?.type).toBe(sends[0]!.thinking?.type); + expect(sends[1]!.thinking?.type).not.toBe("disabled"); + expect(logCtx.activeAttempt?.recoveryKinds).toEqual(["anthropic-thinking-replay"]); + }); + + test("inside an open tool loop the resend turns thinking off", async () => { + const sends = fakeUpstream(index => index === 1 ? Response.json(BAD_SIGNATURE, { status: 400 }) : success()); + const response = await handleResponses(request(toolLoop), config(), { model: "", provider: "" }); + await response.text(); + + expect(response.status).toBe(200); + expect(sends).toHaveLength(2); + expect(sends[0]!.thinking).toBeDefined(); + expect(thinkingBlocks(sends[1]!)).toHaveLength(0); + expect(sends[1]!.messages.some((m: any) => Array.isArray(m.content) && m.content.some((b: any) => b.type === "tool_use"))).toBe(true); + expect([undefined, "disabled"]).toContain(sends[1]!.thinking?.type); + }); + + test("an unrelated 400 is not resent", async () => { + const sends = fakeUpstream(() => Response.json(OTHER_400, { status: 400 })); + const logCtx: RequestLogContext = { model: "", provider: "" }; + const response = await handleResponses(request(closedTurn), config(), logCtx); + await response.text(); + + expect(response.status).toBe(400); + expect(sends).toHaveLength(1); + expect(logCtx.activeAttempt?.recoveryKinds ?? []).not.toContain("anthropic-thinking-replay"); + }); + + test("a second signature rejection is returned after one resend", async () => { + const sends = fakeUpstream(() => Response.json(BAD_SIGNATURE, { status: 400 })); + const response = await handleResponses(request(closedTurn), config(), { model: "", provider: "" }); + const body = await response.text(); + + expect(response.status).toBe(400); + expect(body).toContain("Invalid `signature`"); + expect(sends).toHaveLength(2); + }); +});