@openclaw/ai 2026.11.3 → 2026.11.5-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +11 -8
  2. package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
  3. package/dist/anthropic-DEKgalVg.mjs +182 -0
  4. package/dist/{anthropic-payload-policy-C0ki72BT.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
  5. package/dist/{anthropic-stream-reducer-yWDb5Cct.mjs → anthropic-stream-lifecycle-DF2qVvg1.mjs} +845 -649
  6. package/dist/{anthropic-tool-projection-C2-d1eZ3.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
  7. package/dist/{anthropic-tool-projection-DZOKfAmL.mjs → anthropic-tool-projection-dGRfr4iT.mjs} +22 -32
  8. package/dist/{api-registry-gDt0faai.d.mts → api-registry-DY2MLUyg.d.mts} +2 -2
  9. package/dist/assistant-output-CD4kY9gu.mjs +16 -0
  10. package/dist/{azure-openai-responses-BvvXzZbi.mjs → azure-openai-responses-DbQV5RTx.mjs} +47 -53
  11. package/dist/{cloudflare-Dttf8jKq.mjs → cloudflare-BJ2_Xabx.mjs} +1 -1
  12. package/dist/{credential-redaction-XvsPf7Yi.d.mts → credential-redaction-DrgndwTJ.d.mts} +5 -3
  13. package/dist/{deferred-event-buffer-DAvyP7qA.mjs → deferred-event-buffer-tIGkTkTm.mjs} +1 -2
  14. package/dist/{diagnostics-v7oVEW59.mjs → diagnostics-CloVGQiK.mjs} +27 -20
  15. package/dist/{diagnostics-DzrF1h4J.mjs → diagnostics-o1PrVNQb.mjs} +11 -4
  16. package/dist/diagnostics.d.mts +6 -7
  17. package/dist/diagnostics.mjs +4 -4
  18. package/dist/{env-api-keys-Xd8dm_aV.mjs → env-api-keys-BuHc86ya.mjs} +1 -26
  19. package/dist/event-stream-B4ZcSvsu.d.mts +1 -0
  20. package/dist/{event-stream-CzpE1g_o.d.mts → event-stream-BYmtRe8-.d.mts} +1 -1
  21. package/dist/event-stream.d.mts +2 -2
  22. package/dist/event-stream.mjs +1 -2
  23. package/dist/expect-lbe3Hgrh.mjs +8 -0
  24. package/dist/{github-copilot-request-facts-F-EmvkpW.mjs → github-copilot-request-facts-BZ_EMo7X.mjs} +1 -1
  25. package/dist/{google-Cpi_cLKZ.mjs → google-B1g82bn4.mjs} +7 -8
  26. package/dist/{google-interactions-CGINbsjO.mjs → google-interactions-Ckr0Z99Z.mjs} +243 -269
  27. package/dist/{google-messages-DQMgG5yG.mjs → google-messages-A-9d3y5V.mjs} +52 -18
  28. package/dist/{google-provider-stream-BHd0cST9.mjs → google-provider-stream-CNVh4gpm.mjs} +19 -11
  29. package/dist/{google-shared-vtag8bj5.mjs → google-shared-WNM86ZcW.mjs} +72 -42
  30. package/dist/{google-vertex-eKoUnW7N.mjs → google-vertex-CXjleC6g.mjs} +3 -3
  31. package/dist/{google-video-slots-D8tPH8wX.mjs → google-video-slots-Bxt-OXO8.mjs} +1 -1
  32. package/dist/{host-CWt55nnF.mjs → host-DX7ORpeH.mjs} +46 -39
  33. package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
  34. package/dist/{host-policy-Dm7PM6AD.mjs → host-policy-jCZebuXx.mjs} +2 -2
  35. package/dist/index-Bczt0MnO.d.mts +17 -0
  36. package/dist/index.d.mts +8 -7
  37. package/dist/index.mjs +9 -7
  38. package/dist/internal/anthropic.d.mts +21 -26
  39. package/dist/internal/anthropic.mjs +6 -6
  40. package/dist/internal/google-model-family.mjs +1 -1
  41. package/dist/internal/google.d.mts +15 -0
  42. package/dist/internal/google.mjs +1 -0
  43. package/dist/internal/model-request-body.d.mts +37 -0
  44. package/dist/internal/model-request-body.mjs +106 -0
  45. package/dist/internal/openai-completions-compat.d.mts +1 -1
  46. package/dist/internal/openai-completions-compat.mjs +1 -1
  47. package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
  48. package/dist/internal/openai-responses-payload-policy.mjs +2 -2
  49. package/dist/internal/openai.d.mts +14 -12
  50. package/dist/internal/openai.mjs +11 -10
  51. package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
  52. package/dist/{reasoning-tag-text-partitioner-CU9A4Lg8.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -111
  53. package/dist/internal/retry-after.d.mts +2 -2
  54. package/dist/internal/retry-after.mjs +96 -32
  55. package/dist/internal/runtime.d.mts +15 -41
  56. package/dist/internal/runtime.mjs +9 -10
  57. package/dist/internal/shared.d.mts +21 -25
  58. package/dist/internal/shared.mjs +9 -98
  59. package/dist/internal/tool-schema.d.mts +10 -10
  60. package/dist/internal/tool-schema.mjs +4 -4
  61. package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
  62. package/dist/mistral-CjHkvsqR.mjs +3741 -0
  63. package/dist/{openai.LICENSE → mistral.LICENSE} +1 -1
  64. package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
  65. package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
  66. package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
  67. package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
  68. package/dist/{openai-chatgpt-responses-BZa3SySh.mjs → openai-chatgpt-responses-CwS5JP7A.mjs} +61 -80
  69. package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
  70. package/dist/{openai-completions-compat-bNQXF1y9.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
  71. package/dist/{openai-completions-CCZ_UHCk.mjs → openai-completions-sj4S-RXQ.mjs} +5 -5
  72. package/dist/openai-completions-transport-BDAIA0_P.mjs +3406 -0
  73. package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
  74. package/dist/{openai-prompt-cache-B9AvdoEo.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
  75. package/dist/{openai-responses-compaction-replay-_sUXtcwU.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
  76. package/dist/{openai-responses-contracts-B1nkeLL6.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
  77. package/dist/{openai-responses-contracts-B5mGAbR6.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
  78. package/dist/{openai-responses-endpoint-CfKR6N5f.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
  79. package/dist/openai-responses-ev_c6oTy.mjs +89 -0
  80. package/dist/{openai-responses-payload-policy-BzM52TTH.d.mts → openai-responses-payload-policy-DyE30gdD.d.mts} +7 -7
  81. package/dist/{openai-responses-request-lifecycle-CTqHc02t.mjs → openai-responses-request-lifecycle-BuOs0mwI.mjs} +12 -26
  82. package/dist/{openai-responses-shared-wx9v1MCn.mjs → openai-responses-shared-BmRQnUPP.mjs} +633 -1493
  83. package/dist/{openai-responses-terminal-usage-CpVjkqn-.d.mts → openai-responses-terminal-usage-D7IhRA6i.d.mts} +9 -3
  84. package/dist/{openai-tool-schema-BTEU2xmN.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
  85. package/dist/otel-Buswj0Mf.mjs +766 -0
  86. package/dist/{overflow-OF3PgPbw.mjs → overflow-CpApyjG2.mjs} +1 -1
  87. package/dist/{positive-integer-Bb4Evc7L.mjs → positive-integer-DiqE5vNi.mjs} +2 -3
  88. package/dist/{prompt-cache-stability-D_MeCQFI.mjs → prompt-cache-stability-w-ICeyOI.mjs} +1 -1
  89. package/dist/{provider-error-qtZD2inE.mjs → provider-error-DD-fo4Rz.mjs} +71 -234
  90. package/dist/{provider-options-DAzsyi49.d.mts → provider-options-Mo8NM5d1.d.mts} +16 -5
  91. package/dist/{provider-replay-context-4vxI7p4V.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
  92. package/dist/provider-transcript-transform-DtaxNcC1.mjs +32 -0
  93. package/dist/{provider-transport-turn-state-D_GjPJHe.mjs → provider-transport-turn-state-BIS8maBK.mjs} +4 -4
  94. package/dist/{provider-types-CWl4VXvE.d.mts → provider-types-B1e98js5.d.mts} +3 -3
  95. package/dist/provider-types.d.mts +7 -6
  96. package/dist/providers.d.mts +2 -2
  97. package/dist/providers.mjs +26 -29
  98. package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
  99. package/dist/request-headers-DO4Mqhw1.mjs +10 -0
  100. package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
  101. package/dist/{retry-after-BrmTv0jL.d.mts → retry-after-DnHBlFS2.d.mts} +21 -1
  102. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  103. package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
  104. package/dist/{simple-options-xJkqrG_E.mjs → simple-options-tLSeECry.mjs} +108 -82
  105. package/dist/src-BUsVkrNt.mjs +105 -0
  106. package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
  107. package/dist/stable-stringify-CchQEmeA.mjs +84 -0
  108. package/dist/{stream-C4YDqhFj.mjs → stream-DrtAWu7c.mjs} +2 -6
  109. package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
  110. package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
  111. package/dist/string-normalization-B8TDDBX_.mjs +32 -0
  112. package/dist/telemetry-CvK1yQg7.mjs +582 -0
  113. package/dist/{tool-schema-json-projection-B1sTYwfH.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
  114. package/dist/{transport-stream-shared-lhgkTOz3.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
  115. package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
  116. package/dist/{transport-utils-DwOpuTjL.mjs → transport-utils-Da_39MYi.mjs} +23 -38
  117. package/dist/transports.d.mts +42 -39
  118. package/dist/transports.mjs +215 -296
  119. package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
  120. package/dist/types-Cb3-5WM9.d.mts +1 -0
  121. package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
  122. package/dist/types.d.mts +7 -6
  123. package/dist/types.mjs +7 -5
  124. package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
  125. package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
  126. package/dist/validation.d.mts +1 -1
  127. package/dist/validation.mjs +1 -2
  128. package/package.json +40 -6
  129. package/dist/anthropic-lueA8LUg.mjs +0 -221
  130. package/dist/assistant-output-BnQm3fov.mjs +0 -47
  131. package/dist/event-stream-CDpFza-M.d.mts +0 -1
  132. package/dist/index-DSprYWaz.d.mts +0 -185
  133. package/dist/mistral-CQ7aoWg2.mjs +0 -512
  134. package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
  135. package/dist/openai-CiRi-nVE.mjs +0 -20077
  136. package/dist/openai-completions-transport-DFvSBbUT.mjs +0 -10881
  137. package/dist/openai-responses-DQsZKUoI.mjs +0 -87
  138. package/dist/rolldown-runtime-B4iAMlE-.mjs +0 -35
  139. package/dist/types-CBJthzJX.d.mts +0 -1
  140. package/dist/ws.LICENSE +0 -20
@@ -1,29 +1,33 @@
1
- import { E as supportsClaudeInHistorySystemMessages, O as supportsClaudeNativeXhighEffort, S as resolveClaudeSonnet5ModelIdentity, b as resolveClaudeOpus5ModelIdentity, d as requiresClaudeBetweenToolsThinking, g as resolveClaudeModelIdentity, h as resolveClaudeHaiku55ModelIdentity, k as supportsClaudeServerCompaction, m as resolveClaudeFable5ModelIdentity, u as bindsClaudeThinkingPrefix, w as supportsClaudeAdaptiveThinking, x as resolveClaudeSonnet55ModelIdentity, y as resolveClaudeOpus55ModelIdentity } from "./src-CyA0zJnt.mjs";
2
- import { f as hasRuntimeContextMarker } from "./types-BXd0kI8-.mjs";
1
+ import { E as supportsClaudeInHistorySystemMessages, O as supportsClaudeNativeXhighEffort, S as resolveClaudeSonnet5ModelIdentity, b as resolveClaudeOpus5ModelIdentity, d as requiresClaudeBetweenToolsThinking, g as resolveClaudeModelIdentity, h as resolveClaudeHaiku55ModelIdentity, k as supportsClaudeServerCompaction, m as resolveClaudeFable5ModelIdentity, u as bindsClaudeThinkingPrefix, w as supportsClaudeAdaptiveThinking, x as resolveClaudeSonnet55ModelIdentity, y as resolveClaudeOpus55ModelIdentity } from "./src-CQ7nH2mL.mjs";
2
+ import { p as hasRuntimeContextMarker } from "./types-OVEWUaDh.mjs";
3
3
  import { r as appendAssistantThinking } from "./event-stream-X2gmsUWv.mjs";
4
- import { a as asRecord, o as isRecord, r as asOptionalObjectRecord, s as readStringField } from "./record-coerce-CNDovvft.mjs";
5
- import { a as normalizeOptionalLowercaseString, i as normalizeNullableString } from "./string-coerce-Cj8sqWHx.mjs";
6
- import { n as asNonNegativeFiniteNumber } from "./number-coercion-37gmNkuA.mjs";
7
- import { N as isImageWithMediaPayload, O as calculateCost, S as resolveAnthropicThinkingEffort, g as applyClaudeRequestContract, h as ANTHROPIC_CLAUDE_CODE_VERSION, r as getAiTransportHost, u as STREAM_ERROR_FALLBACK_TEXT, v as defaultsClaudeAdaptiveThinking, w as usesClaudeFable5MessagesContract, x as requiresClaudeAdaptiveThinking, y as mapAnthropicStopReason } from "./host-CWt55nnF.mjs";
8
- import "./transport-utils-DwOpuTjL.mjs";
4
+ import { a as asRecord, c as readStringField, o as isRecord, r as asOptionalObjectRecord } from "./record-coerce-BQaoiN3r.mjs";
5
+ import { a as normalizeOptionalLowercaseString, i as normalizeNullableString } from "./string-coerce-BCuWMIrk.mjs";
6
+ import { n as asNonNegativeFiniteNumber } from "./number-coercion-C7HsBgUL.mjs";
7
+ import { C as resolveAnthropicThinkingEffort, N as isImageWithMediaPayload, O as calculateCost, S as requiresClaudeAdaptiveThinking, T as usesClaudeStreamingRefusalContract, g as applyClaudeRequestContract, h as ANTHROPIC_CLAUDE_CODE_VERSION, r as getAiTransportHost, u as STREAM_ERROR_FALLBACK_TEXT, v as defaultsClaudeAdaptiveThinking, w as usesClaudeFable5MessagesContract, y as mapAnthropicStopReason } from "./host-DX7ORpeH.mjs";
8
+ import "./transport-utils-Da_39MYi.mjs";
9
9
  import { n as estimateBase64DecodedBytes } from "./base64-C8CdcsjU.mjs";
10
- import { a as resolveProviderRequestCapabilities, i as resolveProviderEndpoint } from "./host-policy-Dm7PM6AD.mjs";
11
- import { i as resolveCacheRetention } from "./cloudflare-Dttf8jKq.mjs";
10
+ import { a as resolveProviderRequestCapabilities, i as resolveProviderEndpoint } from "./host-policy-jCZebuXx.mjs";
11
+ import { i as resolveCacheRetention } from "./cloudflare-BJ2_Xabx.mjs";
12
12
  import { t as sanitizeSurrogates } from "./sanitize-unicode-CRGuMONI.mjs";
13
- import { S as splitSystemPromptCacheBoundary, T as stripSystemPromptRelocatableBoundary, d as extractToolResultBlockText, f as extractToolResultText, h as preparedRequestSuffix, l as describeToolResultMediaPlaceholder, t as adjustMaxTokensForThinking, w as stripSystemPromptCacheBoundary } from "./simple-options-xJkqrG_E.mjs";
14
- import { C as parseJsonObjectPreservingUnsafeIntegers, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, b as transportAbortError, d as iterateModelStream, i as copyProviderAcceptanceObserver, l as finalizeTerminalToolCallArguments, r as coerceTransportToolCallArguments, v as sanitizeTransportPayloadText } from "./transport-stream-shared-lhgkTOz3.mjs";
15
- import { t as parsePositiveInteger } from "./positive-integer-Bb4Evc7L.mjs";
16
- import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-4vxI7p4V.mjs";
17
- import { n as transformProviderMessages } from "./assistant-output-BnQm3fov.mjs";
18
- import { a as reconcileAnthropicToolChoice, i as projectAnthropicTools, n as normalizeAnthropicToolChoice, o as resolveOriginalAnthropicToolName, s as toClaudeCodeToolName, t as normalizeAnthropicToolCallId } from "./anthropic-tool-projection-DZOKfAmL.mjs";
19
- import { t as notifyLlmRequestActivity } from "./llm-request-activity-CfMuh5cC.mjs";
13
+ import { C as stripSystemPromptCacheBoundary, a as describeToolResultMediaPlaceholder, c as extractToolResultText, f as preparedRequestSuffix, s as extractToolResultBlockText, t as adjustMaxTokensForThinking, w as stripSystemPromptRelocatableBoundary, x as splitSystemPromptCacheBoundary } from "./simple-options-tLSeECry.mjs";
14
+ import { A as parseStreamingJson, O as createToolArgumentPreviewSchedule, c as failTransportStream, d as iterateModelStream, h as notifyProviderHttpResponse, i as copyProviderAcceptanceObserver, l as finalizeTerminalToolCallArguments, r as coerceTransportToolCallArguments, u as finalizeTransportStream, w as parseJsonObjectPreservingUnsafeIntegers, x as transportAbortError, y as sanitizeTransportPayloadText } from "./transport-stream-shared-D2uFMhMc.mjs";
15
+ import { t as parsePositiveInteger } from "./positive-integer-DiqE5vNi.mjs";
16
+ import { a as reconcileAnthropicToolChoice, i as projectAnthropicTools, n as normalizeAnthropicToolChoice, o as resolveOriginalAnthropicToolName, s as toClaudeCodeToolName, t as normalizeAnthropicToolCallId } from "./anthropic-tool-projection-dGRfr4iT.mjs";
17
+ import { t as createDeferredEventBuffer } from "./deferred-event-buffer-tIGkTkTm.mjs";
18
+ import { t as notifyLlmRequestActivity } from "./llm-request-activity-DzaHoRAU.mjs";
19
+ import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-xyU7-CiT.mjs";
20
+ import { t as transformProviderMessages } from "./provider-transcript-transform-DtaxNcC1.mjs";
21
+ import { markEncodedModelRequestBody } from "./internal/model-request-body.mjs";
22
+ import { t as createAssistantOutput } from "./assistant-output-CD4kY9gu.mjs";
23
+ import { isProxy } from "node:util/types";
20
24
  //#region packages/ai/src/providers/anthropic-auth-headers.ts
21
25
  /** Inspect resolved credential shape for auth routing without exposing its value. */
22
26
  function isAnthropicOAuthApiKey(apiKey) {
23
27
  return typeof apiKey === "string" && getAiTransportHost().resolveSecretSentinel(apiKey).includes("sk-ant-oat");
24
28
  }
25
29
  function usesFoundryBearerAuth(model) {
26
- return model.provider === "microsoft-foundry" && (model.authHeader === true || Object.entries(model.headers ?? {}).some(([key, value]) => key.toLowerCase() === "authorization" && /^bearer\s+\S+/i.test(value.trim())));
30
+ return model.provider === "microsoft-foundry" && (model.authHeader === true || Object.entries(model.headers ?? {}).some(([key, value]) => key.toLowerCase() === "authorization" && value !== null && /^bearer\s+\S+/i.test(value.trim())));
27
31
  }
28
32
  function omitFoundryBearerCredentialHeaders(headers) {
29
33
  if (!headers) return;
@@ -211,7 +215,44 @@ function applyAnthropicRequestCacheControl(payload, cacheControl, supportsCacheC
211
215
  if (isRecord(lastTool)) lastTool.cache_control = cacheControl;
212
216
  }
213
217
  const usedMarkers = countAnthropicCacheControlMarkers(payload.system) + countAnthropicCacheControlMarkers(payload.tools);
214
- applyAnthropicCacheControlToMessages(payload.messages, cacheControl, ANTHROPIC_CACHE_CONTROL_LIMIT - usedMarkers, cacheBreakpointOptOutMessageIndexes);
218
+ const messages = payload.messages;
219
+ const markerLimit = ANTHROPIC_CACHE_CONTROL_LIMIT - usedMarkers;
220
+ if (!Array.isArray(messages) || messages.length === 0 || markerLimit <= 0) return;
221
+ let stableEnd = messages.length;
222
+ for (const index of cacheBreakpointOptOutMessageIndexes) stableEnd = Math.min(stableEnd, index);
223
+ let marked = 0;
224
+ for (let i = stableEnd - 1; i >= 0 && marked < Math.min(markerLimit, 2); i--) {
225
+ const record = messages[i];
226
+ if (!isRecord(record) || record.role !== "user") continue;
227
+ const content = record.content;
228
+ const blocks = typeof content === "string" ? [{
229
+ type: "text",
230
+ text: content
231
+ }] : content;
232
+ if (!Array.isArray(blocks)) continue;
233
+ for (let j = blocks.length - 1; j >= 0; j--) {
234
+ const blockRecord = blocks[j];
235
+ if (!isRecord(blockRecord)) continue;
236
+ if (blockRecord.type === "text" || blockRecord.type === "image" || blockRecord.type === "tool_result") {
237
+ if (Object.isFrozen(record) || Object.isFrozen(blocks) || Object.isFrozen(blockRecord)) {
238
+ const markedBlocks = blocks.slice();
239
+ markedBlocks[j] = {
240
+ ...blockRecord,
241
+ cache_control: cacheControl
242
+ };
243
+ messages[i] = {
244
+ ...record,
245
+ content: markedBlocks
246
+ };
247
+ } else {
248
+ blockRecord.cache_control = cacheControl;
249
+ if (typeof content === "string") record.content = blocks;
250
+ }
251
+ marked++;
252
+ break;
253
+ }
254
+ }
255
+ }
215
256
  }
216
257
  function normalizeAnthropicSystemBlocks(system, cacheControl) {
217
258
  if (!Array.isArray(system)) return;
@@ -252,33 +293,6 @@ function normalizeAnthropicSystemBlocks(system, cacheControl) {
252
293
  }
253
294
  if (cacheControl) system.splice(0, system.length, ...normalizedBlocks);
254
295
  }
255
- /** Apply one shared deepest-stable-message cache breakpoint policy. */
256
- function applyAnthropicCacheControlToMessages(messages, cacheControl, markerLimit, cacheBreakpointOptOutMessageIndexes) {
257
- if (!Array.isArray(messages) || messages.length === 0 || markerLimit <= 0) return;
258
- let stableEnd = messages.length;
259
- for (const index of cacheBreakpointOptOutMessageIndexes) stableEnd = Math.min(stableEnd, index);
260
- let marked = 0;
261
- for (let i = stableEnd - 1; i >= 0 && marked < Math.min(markerLimit, 2); i--) {
262
- const record = messages[i];
263
- if (!isRecord(record) || record.role !== "user") continue;
264
- const content = record.content;
265
- const blocks = typeof content === "string" ? [{
266
- type: "text",
267
- text: content
268
- }] : content;
269
- if (!Array.isArray(blocks)) continue;
270
- for (let j = blocks.length - 1; j >= 0; j--) {
271
- const blockRecord = blocks[j];
272
- if (!isRecord(blockRecord)) continue;
273
- if (blockRecord.type === "text" || blockRecord.type === "image" || blockRecord.type === "tool_result") {
274
- blockRecord.cache_control = cacheControl;
275
- if (typeof content === "string") record.content = blocks;
276
- marked++;
277
- break;
278
- }
279
- }
280
- }
281
- }
282
296
  function countAnthropicCacheControlMarkers(blocks) {
283
297
  if (!Array.isArray(blocks)) return 0;
284
298
  let count = 0;
@@ -430,6 +444,211 @@ function applyAnthropicEphemeralCacheControlMarkers(payloadObj, cacheControl = {
430
444
  }
431
445
  }
432
446
  //#endregion
447
+ //#region packages/ai/src/providers/anthropic-refusal.ts
448
+ function applyAnthropicRefusal(output, stopDetails, provider) {
449
+ const record = asOptionalObjectRecord(stopDetails);
450
+ const details = {
451
+ category: normalizeNullableString(record?.category),
452
+ explanation: normalizeNullableString(record?.explanation)
453
+ };
454
+ const category = details.category ? ` (category: ${details.category})` : "";
455
+ const explanation = details.explanation ? `: ${details.explanation}` : ".";
456
+ output.stopReason = "error";
457
+ output.errorMessage = `Anthropic refusal${category}${explanation}`;
458
+ output.diagnostics = [...output.diagnostics ?? [], {
459
+ type: "provider_refusal",
460
+ timestamp: Date.now(),
461
+ details: {
462
+ provider,
463
+ category: details.category,
464
+ explanation: details.explanation
465
+ }
466
+ }];
467
+ }
468
+ //#endregion
469
+ //#region packages/ai/src/providers/anthropic-thinking-replay.ts
470
+ const ANTHROPIC_OMITTED_REASONING_TEXT = "[assistant reasoning omitted]";
471
+ function applyAnthropicThinkingBindingControls(params, directApiKeyBetaHeader) {
472
+ if (directApiKeyBetaHeader === void 0 || !isRecord(params.thinking) || params.thinking.type !== "adaptive") return;
473
+ params.thinking.block_binding = { prefix_mismatch_behavior: "drop_block" };
474
+ const betas = directApiKeyBetaHeader.split(",").map((beta) => beta.trim()).filter(Boolean);
475
+ return { "anthropic-beta": [.../* @__PURE__ */ new Set([...betas, "thinking-binding-controls-2026-08-01"])].join(",") };
476
+ }
477
+ function readAnthropicInputTransformations(event) {
478
+ if (!isRecord(event) || event.type !== "message_start" && event.type !== "message_delta") return;
479
+ const transformations = (isRecord(event.message) ? event.message : void 0)?.input_transformations ?? event.input_transformations;
480
+ return Array.isArray(transformations) ? transformations : void 0;
481
+ }
482
+ function logAnthropicThinkingDrops(transformations) {
483
+ const drops = transformations?.filter((entry) => isRecord(entry) && entry.type === "thinking_dropped" && typeof entry.reason === "string" && /^(?:prefix|model|organization|end_user)_binding_mismatch$/.test(entry.reason) && typeof entry.path === "string" && /^messages\.\d{1,10}\.content\.\d{1,10}$/.test(entry.path));
484
+ if (!drops?.length) return;
485
+ const paths = drops.slice(0, 5).map(({ reason, path }) => `${reason} at ${path}`);
486
+ getAiTransportHost().logWarn("anthropic", `replayed thinking dropped: ${drops.length} block(s) (${paths.join(", ")}${drops.length > 5 ? ", …" : ""})`);
487
+ }
488
+ /**
489
+ * Anthropic tool results continue the preceding assistant turn. Preserve that
490
+ * turn's signed thinking even when the next request disables new thinking.
491
+ */
492
+ function findActiveAnthropicToolTurnAssistantIndex(messages) {
493
+ const toolResultIds = /* @__PURE__ */ new Set();
494
+ let index = messages.length - 1;
495
+ while (index >= 0) {
496
+ const message = asOptionalObjectRecord(messages[index]);
497
+ if (message?.role === "user" && isRecord(message.operatorMessage)) {
498
+ index -= 1;
499
+ continue;
500
+ }
501
+ if (message?.role !== "toolResult") break;
502
+ if (typeof message.toolCallId === "string") toolResultIds.add(message.toolCallId);
503
+ index -= 1;
504
+ }
505
+ if (toolResultIds.size === 0) return -1;
506
+ const assistant = asOptionalObjectRecord(messages[index]);
507
+ if (assistant?.role !== "assistant" || !Array.isArray(assistant.content)) return -1;
508
+ const toolCallIds = /* @__PURE__ */ new Set();
509
+ for (const block of assistant.content) {
510
+ const record = asOptionalObjectRecord(block);
511
+ if (!record) continue;
512
+ if ((record.type === "toolCall" || record.type === "tool_use" || record.type === "function_call") && typeof record.id === "string") toolCallIds.add(record.id);
513
+ }
514
+ return [...toolResultIds].every((toolCallId) => toolCallIds.has(toolCallId)) ? index : -1;
515
+ }
516
+ //#endregion
517
+ //#region packages/ai/src/providers/anthropic-usage.ts
518
+ const BILLED_USAGE_KEYS = [
519
+ "input",
520
+ "output",
521
+ "cacheRead",
522
+ "cacheWrite",
523
+ "cacheWrite1h",
524
+ "cacheWrite5m"
525
+ ];
526
+ function readAnthropicBilledUsage(usage, missingCacheTokens) {
527
+ return {
528
+ input: readAnthropicUsageTokenCount(usage.input_tokens),
529
+ output: readAnthropicUsageTokenCount(usage.output_tokens),
530
+ cacheRead: readAnthropicUsageTokenCount(usage.cache_read_input_tokens ?? missingCacheTokens),
531
+ cacheWrite: readAnthropicUsageTokenCount(usage.cache_creation_input_tokens ?? missingCacheTokens),
532
+ ...readAnthropicCacheWriteUsage(usage)
533
+ };
534
+ }
535
+ function applyAnthropicBilledUsage(target, resolved) {
536
+ for (const key of BILLED_USAGE_KEYS) {
537
+ const value = resolved[key];
538
+ if (value !== void 0) target[key] = value;
539
+ }
540
+ target.totalTokens = target.input + target.output + target.cacheRead + target.cacheWrite;
541
+ }
542
+ function readAnthropicIterationUsage(value) {
543
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
544
+ const { input, output, cacheRead, cacheWrite, cacheWrite1h, cacheWrite5m } = readAnthropicBilledUsage(value);
545
+ if (input === void 0 || output === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
546
+ return {
547
+ input,
548
+ output,
549
+ cacheRead,
550
+ cacheWrite,
551
+ cacheWrite1h,
552
+ cacheWrite5m
553
+ };
554
+ }
555
+ function readAnthropicUsageTokenCount(value) {
556
+ return asNonNegativeFiniteNumber(value);
557
+ }
558
+ function readAnthropicCacheWriteUsage(usage) {
559
+ if (!usage.cache_creation || typeof usage.cache_creation !== "object") return {};
560
+ const cacheCreation = usage.cache_creation;
561
+ const cacheWrite5m = readAnthropicUsageTokenCount(cacheCreation.ephemeral_5m_input_tokens);
562
+ const cacheWrite1h = readAnthropicUsageTokenCount(cacheCreation.ephemeral_1h_input_tokens);
563
+ return {
564
+ ...cacheWrite5m !== void 0 ? { cacheWrite5m } : {},
565
+ ...cacheWrite1h !== void 0 ? { cacheWrite1h } : {}
566
+ };
567
+ }
568
+ function readAnthropicPromptUsageSnapshot(usage) {
569
+ const input = readAnthropicUsageTokenCount(usage.input_tokens);
570
+ const cacheRead = usage.cache_read_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_read_input_tokens);
571
+ const cacheWrite = usage.cache_creation_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_creation_input_tokens);
572
+ if (input === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
573
+ return {
574
+ input,
575
+ cacheRead,
576
+ cacheWrite
577
+ };
578
+ }
579
+ function readLastAnthropicIterationUsage(usage) {
580
+ if (usage.iterations == null) return { state: "absent" };
581
+ if (!Array.isArray(usage.iterations) || usage.iterations.length === 0) return { state: "invalid" };
582
+ const iteration = readAnthropicIterationUsage(usage.iterations.at(-1));
583
+ if (!iteration) return { state: "invalid" };
584
+ const contextPromptTokens = iteration.input + iteration.cacheRead + iteration.cacheWrite;
585
+ return {
586
+ state: "valid",
587
+ usage: {
588
+ contextPromptTokens,
589
+ totalTokens: contextPromptTokens + iteration.output
590
+ }
591
+ };
592
+ }
593
+ function readAnthropicCompactionBilledUsage(iterations) {
594
+ if (!Array.isArray(iterations) || iterations.length === 0) return;
595
+ let sawCompaction = false;
596
+ const billed = {
597
+ input: 0,
598
+ output: 0,
599
+ cacheRead: 0,
600
+ cacheWrite: 0
601
+ };
602
+ for (const iteration of iterations) {
603
+ const resolved = readAnthropicIterationUsage(iteration);
604
+ if (!resolved) return;
605
+ sawCompaction ||= iteration.type === "compaction";
606
+ for (const key of BILLED_USAGE_KEYS) {
607
+ const value = resolved[key];
608
+ if (value !== void 0) billed[key] = (billed[key] ?? 0) + value;
609
+ }
610
+ }
611
+ return sawCompaction ? billed : void 0;
612
+ }
613
+ /** Record independent billing buckets without treating zero placeholders as context proof. */
614
+ function applyAnthropicMessageStartUsage(target, payload) {
615
+ const promptUsage = readAnthropicPromptUsageSnapshot(payload);
616
+ const promptTokens = promptUsage ? promptUsage.input + promptUsage.cacheRead + promptUsage.cacheWrite : 0;
617
+ const resolved = readAnthropicBilledUsage(payload, 0);
618
+ applyAnthropicBilledUsage(target, resolved);
619
+ if (promptTokens > 0 && resolved.output !== void 0) target.contextUsage = {
620
+ state: "available",
621
+ promptTokens,
622
+ totalTokens: promptTokens + target.output
623
+ };
624
+ return promptTokens > 0 ? promptUsage : void 0;
625
+ }
626
+ /** Keep billing and context distinct; omitted usage preserves the last snapshot. */
627
+ function applyAnthropicMessageDeltaUsage(target, usage, messageStartPromptUsage) {
628
+ if (!usage) return;
629
+ const billedIterations = readAnthropicCompactionBilledUsage(usage.iterations);
630
+ const reported = readAnthropicBilledUsage(usage);
631
+ applyAnthropicBilledUsage(target, {
632
+ ...reported,
633
+ ...billedIterations
634
+ });
635
+ const iterationUsage = readLastAnthropicIterationUsage(usage);
636
+ if (iterationUsage.state === "valid") target.contextUsage = {
637
+ state: "available",
638
+ promptTokens: iterationUsage.usage.contextPromptTokens,
639
+ totalTokens: iterationUsage.usage.totalTokens
640
+ };
641
+ else if (iterationUsage.state === "invalid") target.contextUsage = { state: "unavailable" };
642
+ else if (reported.output !== void 0 && (messageStartPromptUsage !== void 0 || (reported.cacheRead !== void 0 || reported.cacheWrite !== void 0) && readAnthropicPromptUsageSnapshot(usage) !== void 0)) {
643
+ const promptTokens = target.input + target.cacheRead + target.cacheWrite;
644
+ target.contextUsage = {
645
+ state: "available",
646
+ promptTokens,
647
+ totalTokens: promptTokens + target.output
648
+ };
649
+ } else target.contextUsage = { state: "unavailable" };
650
+ }
651
+ //#endregion
433
652
  //#region packages/ai/src/transports/anthropic-compaction-replay.ts
434
653
  const ANTHROPIC_COMPACTION_REPLAY_TYPE = "anthropic-compaction";
435
654
  const ANTHROPIC_COMPACTION_SUPPRESSION_TYPE = "anthropic-compaction-suppression";
@@ -590,52 +809,95 @@ async function normalizeAnthropicInlineContent(content, budget) {
590
809
  return normalized;
591
810
  }
592
811
  //#endregion
593
- //#region packages/ai/src/providers/anthropic-thinking-replay.ts
594
- const ANTHROPIC_OMITTED_REASONING_TEXT = "[assistant reasoning omitted]";
595
- function applyAnthropicThinkingBindingControls(params, directApiKeyBetaHeader) {
596
- if (directApiKeyBetaHeader === void 0 || !isRecord(params.thinking) || params.thinking.type !== "adaptive") return;
597
- params.thinking.block_binding = { prefix_mismatch_behavior: "drop_block" };
598
- const betas = directApiKeyBetaHeader.split(",").map((beta) => beta.trim()).filter(Boolean);
599
- return { "anthropic-beta": [.../* @__PURE__ */ new Set([...betas, "thinking-binding-controls-2026-08-01"])].join(",") };
812
+ //#region packages/ai/src/transports/anthropic-request-body.ts
813
+ const fragments = /* @__PURE__ */ new WeakMap();
814
+ function copyPlainData(value, retainFrozen = false, copies = /* @__PURE__ */ new Map()) {
815
+ if (!value || typeof value !== "object") return value;
816
+ if (retainFrozen && getAiTransportHost().immutableData?.isDeeplyFrozenPlainData(value)) return value;
817
+ if (copies.has(value)) return copies.get(value);
818
+ const copy = Array.isArray(value) ? [] : { ...value };
819
+ if (Array.isArray(value)) Reflect.set(copy, "length", value.length);
820
+ if (Object.getPrototypeOf(value) === null) Object.setPrototypeOf(copy, null);
821
+ copies.set(value, copy);
822
+ for (const key of Reflect.ownKeys(value)) {
823
+ if (Array.isArray(value) && key === "length") continue;
824
+ const child = copyPlainData(Reflect.get(value, key), retainFrozen, copies);
825
+ if (Object.hasOwn(copy, key) || key !== "__proto__" && Object.prototype.propertyIsEnumerable.call(value, key)) Reflect.set(copy, key, child);
826
+ else Object.defineProperty(copy, key, {
827
+ value: child,
828
+ enumerable: Object.prototype.propertyIsEnumerable.call(value, key),
829
+ writable: true,
830
+ configurable: true
831
+ });
832
+ }
833
+ return copy;
834
+ }
835
+ function samePlainData(left, right, seen = /* @__PURE__ */ new Map()) {
836
+ if (Object.is(left, right)) return true;
837
+ if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
838
+ if (isProxy(right) || Object.getPrototypeOf(left) !== Object.getPrototypeOf(right)) return false;
839
+ if (seen.has(left)) return seen.get(left) === right;
840
+ seen.set(left, right);
841
+ const keys = Reflect.ownKeys(left);
842
+ const otherKeys = Reflect.ownKeys(right);
843
+ if (keys.length !== otherKeys.length || Array.isArray(left) && left.length !== Reflect.get(right, "length")) return false;
844
+ let index = 0;
845
+ for (const key of keys) {
846
+ const descriptor = Object.getOwnPropertyDescriptor(right, key);
847
+ if (key !== otherKeys[index++] || descriptor === void 0 || !("value" in descriptor) || Object.prototype.propertyIsEnumerable.call(left, key) !== descriptor.enumerable || !samePlainData(Reflect.get(left, key), descriptor.value, seen)) return false;
848
+ }
849
+ return true;
850
+ }
851
+ /** Hooks receive editable containers; any edit opts the whole request out of fragment reuse. */
852
+ async function applyAnthropicPayloadHook(params, model, options) {
853
+ if (!options?.onPayload) return { params };
854
+ const plain = getAiTransportHost().immutableData?.isPlainData;
855
+ const snapshot = plain?.(params) ? copyPlainData(params, true) : void 0;
856
+ const editable = snapshot ? copyPlainData(params) : {
857
+ ...params,
858
+ messages: params.messages.map((message) => plain?.(message) ? copyPlainData(message) : message)
859
+ };
860
+ const replacement = await options.onPayload(editable, model);
861
+ const unchanged = (replacement === void 0 || replacement === editable) && snapshot !== void 0 && samePlainData(snapshot, editable);
862
+ return {
863
+ params: replacement === void 0 ? editable : replacement,
864
+ messageSources: unchanged ? snapshot.messages : null
865
+ };
600
866
  }
601
- function readAnthropicInputTransformations(event) {
602
- if (!isRecord(event) || event.type !== "message_start" && event.type !== "message_delta") return;
603
- const transformations = (isRecord(event.message) ? event.message : void 0)?.input_transformations ?? event.input_transformations;
604
- return Array.isArray(transformations) ? transformations : void 0;
605
- }
606
- function logAnthropicThinkingDrops(transformations) {
607
- const drops = transformations?.filter((entry) => isRecord(entry) && entry.type === "thinking_dropped" && typeof entry.reason === "string" && /^(?:prefix|model|organization|end_user)_binding_mismatch$/.test(entry.reason) && typeof entry.path === "string" && /^messages\.\d{1,10}\.content\.\d{1,10}$/.test(entry.path));
608
- if (!drops?.length) return;
609
- const paths = drops.slice(0, 5).map(({ reason, path }) => `${reason} at ${path}`);
610
- getAiTransportHost().logWarn("anthropic", `replayed thinking dropped: ${drops.length} block(s) (${paths.join(", ")}${drops.length > 5 ? ", …" : ""})`);
611
- }
612
- /**
613
- * Anthropic tool results continue the preceding assistant turn. Preserve that
614
- * turn's signed thinking even when the next request disables new thinking.
615
- */
616
- function findActiveAnthropicToolTurnAssistantIndex(messages) {
617
- const toolResultIds = /* @__PURE__ */ new Set();
618
- let index = messages.length - 1;
619
- while (index >= 0) {
620
- const message = asOptionalObjectRecord(messages[index]);
621
- if (message?.role === "user" && isRecord(message.operatorMessage)) {
622
- index -= 1;
623
- continue;
867
+ /** Assemble immutable history bytes while encoding the envelope and mutable tail each time. */
868
+ function serializeAnthropicRequestBody(payload, messageSources) {
869
+ const immutable = getAiTransportHost().immutableData;
870
+ if (messageSources === null || !immutable?.isPlainData || messageSources === void 0 && !immutable.isPlainData(payload) || "toJSON" in Object.prototype || "toJSON" in Array.prototype || !Array.isArray(payload.messages)) return JSON.stringify(payload);
871
+ const messages = messageSources ?? payload.messages;
872
+ const parts = [];
873
+ let envelope = "{";
874
+ let separator = "";
875
+ for (const key of Object.keys(payload)) {
876
+ const value = Reflect.get(payload, key);
877
+ if (key === "messages") {
878
+ parts.push(`${envelope}${separator}"messages":[`);
879
+ envelope = "]";
880
+ for (let index = 0; index < messages.length; index++) {
881
+ const message = messages[index];
882
+ const reusable = message !== null && typeof message === "object" && immutable.isDeeplyFrozenPlainData(message);
883
+ let fragment = reusable ? fragments.get(message) : void 0;
884
+ if (!fragment) {
885
+ fragment = new Blob(["," + JSON.stringify(message)]);
886
+ if (reusable) fragments.set(message, fragment);
887
+ }
888
+ parts.push(index === 0 ? fragment.slice(1) : fragment);
889
+ }
890
+ } else {
891
+ const json = JSON.stringify(value);
892
+ if (json === void 0) continue;
893
+ envelope += `${separator}${JSON.stringify(key)}:${json}`;
624
894
  }
625
- if (message?.role !== "toolResult") break;
626
- if (typeof message.toolCallId === "string") toolResultIds.add(message.toolCallId);
627
- index -= 1;
628
- }
629
- if (toolResultIds.size === 0) return -1;
630
- const assistant = asOptionalObjectRecord(messages[index]);
631
- if (assistant?.role !== "assistant" || !Array.isArray(assistant.content)) return -1;
632
- const toolCallIds = /* @__PURE__ */ new Set();
633
- for (const block of assistant.content) {
634
- const record = asOptionalObjectRecord(block);
635
- if (!record) continue;
636
- if ((record.type === "toolCall" || record.type === "tool_use" || record.type === "function_call") && typeof record.id === "string") toolCallIds.add(record.id);
895
+ separator = ",";
637
896
  }
638
- return [...toolResultIds].every((toolCallId) => toolCallIds.has(toolCallId)) ? index : -1;
897
+ parts.push(`${envelope}}`);
898
+ const body = new Blob(parts, { type: "application/json" });
899
+ markEncodedModelRequestBody(body, payload.stream);
900
+ return body;
639
901
  }
640
902
  //#endregion
641
903
  //#region packages/ai/src/transports/anthropic-transport-options.ts
@@ -674,7 +936,6 @@ function resolveAnthropicTransportOptions(model, options, apiKey) {
674
936
  headers: options?.headers,
675
937
  onPayload: options?.onPayload,
676
938
  onResponse: options?.onResponse,
677
- maxRetryDelayMs: options?.maxRetryDelayMs,
678
939
  metadata: options?.metadata,
679
940
  interleavedThinking: options?.interleavedThinking,
680
941
  toolChoice: options?.toolChoice,
@@ -697,7 +958,7 @@ function applyAnthropicThinkingOptions(model, resolved, options, profile) {
697
958
  resolved.thinkingEnabled = false;
698
959
  return reasoning;
699
960
  }
700
- if (!reasoning || supportsClaudeAdaptiveThinking(model) || !managed && defaultsClaudeAdaptiveThinking(model)) {
961
+ if (!reasoning || supportsClaudeAdaptiveThinking(model)) {
701
962
  resolved.thinkingEnabled = Boolean(reasoning) || defaultsClaudeAdaptiveThinking(model);
702
963
  if (resolved.thinkingEnabled) resolved.effort = resolveAnthropicThinkingEffort(model, reasoning);
703
964
  return reasoning;
@@ -725,6 +986,7 @@ function resolveCompletionTokenReservation(model, maxTokens, reasoning) {
725
986
  }
726
987
  //#endregion
727
988
  //#region packages/ai/src/transports/anthropic-messages.ts
989
+ const anthropicMessageProjections = /* @__PURE__ */ new WeakMap();
728
990
  const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
729
991
  async function convertContentBlocks(content, model, imageBudget, profile, isError) {
730
992
  const mediaPlaceholder = describeToolResultMediaPlaceholder(content);
@@ -734,18 +996,16 @@ async function convertContentBlocks(content, model, imageBudget, profile, isErro
734
996
  }
735
997
  const blocks = [];
736
998
  for (const block of content) {
737
- const record = asOptionalObjectRecord(block);
738
- if (!record) continue;
999
+ if (!asOptionalObjectRecord(block)) continue;
739
1000
  const blockText = extractToolResultBlockText(block);
740
1001
  if (blockText) blocks.push({
741
1002
  type: "text",
742
1003
  text: blockText
743
1004
  });
744
- if (!isImageWithMediaPayload(record)) continue;
745
- const [normalizedImage] = await normalizeAnthropicInlineContent([{
746
- type: "image",
747
- data: record.data,
748
- mimeType: typeof record.mimeType === "string" ? record.mimeType : profile === "provider" ? "image/jpeg" : "image/png"
1005
+ if (!isImageWithMediaPayload(block)) continue;
1006
+ const [normalizedImage] = await normalizeAnthropicInlineContent([typeof block.mimeType === "string" ? block : {
1007
+ ...block,
1008
+ mimeType: profile === "provider" ? "image/jpeg" : "image/png"
749
1009
  }], imageBudget);
750
1010
  if (normalizedImage?.type !== "image") continue;
751
1011
  blocks.push({
@@ -763,38 +1023,61 @@ async function convertContentBlocks(content, model, imageBudget, profile, isErro
763
1023
  });
764
1024
  return blocks;
765
1025
  }
766
- async function convertAnthropicMessages(transformedMessages, model, isOAuthToken, options) {
767
- const params = [];
1026
+ /** Assemble both public Messages routes without changing their replay/default profiles. */
1027
+ async function buildAnthropicRequest(model, context, options, profile, isOAuthToken, serverSideFallback, claudeCodeVersion) {
1028
+ const managed = profile === "transport";
1029
+ const maxTokens = managed ? resolveAnthropicMessagesMaxTokens({
1030
+ modelContextWindow: model.contextWindow,
1031
+ modelMaxTokens: model.maxTokens,
1032
+ requestedMaxTokens: options?.maxTokens
1033
+ }) : options?.maxTokens ?? model.maxTokens;
1034
+ if (managed && maxTokens === void 0) throw new Error(`Anthropic Messages transport requires a positive maxTokens value for ${model.provider}/${model.id}`);
1035
+ const { cacheControl, supportsCacheControlOnTools } = resolveAnthropicCacheOptions(model, options?.cacheRetention);
1036
+ const system = buildAnthropicSystemBlocks(context.systemPrompt, isOAuthToken, cacheControl, claudeCodeVersion);
1037
+ let toolProjection;
1038
+ let eagerToolInputStreaming = false;
1039
+ if (context.tools) {
1040
+ const tools = context.tools;
1041
+ eagerToolInputStreaming = !managed && (model.compat?.supportsEagerToolInputStreaming ?? model.provider !== "fireworks");
1042
+ toolProjection = projectAnthropicTools(tools, (name) => isOAuthToken ? toClaudeCodeToolName(name) : name);
1043
+ }
1044
+ const replayPlan = buildAnthropicReplayPlan(context.messages, model, {
1045
+ enabled: !isOAuthToken && options?.anthropicServerCompaction === true,
1046
+ authProfileId: options?.authProfileId,
1047
+ sessionId: options?.sessionId
1048
+ });
1049
+ const cacheBreakpointOptOutMessageIndexes = /* @__PURE__ */ new Set();
1050
+ const transformed = managed ? getAiTransportHost().transformTransportMessages(replayPlan.messages, model, normalizeAnthropicToolCallId, { preserveUnframedToolResults: preparedRequestSuffix.has(context) }) : transformProviderMessages(replayPlan.messages, model, normalizeAnthropicToolCallId);
1051
+ const allowReasoningContentReplay = managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native";
1052
+ const allowEmptySignature = model.compat?.allowEmptySignature;
1053
+ const compaction = replayPlan.compaction;
1054
+ const replayThinkingEnabled = requiresClaudeAdaptiveThinking(model) || options?.thinkingEnabled === true;
1055
+ const messages = [];
768
1056
  const appendMessage = (message) => {
769
- if (message.role === "system" && (!params.length || params.at(-1)?.role === "assistant")) params.push({
1057
+ if (message.role === "system" && (!messages.length || messages.at(-1)?.role === "assistant")) messages.push({
770
1058
  role: "user",
771
1059
  content: "."
772
1060
  });
773
- if (message.role === "user" && params.at(-1)?.role === "system") params.push({
1061
+ if (message.role === "user" && messages.at(-1)?.role === "system") messages.push({
774
1062
  role: "assistant",
775
1063
  content: [{
776
1064
  type: "text",
777
1065
  text: STREAM_ERROR_FALLBACK_TEXT
778
1066
  }]
779
1067
  });
780
- params.push(message);
1068
+ messages.push(message);
781
1069
  };
782
1070
  const modelRetainsRuntimeContext = bindsClaudeThinkingPrefix(model);
783
1071
  const inHistorySystemUpdates = !isOAuthToken && isDirectAnthropicModel(model) && supportsClaudeInHistorySystemMessages(model);
784
1072
  const imageBudget = createAnthropicInlineImageBudget();
785
- const allowReasoningContentReplay = options.allowReasoningContentReplay === true;
786
- const replayThinkingEnabled = options.replayThinkingEnabled !== false;
787
- const managed = options.profile === "transport";
788
- const activeToolTurnAssistantIndex = replayThinkingEnabled ? -1 : findActiveAnthropicToolTurnAssistantIndex(transformedMessages);
789
- for (let i = 0; i < transformedMessages.length; i += 1) {
790
- const msg = transformedMessages[i];
791
- if (!msg) continue;
1073
+ const activeToolTurnAssistantIndex = replayThinkingEnabled ? -1 : findActiveAnthropicToolTurnAssistantIndex(transformed);
1074
+ const convertMessage = async (msg, i, end) => {
792
1075
  if (msg.role === "user") {
793
1076
  const operatorMessage = inHistorySystemUpdates ? msg.operatorMessage : void 0;
794
1077
  const sourceContent = msg.content;
795
1078
  let content;
796
1079
  if (typeof sourceContent === "string") {
797
- if (sourceContent.trim().length === 0) continue;
1080
+ if (sourceContent.trim().length === 0) return;
798
1081
  content = sanitizeTransportPayloadText(sourceContent);
799
1082
  } else {
800
1083
  content = (!managed || model.input.includes("image") ? await normalizeAnthropicInlineContent(sourceContent, imageBudget) : sourceContent.map((item) => item.type === "image" ? {
@@ -811,22 +1094,19 @@ async function convertAnthropicMessages(transformedMessages, model, isOAuthToken
811
1094
  data: item.data
812
1095
  }
813
1096
  }).filter((block) => block.type === "text" ? block.text.trim().length > 0 : !managed || model.input.includes("image"));
814
- if (content.length === 0) continue;
1097
+ if (content.length === 0) return;
815
1098
  }
816
- appendMessage({
1099
+ return {
817
1100
  role: operatorMessage ? "system" : "user",
818
1101
  content: operatorMessage ? typeof content === "string" ? [{
819
1102
  type: "text",
820
1103
  text: content
821
1104
  }] : content.filter((block) => block.type === "text") : content,
822
1105
  ...operatorMessage?.turnScoped ? { clear_at: "next_user_message" } : {}
823
- });
824
- const runtimeContextRetained = msg.runtimeContext !== void 0 ? msg.runtimeContext.retained : msg.runtimeContextCarrierRetained;
825
- if (hasRuntimeContextMarker(msg) && !(runtimeContextRetained ?? modelRetainsRuntimeContext)) options.cacheBreakpointOptOutMessageIndexes?.add(params.length - 1);
826
- continue;
1106
+ };
827
1107
  }
828
1108
  if (msg.role === "assistant") {
829
- const blocks = i === 0 && options.compaction ? [options.compaction] : [];
1109
+ const blocks = i === 0 && compaction ? [compaction] : [];
830
1110
  const reasoningContent = [];
831
1111
  let omittedThinking = false;
832
1112
  for (const block of msg.content) {
@@ -854,7 +1134,7 @@ async function convertAnthropicMessages(transformedMessages, model, isOAuthToken
854
1134
  }
855
1135
  const hasNativeThinkingSignature = Boolean(thinkingSignature) && !isReasoningContent;
856
1136
  if (block.thinking.trim().length === 0 && !hasNativeThinkingSignature) continue;
857
- if (!thinkingSignature && !options.allowEmptySignature) blocks.push({
1137
+ if (!thinkingSignature && !allowEmptySignature) blocks.push({
858
1138
  type: "text",
859
1139
  text: sanitizeTransportPayloadText(block.thinking)
860
1140
  });
@@ -891,40 +1171,103 @@ async function convertAnthropicMessages(transformedMessages, model, isOAuthToken
891
1171
  thinking: "",
892
1172
  signature: "reasoning_content"
893
1173
  });
894
- params.push(assistantMsg);
1174
+ return assistantMsg;
895
1175
  }
896
- continue;
1176
+ return;
897
1177
  }
898
1178
  if (msg.role === "toolResult") {
899
1179
  const toolResults = [];
900
- let j = i;
901
- while (j < transformedMessages.length) {
902
- const nextMsg = transformedMessages.at(j);
1180
+ for (let j = i; j < end; j++) {
1181
+ const nextMsg = transformed.at(j);
903
1182
  if (nextMsg?.role !== "toolResult") break;
904
1183
  toolResults.push({
905
1184
  type: "tool_result",
906
- tool_use_id: preparedRequestSuffix.has(options.context) ? preparedRequestSuffix.toolCallId(options.context, nextMsg.toolCallId, normalizeAnthropicToolCallId(nextMsg.toolCallId)) : nextMsg.toolCallId,
907
- content: await convertContentBlocks(nextMsg.content, model, imageBudget, options.profile, nextMsg.isError),
1185
+ tool_use_id: preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, nextMsg.toolCallId, normalizeAnthropicToolCallId(nextMsg.toolCallId)) : nextMsg.toolCallId,
1186
+ content: await convertContentBlocks(nextMsg.content, model, imageBudget, profile, nextMsg.isError),
908
1187
  is_error: nextMsg.isError
909
1188
  });
910
- j += 1;
911
1189
  }
912
- i = j - 1;
913
- appendMessage({
1190
+ return {
914
1191
  role: "user",
915
1192
  content: toolResults
916
- });
1193
+ };
1194
+ }
1195
+ };
1196
+ const immutable = getAiTransportHost().immutableData;
1197
+ const projectionKey = JSON.stringify([
1198
+ profile,
1199
+ model.provider,
1200
+ model.api,
1201
+ model.id,
1202
+ model.baseUrl,
1203
+ model.input.includes("image"),
1204
+ isOAuthToken,
1205
+ allowReasoningContentReplay,
1206
+ allowEmptySignature,
1207
+ replayThinkingEnabled,
1208
+ inHistorySystemUpdates
1209
+ ]);
1210
+ const activeProjectionKey = `${projectionKey}:active`;
1211
+ const canReuse = (message) => Boolean(immutable?.isPlainData) && immutable?.isDeeplyFrozenPlainData(message) && (typeof message.content === "string" || !message.content.some((block) => block.type === "image"));
1212
+ for (let i = 0; i < transformed.length;) {
1213
+ const msg = transformed[i];
1214
+ if (!msg) {
1215
+ i++;
1216
+ continue;
1217
+ }
1218
+ let end = i + 1;
1219
+ if (msg.role === "toolResult") while (transformed[end]?.role === "toolResult") end++;
1220
+ let reusable = !compaction && !preparedRequestSuffix.has(context) && canReuse(msg);
1221
+ for (let j = i + 1; reusable && j < end; j++) {
1222
+ const following = transformed[j];
1223
+ reusable = following !== void 0 && canReuse(following);
1224
+ }
1225
+ const key = i === activeToolTurnAssistantIndex ? activeProjectionKey : projectionKey;
1226
+ let projections = reusable ? anthropicMessageProjections.get(msg) : void 0;
1227
+ const projection = projections?.find((entry) => entry.key === key && entry.followingSources.length === end - i - 1 && entry.followingSources.every((source, index) => source === transformed[i + index + 1]));
1228
+ let output = projection?.message;
1229
+ if (!projection) {
1230
+ output = await convertMessage(msg, i, end);
1231
+ if (reusable && immutable) {
1232
+ immutable.freezeJsonSnapshot(output);
1233
+ if (!projections) {
1234
+ projections = [];
1235
+ anthropicMessageProjections.set(msg, projections);
1236
+ }
1237
+ if (projections.length >= 8) projections.shift();
1238
+ projections.push({
1239
+ key,
1240
+ followingSources: transformed.slice(i + 1, end),
1241
+ message: output
1242
+ });
1243
+ }
1244
+ }
1245
+ if (output) {
1246
+ appendMessage(output);
1247
+ if (msg.role === "user") {
1248
+ const runtimeContextRetained = msg.runtimeContext !== void 0 ? msg.runtimeContext.retained : msg.runtimeContextCarrierRetained;
1249
+ if (hasRuntimeContextMarker(msg) && !(runtimeContextRetained ?? modelRetainsRuntimeContext)) cacheBreakpointOptOutMessageIndexes.add(messages.length - 1);
1250
+ }
917
1251
  }
1252
+ i = end;
918
1253
  }
919
- return params;
920
- }
921
- /** Shared generation contract, after each entry point resolves its defaults and tool policy. */
922
- function buildAnthropicGenerationParams({ model, options, toolProjection, eagerToolInputStreaming, profile }) {
923
- const params = {};
1254
+ if (managed && messages.length === 0) messages.push({
1255
+ role: "user",
1256
+ content: "."
1257
+ });
1258
+ const params = {
1259
+ model: managed && isDirectAnthropicModel(model) ? model.id.replace(/^anthropic\//i, "") : model.id,
1260
+ messages,
1261
+ max_tokens: maxTokens ?? model.maxTokens,
1262
+ stream: true
1263
+ };
1264
+ if (system) params.system = system;
1265
+ if (serverSideFallback) Object.assign(params, { fallbacks: ANTHROPIC_SERVER_SIDE_FALLBACKS });
1266
+ const generationParams = {};
924
1267
  const mandatoryAdaptiveThinking = requiresClaudeAdaptiveThinking(model);
925
- if (options?.temperature !== void 0 && !options?.thinkingEnabled && !supportsClaudeNativeXhighEffort(model)) params.temperature = options.temperature;
926
- if (options?.stop !== void 0 && options.stop.length > 0) params.stop_sequences = options.stop;
927
- if (toolProjection && toolProjection.tools.length > 0) params.tools = toolProjection.tools.map((tool) => ({
1268
+ if (options?.temperature !== void 0 && !options?.thinkingEnabled && !supportsClaudeNativeXhighEffort(model)) generationParams.temperature = options.temperature;
1269
+ if (options?.stop !== void 0 && options.stop.length > 0) generationParams.stop_sequences = options.stop;
1270
+ if (toolProjection && toolProjection.tools.length > 0) generationParams.tools = toolProjection.tools.map((tool) => ({
928
1271
  name: tool.wireName,
929
1272
  description: tool.description,
930
1273
  input_schema: tool.inputSchema,
@@ -934,82 +1277,29 @@ function buildAnthropicGenerationParams({ model, options, toolProjection, eagerT
934
1277
  if (mandatoryAdaptiveThinking || options?.thinkingEnabled) {
935
1278
  const display = options?.thinkingDisplay ?? "summarized";
936
1279
  if (supportsClaudeAdaptiveThinking(model)) {
937
- params.thinking = {
1280
+ generationParams.thinking = {
938
1281
  type: "adaptive",
939
1282
  display
940
1283
  };
941
1284
  const effort = options?.effort ?? (mandatoryAdaptiveThinking ? resolveAnthropicThinkingEffort(model, void 0) : void 0);
942
- if (effort) params.output_config = { effort };
943
- } else params.thinking = {
1285
+ if (effort) generationParams.output_config = { effort };
1286
+ } else generationParams.thinking = {
944
1287
  type: "enabled",
945
1288
  budget_tokens: options?.thinkingBudgetTokens ?? 1024,
946
1289
  ...profile === "provider" ? { display } : {}
947
1290
  };
948
- } else if (options?.thinkingEnabled === false) params.thinking = requiresClaudeBetweenToolsThinking(model) ? { type: "between_tools" } : { type: "disabled" };
1291
+ } else if (options?.thinkingEnabled === false) generationParams.thinking = requiresClaudeBetweenToolsThinking(model) ? { type: "between_tools" } : { type: "disabled" };
949
1292
  }
950
1293
  if (options?.metadata) {
951
1294
  const userId = options.metadata.user_id;
952
- if (typeof userId === "string") params.metadata = { user_id: userId };
1295
+ if (typeof userId === "string") generationParams.metadata = { user_id: userId };
953
1296
  }
954
1297
  if (options?.toolChoice) {
955
1298
  const normalizedToolChoice = normalizeAnthropicToolChoice(resolveClaudeHaiku55ModelIdentity(model) === void 0 && (mandatoryAdaptiveThinking || options?.thinkingEnabled === true || resolveClaudeSonnet55ModelIdentity(model) !== void 0), options.toolChoice);
956
1299
  const projectedToolChoice = toolProjection ? reconcileAnthropicToolChoice(normalizedToolChoice, toolProjection) : normalizedToolChoice;
957
- if (projectedToolChoice) params.tool_choice = projectedToolChoice;
1300
+ if (projectedToolChoice) generationParams.tool_choice = projectedToolChoice;
958
1301
  }
959
- return params;
960
- }
961
- /** Assemble both public Messages routes without changing their replay/default profiles. */
962
- async function buildAnthropicRequest(model, context, options, profile, isOAuthToken, serverSideFallback, claudeCodeVersion) {
963
- const managed = profile === "transport";
964
- const maxTokens = managed ? resolveAnthropicMessagesMaxTokens({
965
- modelContextWindow: model.contextWindow,
966
- modelMaxTokens: model.maxTokens,
967
- requestedMaxTokens: options?.maxTokens
968
- }) : options?.maxTokens ?? model.maxTokens;
969
- if (managed && maxTokens === void 0) throw new Error(`Anthropic Messages transport requires a positive maxTokens value for ${model.provider}/${model.id}`);
970
- const { cacheControl, supportsCacheControlOnTools } = resolveAnthropicCacheOptions(model, options?.cacheRetention);
971
- const system = buildAnthropicSystemBlocks(context.systemPrompt, isOAuthToken, cacheControl, claudeCodeVersion);
972
- let toolProjection;
973
- let eagerToolInputStreaming = false;
974
- if (context.tools) {
975
- const tools = context.tools;
976
- eagerToolInputStreaming = !managed && (model.compat?.supportsEagerToolInputStreaming ?? model.provider !== "fireworks");
977
- toolProjection = projectAnthropicTools(tools, (name) => isOAuthToken ? toClaudeCodeToolName(name) : name);
978
- }
979
- const replayPlan = buildAnthropicReplayPlan(context.messages, model, {
980
- enabled: !isOAuthToken && options?.anthropicServerCompaction === true,
981
- authProfileId: options?.authProfileId,
982
- sessionId: options?.sessionId
983
- });
984
- const cacheBreakpointOptOutMessageIndexes = /* @__PURE__ */ new Set();
985
- const messages = await convertAnthropicMessages(managed ? getAiTransportHost().transformTransportMessages(replayPlan.messages, model, normalizeAnthropicToolCallId, { preserveUnframedToolResults: preparedRequestSuffix.has(context) }) : transformProviderMessages(replayPlan.messages, model, normalizeAnthropicToolCallId), model, isOAuthToken, {
986
- profile,
987
- context,
988
- allowReasoningContentReplay: managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native",
989
- allowEmptySignature: model.compat?.allowEmptySignature,
990
- compaction: replayPlan.compaction,
991
- replayThinkingEnabled: requiresClaudeAdaptiveThinking(model) || options?.thinkingEnabled === true,
992
- cacheBreakpointOptOutMessageIndexes
993
- });
994
- if (managed && messages.length === 0) messages.push({
995
- role: "user",
996
- content: "."
997
- });
998
- const params = {
999
- model: managed && isDirectAnthropicModel(model) ? model.id.replace(/^anthropic\//i, "") : model.id,
1000
- messages,
1001
- max_tokens: maxTokens ?? model.maxTokens,
1002
- stream: true
1003
- };
1004
- if (system) params.system = system;
1005
- if (serverSideFallback) Object.assign(params, { fallbacks: ANTHROPIC_SERVER_SIDE_FALLBACKS });
1006
- Object.assign(params, buildAnthropicGenerationParams({
1007
- model,
1008
- options,
1009
- toolProjection,
1010
- eagerToolInputStreaming,
1011
- profile
1012
- }));
1302
+ Object.assign(params, generationParams);
1013
1303
  applyAnthropicRequestCacheControl(params, cacheControl, supportsCacheControlOnTools, cacheBreakpointOptOutMessageIndexes);
1014
1304
  return {
1015
1305
  params,
@@ -1021,487 +1311,393 @@ async function buildAnthropicRequest(model, context, options, profile, isOAuthTo
1021
1311
  async function prepareAnthropicRequest(initialParams, model, options, directApiKeyBetaHeader) {
1022
1312
  let params = initialParams;
1023
1313
  applyAnthropicContextManagementToRequest(params, model, options, directApiKeyBetaHeader);
1024
- const nextParams = await options?.onPayload?.(params, model);
1025
- if (nextParams !== void 0) params = nextParams;
1314
+ const hooked = await applyAnthropicPayloadHook(params, model, options);
1315
+ params = hooked.params;
1026
1316
  applyClaudeRequestContract(params, model);
1027
1317
  const betaHeader = resolveAnthropicRequestBetaHeader(params, directApiKeyBetaHeader);
1028
1318
  const headers = applyAnthropicThinkingBindingControls(params, betaHeader) ?? (betaHeader ? { "anthropic-beta": betaHeader } : void 0);
1029
1319
  return {
1030
1320
  params,
1031
- headers
1032
- };
1033
- }
1034
- //#endregion
1035
- //#region packages/ai/src/providers/anthropic-refusal.ts
1036
- function applyAnthropicRefusal(output, stopDetails, provider) {
1037
- const record = asOptionalObjectRecord(stopDetails);
1038
- const details = {
1039
- category: normalizeNullableString(record?.category),
1040
- explanation: normalizeNullableString(record?.explanation)
1321
+ headers,
1322
+ messageSources: hooked.messageSources
1041
1323
  };
1042
- const category = details.category ? ` (category: ${details.category})` : "";
1043
- const explanation = details.explanation ? `: ${details.explanation}` : ".";
1044
- output.stopReason = "error";
1045
- output.errorMessage = `Anthropic refusal${category}${explanation}`;
1046
- output.diagnostics = [...output.diagnostics ?? [], {
1047
- type: "provider_refusal",
1048
- timestamp: Date.now(),
1049
- details: {
1050
- provider,
1051
- category: details.category,
1052
- explanation: details.explanation
1053
- }
1054
- }];
1055
1324
  }
1056
1325
  //#endregion
1057
- //#region packages/ai/src/providers/anthropic-usage.ts
1058
- const BILLED_USAGE_KEYS = [
1059
- "input",
1060
- "output",
1061
- "cacheRead",
1062
- "cacheWrite",
1063
- "cacheWrite1h"
1064
- ];
1065
- function readAnthropicBilledUsage(usage, missingCacheTokens) {
1066
- return {
1067
- input: readAnthropicUsageTokenCount(usage.input_tokens),
1068
- output: readAnthropicUsageTokenCount(usage.output_tokens),
1069
- cacheRead: readAnthropicUsageTokenCount(usage.cache_read_input_tokens ?? missingCacheTokens),
1070
- cacheWrite: readAnthropicUsageTokenCount(usage.cache_creation_input_tokens ?? missingCacheTokens),
1071
- cacheWrite1h: readAnthropicCacheWriteUsage(usage).cacheWrite1h
1072
- };
1073
- }
1074
- function applyAnthropicBilledUsage(target, resolved) {
1075
- for (const key of BILLED_USAGE_KEYS) {
1076
- const value = resolved[key];
1077
- if (value !== void 0) target[key] = value;
1078
- }
1079
- target.totalTokens = target.input + target.output + target.cacheRead + target.cacheWrite;
1080
- }
1081
- function readAnthropicIterationUsage(value) {
1082
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
1083
- const { input, output, cacheRead, cacheWrite, cacheWrite1h } = readAnthropicBilledUsage(value);
1084
- if (input === void 0 || output === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
1085
- return {
1086
- input,
1087
- output,
1088
- cacheRead,
1089
- cacheWrite,
1090
- cacheWrite1h: cacheWrite1h ?? 0
1091
- };
1092
- }
1093
- function readAnthropicUsageTokenCount(value) {
1094
- return asNonNegativeFiniteNumber(value);
1095
- }
1096
- function readAnthropicCacheWriteUsage(usage) {
1097
- if (!usage.cache_creation || typeof usage.cache_creation !== "object") return {};
1098
- const cacheCreation = usage.cache_creation;
1099
- const cacheWrite5m = readAnthropicUsageTokenCount(cacheCreation.ephemeral_5m_input_tokens);
1100
- const cacheWrite1h = readAnthropicUsageTokenCount(cacheCreation.ephemeral_1h_input_tokens);
1101
- return {
1102
- ...cacheWrite5m !== void 0 ? { cacheWrite5m } : {},
1103
- ...cacheWrite1h !== void 0 ? { cacheWrite1h } : {}
1104
- };
1105
- }
1106
- function readAnthropicPromptUsageSnapshot(usage) {
1107
- const input = readAnthropicUsageTokenCount(usage.input_tokens);
1108
- const cacheRead = usage.cache_read_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_read_input_tokens);
1109
- const cacheWrite = usage.cache_creation_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_creation_input_tokens);
1110
- if (input === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
1111
- return {
1112
- input,
1113
- cacheRead,
1114
- cacheWrite
1115
- };
1116
- }
1117
- function readLastAnthropicIterationUsage(usage) {
1118
- if (usage.iterations == null) return { state: "absent" };
1119
- if (!Array.isArray(usage.iterations) || usage.iterations.length === 0) return { state: "invalid" };
1120
- const iteration = readAnthropicIterationUsage(usage.iterations.at(-1));
1121
- if (!iteration) return { state: "invalid" };
1122
- const contextPromptTokens = iteration.input + iteration.cacheRead + iteration.cacheWrite;
1123
- return {
1124
- state: "valid",
1125
- usage: {
1126
- contextPromptTokens,
1127
- totalTokens: contextPromptTokens + iteration.output
1128
- }
1129
- };
1130
- }
1131
- function readAnthropicCompactionBilledUsage(iterations) {
1132
- if (!Array.isArray(iterations) || iterations.length === 0) return;
1133
- let sawCompaction = false;
1134
- const billed = {
1135
- input: 0,
1136
- output: 0,
1137
- cacheRead: 0,
1138
- cacheWrite: 0,
1139
- cacheWrite1h: 0
1140
- };
1141
- for (const iteration of iterations) {
1142
- const resolved = readAnthropicIterationUsage(iteration);
1143
- if (!resolved) return;
1144
- sawCompaction ||= iteration.type === "compaction";
1145
- for (const key of BILLED_USAGE_KEYS) billed[key] += resolved[key];
1146
- }
1147
- return sawCompaction ? billed : void 0;
1148
- }
1149
- /** Record independent billing buckets without treating zero placeholders as context proof. */
1150
- function applyAnthropicMessageStartUsage(target, payload) {
1151
- const promptUsage = readAnthropicPromptUsageSnapshot(payload);
1152
- const promptTokens = promptUsage ? promptUsage.input + promptUsage.cacheRead + promptUsage.cacheWrite : 0;
1153
- const resolved = readAnthropicBilledUsage(payload, 0);
1154
- applyAnthropicBilledUsage(target, resolved);
1155
- if (promptTokens > 0 && resolved.output !== void 0) target.contextUsage = {
1156
- state: "available",
1157
- promptTokens,
1158
- totalTokens: promptTokens + target.output
1159
- };
1160
- return promptTokens > 0 ? promptUsage : void 0;
1161
- }
1162
- /** Keep billing and context distinct; omitted usage preserves the last snapshot. */
1163
- function applyAnthropicMessageDeltaUsage(target, usage, messageStartPromptUsage) {
1164
- if (!usage) return;
1165
- const billedIterations = readAnthropicCompactionBilledUsage(usage.iterations);
1166
- const reported = readAnthropicBilledUsage(usage);
1167
- applyAnthropicBilledUsage(target, billedIterations ?? reported);
1168
- const iterationUsage = readLastAnthropicIterationUsage(usage);
1169
- if (iterationUsage.state === "valid") target.contextUsage = {
1170
- state: "available",
1171
- promptTokens: iterationUsage.usage.contextPromptTokens,
1172
- totalTokens: iterationUsage.usage.totalTokens
1173
- };
1174
- else if (iterationUsage.state === "invalid") target.contextUsage = { state: "unavailable" };
1175
- else if (reported.output !== void 0 && (messageStartPromptUsage !== void 0 || (reported.cacheRead !== void 0 || reported.cacheWrite !== void 0) && readAnthropicPromptUsageSnapshot(usage) !== void 0)) {
1176
- const promptTokens = target.input + target.cacheRead + target.cacheWrite;
1177
- target.contextUsage = {
1178
- state: "available",
1179
- promptTokens,
1180
- totalTokens: promptTokens + target.output
1181
- };
1182
- } else target.contextUsage = { state: "unavailable" };
1183
- }
1184
- //#endregion
1185
- //#region packages/ai/src/transports/anthropic-stream-reducer.ts
1186
- /** One Messages protocol reducer; entry points retain their established preview/replay contracts. */
1187
- async function consumeAnthropicStream(params) {
1188
- const { model, options, output, stream, refusalBuffer, isOAuthToken, toolProjection } = params;
1189
- const managed = params.profile === "transport";
1190
- const eventSink = refusalBuffer ?? stream;
1191
- let costModel = model;
1192
- let messageStartPromptUsage;
1193
- let inputTransformations;
1326
+ //#region packages/ai/src/transports/anthropic-stream-lifecycle.ts
1327
+ /** Entry points retain their SDK/fetch adapters; request and terminal ownership is shared. */
1328
+ async function runAnthropicStreamLifecycle(params) {
1329
+ const { model, stream, options, profile } = params;
1330
+ const output = createAssistantOutput(model, "anthropic-messages");
1331
+ const refusalBuffer = usesClaudeStreamingRefusalContract(model) ? createDeferredEventBuffer(stream) : void 0;
1332
+ let replayedCompaction;
1194
1333
  try {
1195
- const blocks = output.content;
1196
- const blockIndexes = /* @__PURE__ */ new Map();
1197
- const toolArgumentPreviewSchedules = /* @__PURE__ */ new WeakMap();
1198
- const seededToolArguments = /* @__PURE__ */ new WeakMap();
1199
- const sealedToolCalls = [];
1200
- const compactionCapture = createCompactionCapture(output, model, options);
1201
- const pendingThinkingSignatures = /* @__PURE__ */ new Map();
1202
- const allowReasoningContentReplay = managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native";
1203
- const reasoningContentBlocks = {
1204
- thinking: /* @__PURE__ */ new Map(),
1205
- text: /* @__PURE__ */ new Map()
1206
- };
1207
- let sawMessageStart = false;
1208
- let sawMessageStop = false;
1209
- let sawStopReason = false;
1210
- const emitContentEnd = (block, contentIndex) => {
1211
- eventSink.push({
1212
- type: `${block.type}_end`,
1213
- contentIndex,
1214
- content: block.type === "thinking" ? block.thinking : block.text,
1215
- partial: output
1216
- });
1334
+ const prepared = await params.prepare();
1335
+ const built = await buildAnthropicRequest(model, prepared.context, prepared.options, profile, prepared.isOAuthToken, prepared.serverSideFallback, prepared.claudeCodeVersion);
1336
+ replayedCompaction = built.replayedCompaction;
1337
+ const { params: body, headers, messageSources } = await prepareAnthropicRequest(built.params, model, prepared.options, prepared.directApiKeyBetaHeader);
1338
+ const wireBody = {
1339
+ ...body,
1340
+ stream: true
1217
1341
  };
1218
- const emitContentStart = (kind, contentIndex, delta = "") => {
1219
- eventSink.push({
1220
- type: `${kind}_start`,
1221
- contentIndex,
1222
- partial: output
1223
- });
1224
- if (delta.length > 0) eventSink.push({
1225
- type: `${kind}_delta`,
1226
- contentIndex,
1227
- delta,
1228
- partial: output
1229
- });
1230
- };
1231
- const appendContentDelta = (block, contentIndex, delta) => {
1232
- if (block.type === "thinking") appendAssistantThinking(block, delta);
1233
- else block.text += delta;
1234
- eventSink.push({
1235
- type: `${block.type}_delta`,
1236
- contentIndex,
1237
- delta,
1238
- partial: output
1239
- });
1240
- };
1241
- const eventIndexKey = (eventIndex) => typeof eventIndex === "number" ? eventIndex : -1;
1242
- const appendReasoningContentDelta = (kind, eventIndex, rawText) => {
1243
- if (typeof rawText !== "string") return false;
1244
- const text = sanitizeTransportPayloadText(rawText);
1245
- if (text.length === 0) return false;
1246
- const indexes = reasoningContentBlocks[kind];
1247
- const key = eventIndexKey(eventIndex);
1248
- let contentIndex = indexes.get(key);
1249
- let block = contentIndex === void 0 ? void 0 : blocks[contentIndex];
1250
- if (contentIndex === void 0 || !block || block.type !== kind) {
1251
- block = kind === "thinking" ? {
1252
- type: "thinking",
1253
- thinking: "",
1254
- thinkingSignature: "reasoning_content"
1255
- } : {
1256
- type: "text",
1257
- text: ""
1342
+ const { response, events } = await prepared.request(wireBody, headers, () => serializeAnthropicRequestBody(wireBody, messageSources));
1343
+ await notifyProviderHttpResponse({
1344
+ options: prepared.options,
1345
+ response,
1346
+ model
1347
+ });
1348
+ await prepared.checkResponse?.(response);
1349
+ await (async () => {
1350
+ const reducerOptions = prepared.options ?? {};
1351
+ const isOAuthToken = prepared.isOAuthToken;
1352
+ const toolProjection = built.toolProjection;
1353
+ const managed = profile === "transport";
1354
+ const eventSink = refusalBuffer ?? stream;
1355
+ let costModel = model;
1356
+ const applyServingModelCost = (servingModelId) => {
1357
+ costModel = {
1358
+ ...model,
1359
+ cost: resolveAnthropicFallbackServingModelCost({
1360
+ requestedModelId: model.id,
1361
+ servingModelId,
1362
+ requestedCost: model.cost
1363
+ })
1258
1364
  };
1259
- output.content.push(block);
1260
- contentIndex = output.content.length - 1;
1261
- indexes.set(key, contentIndex);
1262
- emitContentStart(kind, contentIndex);
1263
- }
1264
- if (block.type === "thinking") block.thinkingSignature = "reasoning_content";
1265
- appendContentDelta(block, contentIndex, text);
1266
- return true;
1267
- };
1268
- const finishReasoningContentSidecars = (eventIndex) => {
1269
- const key = eventIndexKey(eventIndex);
1270
- for (const kind of ["thinking", "text"]) {
1271
- const indexes = reasoningContentBlocks[kind];
1272
- const contentIndex = indexes.get(key);
1273
- if (contentIndex === void 0) continue;
1274
- indexes.delete(key);
1275
- const block = output.content[contentIndex];
1276
- if (block?.type === kind) emitContentEnd(block, contentIndex);
1277
- }
1278
- };
1279
- for await (const rawEvent of iterateModelStream(params.events, options.signal)) {
1280
- const event = asRecord(rawEvent);
1281
- inputTransformations = readAnthropicInputTransformations(event) ?? inputTransformations;
1282
- if (managed) notifyLlmRequestActivity(options.signal);
1283
- if (event.type === "error") {
1284
- const error = asOptionalObjectRecord(event.error);
1285
- throw Object.assign(new Error(readStringField(error, "message") || "Anthropic Messages stream failed"), { error });
1286
- }
1287
- if (event.type === "message_start") {
1288
- sawMessageStart = true;
1289
- const message = asOptionalObjectRecord(event.message);
1290
- const usage = asRecord(message?.usage);
1291
- output.responseId = typeof message?.id === "string" ? message.id : void 0;
1292
- output.responseModel = typeof message?.model === "string" ? message.model : void 0;
1293
- messageStartPromptUsage = applyAnthropicMessageStartUsage(output.usage, usage);
1294
1365
  calculateCost(costModel, output.usage);
1295
- eventSink.push({
1296
- type: "start",
1297
- partial: output
1298
- });
1299
- continue;
1300
- }
1301
- if (event.type === "message_stop") {
1302
- sawMessageStop = true;
1303
- continue;
1304
- }
1305
- if (event.type === "content_block_start") {
1306
- const contentBlock = asOptionalObjectRecord(event.content_block);
1307
- const index = typeof event.index === "number" ? event.index : -1;
1308
- if (options.anthropicServerCompaction === true && compactionCapture.begin(index, contentBlock, output.content.length)) continue;
1309
- const fallbackBoundary = refusalBuffer ? readAnthropicFallbackBoundary(contentBlock) : null;
1310
- if (fallbackBoundary) {
1311
- refusalBuffer?.discard();
1312
- sealedToolCalls.length = 0;
1313
- blockIndexes.clear();
1314
- pendingThinkingSignatures.clear();
1315
- applyAnthropicFallbackBoundary({
1316
- output,
1317
- boundary: fallbackBoundary,
1318
- provider: model.provider
1366
+ };
1367
+ let messageStartPromptUsage;
1368
+ let inputTransformations;
1369
+ try {
1370
+ const blocks = output.content;
1371
+ const blockIndexes = /* @__PURE__ */ new Map();
1372
+ const toolArgumentPreviewSchedules = /* @__PURE__ */ new WeakMap();
1373
+ const seededToolArguments = /* @__PURE__ */ new WeakMap();
1374
+ const sealedToolCalls = [];
1375
+ const compactionCapture = createCompactionCapture(output, model, reducerOptions);
1376
+ const pendingThinkingSignatures = /* @__PURE__ */ new Map();
1377
+ const allowReasoningContentReplay = managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native";
1378
+ const reasoningContentBlocks = {
1379
+ thinking: /* @__PURE__ */ new Map(),
1380
+ text: /* @__PURE__ */ new Map()
1381
+ };
1382
+ let sawMessageStart = false;
1383
+ let sawMessageStop = false;
1384
+ let sawStopReason = false;
1385
+ let sawFallbackBoundary = false;
1386
+ let terminalFallbackModel;
1387
+ const emitContentEnd = (block, contentIndex) => {
1388
+ eventSink.push({
1389
+ type: `${block.type}_end`,
1390
+ contentIndex,
1391
+ content: block.type === "thinking" ? block.thinking : block.text,
1392
+ partial: output
1319
1393
  });
1320
- costModel = {
1321
- ...model,
1322
- cost: resolveAnthropicFallbackServingModelCost({
1323
- requestedModelId: model.id,
1324
- servingModelId: fallbackBoundary.toModel,
1325
- requestedCost: model.cost
1326
- })
1327
- };
1328
- calculateCost(costModel, output.usage);
1394
+ };
1395
+ const emitContentStart = (kind, contentIndex, delta = "") => {
1329
1396
  eventSink.push({
1330
- type: "start",
1397
+ type: `${kind}_start`,
1398
+ contentIndex,
1331
1399
  partial: output
1332
1400
  });
1333
- for (const [i, block] of blocks.entries()) {
1334
- if (block.type !== "text") continue;
1335
- delete block.index;
1336
- emitContentStart("text", i, block.text);
1337
- emitContentEnd(block, i);
1338
- }
1339
- continue;
1340
- }
1341
- pendingThinkingSignatures.delete(index);
1342
- if (contentBlock?.type === "text" || contentBlock?.type === "thinking" || contentBlock?.type === "redacted_thinking") {
1343
- const block = contentBlock.type === "text" ? {
1344
- type: "text",
1345
- text: typeof contentBlock.text === "string" ? sanitizeTransportPayloadText(contentBlock.text) : "",
1346
- index
1347
- } : contentBlock.type === "thinking" ? {
1348
- type: "thinking",
1349
- thinking: typeof contentBlock.thinking === "string" ? contentBlock.thinking : "",
1350
- thinkingSignature: typeof contentBlock.signature === "string" ? contentBlock.signature : "",
1351
- index
1352
- } : {
1353
- type: "thinking",
1354
- thinking: "[Reasoning redacted]",
1355
- thinkingSignature: typeof contentBlock.data === "string" ? contentBlock.data : "",
1356
- redacted: true,
1357
- index
1358
- };
1359
- const delta = block.type === "text" ? block.text : block.redacted ? "" : block.thinking;
1360
- output.content.push(block);
1361
- const contentIndex = output.content.length - 1;
1362
- blockIndexes.set(index, contentIndex);
1363
- emitContentStart(block.type, contentIndex, delta);
1364
- continue;
1365
- }
1366
- if (contentBlock?.type === "tool_use") {
1367
- const block = {
1368
- type: "toolCall",
1369
- id: typeof contentBlock.id === "string" ? contentBlock.id : "",
1370
- name: typeof contentBlock.name === "string" ? isOAuthToken ? resolveOriginalAnthropicToolName(contentBlock.name, toolProjection) : contentBlock.name : "",
1371
- arguments: asRecord(contentBlock.input),
1372
- partialJson: "",
1373
- index
1374
- };
1375
- output.content.push(block);
1376
- blockIndexes.set(index, output.content.length - 1);
1377
- seededToolArguments.set(block, managed ? block.arguments : contentBlock.input ?? {});
1378
- toolArgumentPreviewSchedules.set(block, createToolArgumentPreviewSchedule());
1401
+ if (delta.length > 0) eventSink.push({
1402
+ type: `${kind}_delta`,
1403
+ contentIndex,
1404
+ delta,
1405
+ partial: output
1406
+ });
1407
+ };
1408
+ const appendContentDelta = (block, contentIndex, delta) => {
1409
+ if (block.type === "thinking") appendAssistantThinking(block, delta);
1410
+ else block.text += delta;
1379
1411
  eventSink.push({
1380
- type: "toolcall_start",
1381
- contentIndex: output.content.length - 1,
1412
+ type: `${block.type}_delta`,
1413
+ contentIndex,
1414
+ delta,
1382
1415
  partial: output
1383
1416
  });
1384
- }
1385
- continue;
1386
- }
1387
- if (event.type === "content_block_delta") {
1388
- const delta = asOptionalObjectRecord(event.delta);
1389
- const eventIndex = typeof event.index === "number" ? event.index : void 0;
1390
- if (eventIndex !== void 0 && compactionCapture.delta(eventIndex, delta)) continue;
1391
- let index = eventIndex === void 0 ? void 0 : blockIndexes.get(eventIndex);
1392
- let block = index === void 0 ? void 0 : blocks[index];
1393
- if (allowReasoningContentReplay) {
1394
- const appendedThinking = appendReasoningContentDelta("thinking", event.index, delta?.reasoning_content);
1395
- const hasNativeAnthropicDelta = delta?.type === "text_delta" && typeof delta.text === "string" || delta?.type === "thinking_delta" && typeof delta.thinking === "string" || delta?.type === "input_json_delta" && typeof delta.partial_json === "string" || delta?.type === "signature_delta" && typeof delta.signature === "string";
1396
- let appendedContent = false;
1397
- if (!hasNativeAnthropicDelta && typeof delta?.content === "string" && delta.content.length > 0) {
1398
- const text = sanitizeTransportPayloadText(delta.content);
1399
- if (text.length > 0) {
1400
- if (block?.type === "text" && index !== void 0) {
1401
- appendContentDelta(block, index, text);
1402
- appendedContent = true;
1403
- } else appendedContent = appendReasoningContentDelta("text", event.index, text);
1417
+ };
1418
+ const eventIndexKey = (eventIndex) => typeof eventIndex === "number" ? eventIndex : -1;
1419
+ const appendReasoningContentDelta = (kind, eventIndex, rawText) => {
1420
+ if (typeof rawText !== "string") return false;
1421
+ const text = sanitizeTransportPayloadText(rawText);
1422
+ if (text.length === 0) return false;
1423
+ const indexes = reasoningContentBlocks[kind];
1424
+ const key = eventIndexKey(eventIndex);
1425
+ let contentIndex = indexes.get(key);
1426
+ let block = contentIndex === void 0 ? void 0 : blocks[contentIndex];
1427
+ if (contentIndex === void 0 || !block || block.type !== kind) {
1428
+ block = kind === "thinking" ? {
1429
+ type: "thinking",
1430
+ thinking: "",
1431
+ thinkingSignature: "reasoning_content"
1432
+ } : {
1433
+ type: "text",
1434
+ text: ""
1435
+ };
1436
+ output.content.push(block);
1437
+ contentIndex = output.content.length - 1;
1438
+ indexes.set(key, contentIndex);
1439
+ emitContentStart(kind, contentIndex);
1440
+ }
1441
+ if (block.type === "thinking") block.thinkingSignature = "reasoning_content";
1442
+ appendContentDelta(block, contentIndex, text);
1443
+ return true;
1444
+ };
1445
+ const finishReasoningContentSidecars = (eventIndex) => {
1446
+ const key = eventIndexKey(eventIndex);
1447
+ for (const kind of ["thinking", "text"]) {
1448
+ const indexes = reasoningContentBlocks[kind];
1449
+ const contentIndex = indexes.get(key);
1450
+ if (contentIndex === void 0) continue;
1451
+ indexes.delete(key);
1452
+ const block = output.content[contentIndex];
1453
+ if (block?.type === kind) emitContentEnd(block, contentIndex);
1454
+ }
1455
+ };
1456
+ for await (const rawEvent of iterateModelStream(events, reducerOptions.signal)) {
1457
+ const event = asRecord(rawEvent);
1458
+ inputTransformations = readAnthropicInputTransformations(event) ?? inputTransformations;
1459
+ if (managed) notifyLlmRequestActivity(reducerOptions.signal);
1460
+ if (event.type === "error") {
1461
+ const error = asOptionalObjectRecord(event.error);
1462
+ throw Object.assign(new Error(readStringField(error, "message") || "Anthropic Messages stream failed"), { error });
1463
+ }
1464
+ if (event.type === "message_start") {
1465
+ sawMessageStart = true;
1466
+ const message = asOptionalObjectRecord(event.message);
1467
+ const usage = asRecord(message?.usage);
1468
+ output.responseId = typeof message?.id === "string" ? message.id : void 0;
1469
+ output.responseModel = typeof message?.model === "string" ? message.model : void 0;
1470
+ messageStartPromptUsage = applyAnthropicMessageStartUsage(output.usage, usage);
1471
+ calculateCost(costModel, output.usage);
1472
+ eventSink.push({
1473
+ type: "start",
1474
+ partial: output
1475
+ });
1476
+ continue;
1477
+ }
1478
+ if (event.type === "message_stop") {
1479
+ sawMessageStop = true;
1480
+ continue;
1481
+ }
1482
+ if (event.type === "content_block_start") {
1483
+ const contentBlock = asOptionalObjectRecord(event.content_block);
1484
+ const index = typeof event.index === "number" ? event.index : -1;
1485
+ if (reducerOptions.anthropicServerCompaction === true && compactionCapture.begin(index, contentBlock, output.content.length)) continue;
1486
+ const fallbackBoundary = refusalBuffer ? readAnthropicFallbackBoundary(contentBlock) : null;
1487
+ if (fallbackBoundary) {
1488
+ sawFallbackBoundary = true;
1489
+ refusalBuffer?.discard();
1490
+ sealedToolCalls.length = 0;
1491
+ blockIndexes.clear();
1492
+ pendingThinkingSignatures.clear();
1493
+ applyAnthropicFallbackBoundary({
1494
+ output,
1495
+ boundary: fallbackBoundary,
1496
+ provider: model.provider
1497
+ });
1498
+ applyServingModelCost(fallbackBoundary.toModel);
1499
+ eventSink.push({
1500
+ type: "start",
1501
+ partial: output
1502
+ });
1503
+ for (const [i, block] of blocks.entries()) {
1504
+ if (block.type !== "text") continue;
1505
+ emitContentStart("text", i, block.text);
1506
+ emitContentEnd(block, i);
1507
+ }
1508
+ continue;
1509
+ }
1510
+ pendingThinkingSignatures.delete(index);
1511
+ if (contentBlock?.type === "text" || contentBlock?.type === "thinking" || contentBlock?.type === "redacted_thinking") {
1512
+ const block = contentBlock.type === "text" ? {
1513
+ type: "text",
1514
+ text: typeof contentBlock.text === "string" ? sanitizeTransportPayloadText(contentBlock.text) : ""
1515
+ } : contentBlock.type === "thinking" ? {
1516
+ type: "thinking",
1517
+ thinking: typeof contentBlock.thinking === "string" ? contentBlock.thinking : "",
1518
+ thinkingSignature: typeof contentBlock.signature === "string" ? contentBlock.signature : ""
1519
+ } : {
1520
+ type: "thinking",
1521
+ thinking: "[Reasoning redacted]",
1522
+ thinkingSignature: typeof contentBlock.data === "string" ? contentBlock.data : "",
1523
+ redacted: true
1524
+ };
1525
+ const delta = block.type === "text" ? block.text : block.redacted ? "" : block.thinking;
1526
+ output.content.push(block);
1527
+ const contentIndex = output.content.length - 1;
1528
+ blockIndexes.set(index, contentIndex);
1529
+ emitContentStart(block.type, contentIndex, delta);
1530
+ continue;
1531
+ }
1532
+ if (contentBlock?.type === "tool_use") {
1533
+ const block = {
1534
+ type: "toolCall",
1535
+ id: typeof contentBlock.id === "string" ? contentBlock.id : "",
1536
+ name: typeof contentBlock.name === "string" ? isOAuthToken ? resolveOriginalAnthropicToolName(contentBlock.name, toolProjection) : contentBlock.name : "",
1537
+ arguments: asRecord(contentBlock.input),
1538
+ partialJson: ""
1539
+ };
1540
+ output.content.push(block);
1541
+ blockIndexes.set(index, output.content.length - 1);
1542
+ seededToolArguments.set(block, managed ? block.arguments : contentBlock.input ?? {});
1543
+ toolArgumentPreviewSchedules.set(block, createToolArgumentPreviewSchedule());
1544
+ eventSink.push({
1545
+ type: "toolcall_start",
1546
+ contentIndex: output.content.length - 1,
1547
+ partial: output
1548
+ });
1404
1549
  }
1550
+ continue;
1551
+ }
1552
+ if (event.type === "content_block_delta") {
1553
+ const delta = asOptionalObjectRecord(event.delta);
1554
+ const eventIndex = typeof event.index === "number" ? event.index : void 0;
1555
+ if (eventIndex !== void 0 && compactionCapture.delta(eventIndex, delta)) continue;
1556
+ let index = eventIndex === void 0 ? void 0 : blockIndexes.get(eventIndex);
1557
+ let block = index === void 0 ? void 0 : blocks[index];
1558
+ if (allowReasoningContentReplay) {
1559
+ const appendedThinking = appendReasoningContentDelta("thinking", event.index, delta?.reasoning_content);
1560
+ const hasNativeAnthropicDelta = delta?.type === "text_delta" && typeof delta.text === "string" || delta?.type === "thinking_delta" && typeof delta.thinking === "string" || delta?.type === "input_json_delta" && typeof delta.partial_json === "string" || delta?.type === "signature_delta" && typeof delta.signature === "string";
1561
+ let appendedContent = false;
1562
+ if (!hasNativeAnthropicDelta && typeof delta?.content === "string" && delta.content.length > 0) {
1563
+ const text = sanitizeTransportPayloadText(delta.content);
1564
+ if (text.length > 0) {
1565
+ if (block?.type === "text" && index !== void 0) {
1566
+ appendContentDelta(block, index, text);
1567
+ appendedContent = true;
1568
+ } else appendedContent = appendReasoningContentDelta("text", event.index, text);
1569
+ }
1570
+ }
1571
+ if ((appendedThinking || appendedContent) && !hasNativeAnthropicDelta) continue;
1572
+ }
1573
+ if (managed && !block && delta?.type === "text_delta" && typeof delta.text === "string") {
1574
+ block = {
1575
+ type: "text",
1576
+ text: ""
1577
+ };
1578
+ output.content.push(block);
1579
+ index = output.content.length - 1;
1580
+ if (typeof event.index === "number") blockIndexes.set(event.index, index);
1581
+ emitContentStart("text", index);
1582
+ }
1583
+ if (index === void 0) continue;
1584
+ if (block?.type === "text" && delta?.type === "text_delta" && typeof delta.text === "string") {
1585
+ appendContentDelta(block, index, delta.text);
1586
+ continue;
1587
+ }
1588
+ if (block?.type === "thinking" && delta?.type === "thinking_delta" && typeof delta.thinking === "string") {
1589
+ appendContentDelta(block, index, delta.thinking);
1590
+ continue;
1591
+ }
1592
+ if (block?.type === "toolCall" && delta?.type === "input_json_delta" && typeof delta.partial_json === "string") {
1593
+ const partialJson = `${block.partialJson ?? ""}${delta.partial_json}`;
1594
+ block.partialJson = partialJson;
1595
+ if (toolArgumentPreviewSchedules.get(block)?.(partialJson.length)) block.arguments = managed ? coerceTransportToolCallArguments(parseJsonObjectPreservingUnsafeIntegers(partialJson) ?? parseStreamingJson(partialJson)) : parseStreamingJson(partialJson);
1596
+ eventSink.push({
1597
+ type: "toolcall_delta",
1598
+ contentIndex: index,
1599
+ delta: delta.partial_json,
1600
+ partial: output
1601
+ });
1602
+ continue;
1603
+ }
1604
+ if (block?.type === "thinking" && delta?.type === "signature_delta" && typeof delta.signature === "string") {
1605
+ const signatureIndex = eventIndexKey(event.index);
1606
+ const pendingSignature = pendingThinkingSignatures.get(signatureIndex);
1607
+ if (pendingSignature === void 0) {
1608
+ block.thinkingSignature = "";
1609
+ pendingThinkingSignatures.set(signatureIndex, delta.signature);
1610
+ } else pendingThinkingSignatures.set(signatureIndex, pendingSignature + delta.signature);
1611
+ }
1612
+ continue;
1613
+ }
1614
+ if (event.type === "content_block_stop") {
1615
+ const eventIndex = typeof event.index === "number" ? event.index : void 0;
1616
+ if (eventIndex !== void 0 && compactionCapture.complete(eventIndex)) continue;
1617
+ const pendingSignature = eventIndex === void 0 ? void 0 : pendingThinkingSignatures.get(eventIndex);
1618
+ if (eventIndex !== void 0) pendingThinkingSignatures.delete(eventIndex);
1619
+ const index = eventIndex === void 0 ? void 0 : blockIndexes.get(eventIndex);
1620
+ const block = index === void 0 ? void 0 : blocks[index];
1621
+ if (eventIndex === void 0 || index === void 0 || !block) {
1622
+ finishReasoningContentSidecars(event.index);
1623
+ continue;
1624
+ }
1625
+ blockIndexes.delete(eventIndex);
1626
+ if (block.type === "thinking" && pendingSignature !== void 0) block.thinkingSignature = pendingSignature;
1627
+ if (block.type === "toolCall") sealedToolCalls.push({
1628
+ block,
1629
+ contentIndex: index
1630
+ });
1631
+ else emitContentEnd(block, index);
1632
+ finishReasoningContentSidecars(event.index);
1633
+ continue;
1634
+ }
1635
+ if (event.type === "message_delta") {
1636
+ logAnthropicContextEdits(event);
1637
+ const delta = asOptionalObjectRecord(event.delta);
1638
+ const usage = asOptionalObjectRecord(event.usage);
1639
+ if (typeof delta?.stop_reason === "string" && delta.stop_reason) {
1640
+ sawStopReason = true;
1641
+ const iteration = Array.isArray(usage?.iterations) ? asOptionalObjectRecord(usage.iterations.at(-1)) : void 0;
1642
+ terminalFallbackModel = iteration?.type === "fallback_message" && typeof iteration.model === "string" && iteration.model.trim() ? iteration.model : void 0;
1643
+ if (delta.stop_reason === "refusal") applyAnthropicRefusal(output, delta.stop_details, model.provider);
1644
+ else output.stopReason = mapAnthropicStopReason(delta.stop_reason);
1645
+ }
1646
+ applyAnthropicMessageDeltaUsage(output.usage, usage, messageStartPromptUsage);
1647
+ if (sawStopReason && messageStartPromptUsage && typeof usage?.output_tokens === "number") output.usage.usageReport = { state: "available" };
1648
+ calculateCost(costModel, output.usage);
1405
1649
  }
1406
- if ((appendedThinking || appendedContent) && !hasNativeAnthropicDelta) continue;
1407
- }
1408
- if (managed && !block && delta?.type === "text_delta" && typeof delta.text === "string") {
1409
- block = {
1410
- type: "text",
1411
- text: "",
1412
- index: typeof event.index === "number" ? event.index : blocks.length
1413
- };
1414
- output.content.push(block);
1415
- index = output.content.length - 1;
1416
- if (typeof event.index === "number") blockIndexes.set(event.index, index);
1417
- emitContentStart("text", index);
1418
- }
1419
- if (index === void 0) continue;
1420
- if (block?.type === "text" && delta?.type === "text_delta" && typeof delta.text === "string") {
1421
- appendContentDelta(block, index, delta.text);
1422
- continue;
1423
1650
  }
1424
- if (block?.type === "thinking" && delta?.type === "thinking_delta" && typeof delta.thinking === "string") {
1425
- appendContentDelta(block, index, delta.thinking);
1426
- continue;
1651
+ if ((isDirectAnthropicModel(model) || !managed && refusalBuffer) && !sawMessageStop) throw new Error("Anthropic stream ended before message_stop");
1652
+ if (reducerOptions.signal?.aborted) throw transportAbortError(reducerOptions.signal);
1653
+ if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
1654
+ if ([...blockIndexes.values()].some((index) => blocks[index]?.type === "toolCall")) throw new Error("Provider completed stream with an incomplete tool call");
1655
+ if ((sawMessageStart || blocks.length > 0) && !sawMessageStop && !sawStopReason) throw new Error("Anthropic stream ended before a terminal event");
1656
+ finalizeTerminalToolCallArguments(sealedToolCalls.map(({ block }) => block), (block) => block.partialJson && block.partialJson.length > 0 ? block.partialJson : seededToolArguments.get(block), void 0, { repairStringLiterals: true });
1657
+ if (refusalBuffer && terminalFallbackModel && !sawFallbackBoundary) {
1658
+ output.responseModel = terminalFallbackModel;
1659
+ applyServingModelCost(terminalFallbackModel);
1660
+ output.diagnostics = [...output.diagnostics ?? [], {
1661
+ type: "provider_fallback",
1662
+ timestamp: Date.now(),
1663
+ details: {
1664
+ provider: model.provider,
1665
+ fromModel: model.id,
1666
+ toModel: terminalFallbackModel
1667
+ }
1668
+ }];
1427
1669
  }
1428
- if (block?.type === "toolCall" && delta?.type === "input_json_delta" && typeof delta.partial_json === "string") {
1429
- const partialJson = `${block.partialJson ?? ""}${delta.partial_json}`;
1430
- block.partialJson = partialJson;
1431
- if (toolArgumentPreviewSchedules.get(block)?.(partialJson.length)) block.arguments = managed ? coerceTransportToolCallArguments(parseJsonObjectPreservingUnsafeIntegers(partialJson) ?? parseStreamingJson(partialJson)) : parseStreamingJson(partialJson);
1670
+ for (const sealed of sealedToolCalls) {
1671
+ delete sealed.block.partialJson;
1432
1672
  eventSink.push({
1433
- type: "toolcall_delta",
1434
- contentIndex: index,
1435
- delta: delta.partial_json,
1673
+ type: "toolcall_end",
1674
+ contentIndex: sealed.contentIndex,
1675
+ toolCall: sealed.block,
1436
1676
  partial: output
1437
1677
  });
1438
- continue;
1439
1678
  }
1440
- if (block?.type === "thinking" && delta?.type === "signature_delta" && typeof delta.signature === "string") {
1441
- const signatureIndex = eventIndexKey(event.index);
1442
- const pendingSignature = pendingThinkingSignatures.get(signatureIndex);
1443
- if (pendingSignature === void 0) {
1444
- block.thinkingSignature = "";
1445
- pendingThinkingSignatures.set(signatureIndex, delta.signature);
1446
- } else pendingThinkingSignatures.set(signatureIndex, pendingSignature + delta.signature);
1447
- }
1448
- continue;
1679
+ refusalBuffer?.flush();
1680
+ } finally {
1681
+ logAnthropicThinkingDrops(inputTransformations);
1449
1682
  }
1450
- if (event.type === "content_block_stop") {
1451
- const eventIndex = typeof event.index === "number" ? event.index : void 0;
1452
- if (eventIndex !== void 0 && compactionCapture.complete(eventIndex)) continue;
1453
- const pendingSignature = eventIndex === void 0 ? void 0 : pendingThinkingSignatures.get(eventIndex);
1454
- if (eventIndex !== void 0) pendingThinkingSignatures.delete(eventIndex);
1455
- const index = eventIndex === void 0 ? void 0 : blockIndexes.get(eventIndex);
1456
- const block = index === void 0 ? void 0 : blocks[index];
1457
- if (eventIndex === void 0 || index === void 0 || !block) {
1458
- finishReasoningContentSidecars(event.index);
1459
- continue;
1460
- }
1461
- blockIndexes.delete(eventIndex);
1462
- delete block.index;
1463
- if (block.type === "thinking" && pendingSignature !== void 0) block.thinkingSignature = pendingSignature;
1464
- if (block.type === "toolCall") sealedToolCalls.push({
1465
- block,
1466
- contentIndex: index
1467
- });
1468
- else emitContentEnd(block, index);
1469
- finishReasoningContentSidecars(event.index);
1470
- continue;
1471
- }
1472
- if (event.type === "message_delta") {
1473
- logAnthropicContextEdits(event);
1474
- const delta = asOptionalObjectRecord(event.delta);
1475
- const usage = asOptionalObjectRecord(event.usage);
1476
- if (typeof delta?.stop_reason === "string" && delta.stop_reason) {
1477
- sawStopReason = true;
1478
- if (delta.stop_reason === "refusal") applyAnthropicRefusal(output, delta.stop_details, model.provider);
1479
- else output.stopReason = mapAnthropicStopReason(delta.stop_reason);
1480
- }
1481
- applyAnthropicMessageDeltaUsage(output.usage, usage, messageStartPromptUsage);
1482
- if (sawStopReason && messageStartPromptUsage && typeof usage?.output_tokens === "number") output.usage.usageReport = { state: "available" };
1483
- calculateCost(costModel, output.usage);
1683
+ })();
1684
+ finalizeTransportStream({
1685
+ stream,
1686
+ output
1687
+ });
1688
+ } catch (error) {
1689
+ failTransportStream({
1690
+ stream,
1691
+ output,
1692
+ signal: options?.signal,
1693
+ error,
1694
+ cleanup: () => {
1695
+ refusalBuffer?.discard();
1696
+ output.content = refusalBuffer ? [] : output.content.filter((block) => block.type !== "toolCall");
1697
+ if (replayedCompaction && isAnthropicReplayRejection(profile === "provider" ? error : output)) suppressAnthropicCompaction(output, model, options, replayedCompaction);
1484
1698
  }
1485
- }
1486
- if ((isDirectAnthropicModel(model) || !managed && refusalBuffer) && !sawMessageStop) throw new Error("Anthropic stream ended before message_stop");
1487
- if (options.signal?.aborted) throw transportAbortError(options.signal);
1488
- if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
1489
- if ([...blockIndexes.values()].some((index) => blocks[index]?.type === "toolCall")) throw new Error("Provider completed stream with an incomplete tool call");
1490
- if ((sawMessageStart || blocks.length > 0) && !sawMessageStop && !sawStopReason) throw new Error("Anthropic stream ended before a terminal event");
1491
- finalizeTerminalToolCallArguments(sealedToolCalls.map(({ block }) => block), (block) => block.partialJson && block.partialJson.length > 0 ? block.partialJson : seededToolArguments.get(block), void 0, { repairStringLiterals: true });
1492
- for (const sealed of sealedToolCalls) {
1493
- delete sealed.block.partialJson;
1494
- eventSink.push({
1495
- type: "toolcall_end",
1496
- contentIndex: sealed.contentIndex,
1497
- toolCall: sealed.block,
1498
- partial: output
1499
- });
1500
- }
1501
- refusalBuffer?.flush();
1502
- } finally {
1503
- logAnthropicThinkingDrops(inputTransformations);
1699
+ });
1504
1700
  }
1505
1701
  }
1506
1702
  //#endregion
1507
- export { resolveAnthropicCacheOptions as A, readAnthropicFallbackBoundary as B, applyAnthropicEphemeralCacheControlMarkers as C, isAnthropicServerToolClearingEnabled as D, buildAnthropicSystemBlocks as E, supportsAnthropicServerSideFallback as F, isAnthropicOAuthApiKey as H, ANTHROPIC_SERVER_SIDE_FALLBACKS as I, ANTHROPIC_SERVER_SIDE_FALLBACK_BETA as L, resolveAnthropicPayloadPolicy as M, resolveAnthropicRequestBetaHeader as N, isDirectAnthropicModel as O, resolveAnthropicServerCompactionPlan as P, CLAUDE_OPUS_FALLBACK_MODEL_COST as R, applyAnthropicContextManagementToRequest as S, applyAnthropicRequestCacheControl as T, omitFoundryBearerCredentialHeaders as U, resolveAnthropicFallbackServingModelCost as V, usesFoundryBearerAuth as W, logAnthropicThinkingDrops as _, readAnthropicPromptUsageSnapshot as a, resolveNewestAnthropicCompaction as b, applyAnthropicRefusal as c, applyAnthropicThinkingOptions as d, resolveAnthropicTransportOptions as f, findActiveAnthropicToolTurnAssistantIndex as g, applyAnthropicThinkingBindingControls as h, readAnthropicCacheWriteUsage as i, resolveAnthropicEphemeralCacheControl as j, logAnthropicContextEdits as k, buildAnthropicRequest as l, ANTHROPIC_OMITTED_REASONING_TEXT as m, applyAnthropicMessageDeltaUsage as n, readAnthropicUsageTokenCount as o, resolveCompletionTokenReservation as p, applyAnthropicMessageStartUsage as r, readLastAnthropicIterationUsage as s, consumeAnthropicStream as t, prepareAnthropicRequest as u, readAnthropicInputTransformations as v, applyAnthropicPayloadPolicyToParams as w, suppressAnthropicCompaction as x, isAnthropicReplayRejection as y, applyAnthropicFallbackBoundary as z };
1703
+ export { resolveAnthropicServerCompactionPlan as A, usesFoundryBearerAuth as B, isAnthropicServerToolClearingEnabled as C, resolveAnthropicEphemeralCacheControl as D, resolveAnthropicCacheOptions as E, applyAnthropicFallbackBoundary as F, readAnthropicFallbackBoundary as I, resolveAnthropicFallbackServingModelCost as L, ANTHROPIC_SERVER_SIDE_FALLBACKS as M, ANTHROPIC_SERVER_SIDE_FALLBACK_BETA as N, resolveAnthropicPayloadPolicy as O, CLAUDE_OPUS_FALLBACK_MODEL_COST as P, isAnthropicOAuthApiKey as R, buildAnthropicSystemBlocks as S, logAnthropicContextEdits as T, applyAnthropicRefusal as _, resolveNewestAnthropicCompaction as a, applyAnthropicPayloadPolicyToParams as b, readAnthropicCacheWriteUsage as c, readLastAnthropicIterationUsage as d, ANTHROPIC_OMITTED_REASONING_TEXT as f, readAnthropicInputTransformations as g, logAnthropicThinkingDrops as h, resolveCompletionTokenReservation as i, supportsAnthropicServerSideFallback as j, resolveAnthropicRequestBetaHeader as k, readAnthropicPromptUsageSnapshot as l, findActiveAnthropicToolTurnAssistantIndex as m, applyAnthropicThinkingOptions as n, applyAnthropicMessageDeltaUsage as o, applyAnthropicThinkingBindingControls as p, resolveAnthropicTransportOptions as r, applyAnthropicMessageStartUsage as s, runAnthropicStreamLifecycle as t, readAnthropicUsageTokenCount as u, applyAnthropicContextManagementToRequest as v, isDirectAnthropicModel as w, applyAnthropicRequestCacheControl as x, applyAnthropicEphemeralCacheControlMarkers as y, omitFoundryBearerCredentialHeaders as z };