@openclaw/ai 2026.9.1 → 2026.9.3

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 (111) hide show
  1. package/README.md +3 -2
  2. package/dist/anthropic-CZy5U0NY.mjs +376 -0
  3. package/dist/anthropic-payload-policy-wuRCb6MH.d.mts +85 -0
  4. package/dist/anthropic-stream-reducer-B_yo_7pf.mjs +1669 -0
  5. package/dist/{api-registry-Cs6HGNqY.d.mts → api-registry-CB1-1oQ2.d.mts} +2 -2
  6. package/dist/assistant-output-iqnlJCV2.mjs +16 -0
  7. package/dist/assistant-text-phase-C20rxWwP.mjs +55 -0
  8. package/dist/{azure-openai-responses-CN4Fy5zV.mjs → azure-openai-responses-Crpa40QR.mjs} +5 -5
  9. package/dist/{base64-CEFBpSkN.mjs → base64-D-su8YVo.mjs} +1 -27
  10. package/dist/{diagnostics-KhXK-QJI.mjs → diagnostics-dV98PqIy.mjs} +96 -21
  11. package/dist/diagnostics.d.mts +3 -1
  12. package/dist/diagnostics.mjs +3 -3
  13. package/dist/{event-stream-vK_7r3bj.d.mts → event-stream-C1Z2piyk.d.mts} +11 -3
  14. package/dist/{event-stream-uSMZJ3FA.mjs → event-stream-D8PARQfL.mjs} +48 -10
  15. package/dist/event-stream-I_GlBsuZ.d.mts +1 -0
  16. package/dist/event-stream.d.mts +2 -2
  17. package/dist/event-stream.mjs +1 -1
  18. package/dist/{github-copilot-headers-NCJtz9i0.mjs → github-copilot-headers-B37TB3rB.mjs} +3 -10
  19. package/dist/github-copilot-request-facts-BTEBMeOv.mjs +16 -0
  20. package/dist/{google-CC-nrwXg.mjs → google-BDPriaVe.mjs} +10 -10
  21. package/dist/google-messages-CVn9eFpF.mjs +449 -0
  22. package/dist/google-shared-BedY23XS.mjs +185 -0
  23. package/dist/{google-vertex-DCr0pyzQ.mjs → google-vertex-DMz8XQCn.mjs} +7 -6
  24. package/dist/{host-BIaiBURL.mjs → host-CWuF-sS3.mjs} +84 -34
  25. package/dist/{host-BztR4tQj.d.mts → host-DK3wmS3e.d.mts} +3 -3
  26. package/dist/host-policy-CAopLRKA.mjs +37 -0
  27. package/dist/{index-AfaxKT8w.d.mts → index-CQ6LTHw8.d.mts} +11 -5
  28. package/dist/index.d.mts +7 -7
  29. package/dist/index.mjs +5 -5
  30. package/dist/internal/anthropic.d.mts +14 -11
  31. package/dist/internal/anthropic.mjs +5 -5
  32. package/dist/internal/google-model-family.d.mts +5 -0
  33. package/dist/internal/google-model-family.mjs +15 -0
  34. package/dist/internal/openai-responses-payload-policy.d.mts +1 -1
  35. package/dist/internal/openai-responses-payload-policy.mjs +1 -1
  36. package/dist/internal/openai.d.mts +8 -103
  37. package/dist/internal/openai.mjs +10 -10
  38. package/dist/internal/retry-after.d.mts +2 -4
  39. package/dist/internal/retry-after.mjs +57 -8
  40. package/dist/internal/runtime.d.mts +7 -6
  41. package/dist/internal/runtime.mjs +8 -7
  42. package/dist/internal/shared.d.mts +14 -3
  43. package/dist/internal/shared.mjs +6 -4
  44. package/dist/internal/tool-schema.d.mts +63 -0
  45. package/dist/internal/tool-schema.mjs +3 -0
  46. package/dist/{json-parse-BuAJEbdW.mjs → json-parse-Dw_hnxsA.mjs} +1 -1
  47. package/dist/{mistral-B7etBd_H.mjs → mistral--m-Jm6VZ.mjs} +16 -38
  48. package/dist/model-transport-url-DKocrEsb.d.mts +28 -0
  49. package/dist/{openai-chatgpt-responses-BAJ4gq3i.mjs → openai-chatgpt-responses-nDZccFW-.mjs} +62 -54
  50. package/dist/openai-completions-KuoZyx0d.mjs +187 -0
  51. package/dist/{openai-completions-compat-4IjSBpr6.d.mts → openai-completions-compat-CXn3T1we.d.mts} +26 -4
  52. package/dist/{openai-completions-stream-DZjwK8vp.mjs → openai-completions-stream-BQk3SkLD.mjs} +621 -451
  53. package/dist/openai-prompt-cache-BI0rkM-5.mjs +220 -0
  54. package/dist/openai-prompt-cache-rrutvqxq.d.mts +16 -0
  55. package/dist/openai-provider-client-ha_WxTyj.mjs +24 -0
  56. package/dist/openai-reasoning-effort-BK7FbcLT.mjs +167 -0
  57. package/dist/{openai-responses-BEUlxfDu.mjs → openai-responses-D99dOzKI.mjs} +14 -32
  58. package/dist/{openai-responses-compaction-window-DO7yV7az.mjs → openai-responses-compaction-window-D5jbzCi3.mjs} +7 -159
  59. package/dist/{openai-responses-contracts-bPzSN_Ba.d.mts → openai-responses-contracts-B55afwRo.d.mts} +12 -4
  60. package/dist/{openai-responses-prompt-observer-internal-C7x4IK7r.mjs → openai-responses-prompt-observer-internal-tApyTLVu.mjs} +3 -3
  61. package/dist/{openai-responses-shared-DiAdpNAM.mjs → openai-responses-shared-ZyQEzS5i.mjs} +217 -212
  62. package/dist/openai-tool-projection-793cE3QX.d.mts +37 -0
  63. package/dist/{openai-tool-schema-BMiHFH36.mjs → openai-tool-schema-CzjyYXun.mjs} +53 -583
  64. package/dist/openai-tool-schema-ynZBgqW-.d.mts +38 -0
  65. package/dist/openai-transport-params-DNasp2fU.mjs +674 -0
  66. package/dist/{provider-error-B6EGq6gg.mjs → provider-error-C6TbKiey.mjs} +29 -13
  67. package/dist/{provider-options-CxFPtvh7.d.mts → provider-options-BXr9Ec83.d.mts} +19 -42
  68. package/dist/provider-replay-context-BuSUaAk5.mjs +21 -0
  69. package/dist/{provider-transcript-transform-WvJmFUAf.mjs → provider-transcript-transform-pPmUIwKt.mjs} +1 -1
  70. package/dist/provider-types-CAV0Og3m.d.mts +29 -0
  71. package/dist/provider-types.d.mts +6 -31
  72. package/dist/providers.d.mts +2 -2
  73. package/dist/providers.mjs +11 -11
  74. package/dist/{reasoning-tag-text-partitioner-C-4uedDb.mjs → reasoning-tag-text-partitioner-BQBi4B9d.mjs} +90 -35
  75. package/dist/record-coerce-DwRYMj3t.mjs +32 -0
  76. package/dist/retry-after-CdCURCVg.d.mts +15 -0
  77. package/dist/{sanitize-unicode-S6binQG-.mjs → sanitize-unicode-Bb-v9meu.mjs} +1 -1
  78. package/dist/session-affinity-CCH7eYdB.mjs +20 -0
  79. package/dist/{simple-options-0PLDyJ-d.mjs → simple-options-tcKOqnpF.mjs} +3 -3
  80. package/dist/{src-C8U7lkoa.mjs → src-B2Q_6G8V.mjs} +10 -2
  81. package/dist/{stream-first-event-timeout-DcNjoFQE.mjs → stream-first-event-timeout-2hfrquuz.mjs} +1 -1
  82. package/dist/string-coerce-fsri9iCu.mjs +34 -0
  83. package/dist/{string-normalization--fwJ4S2q.mjs → string-normalization-CmLIasuf.mjs} +1 -1
  84. package/dist/{tool-schema-json-projection-BtZiml7r.mjs → tool-schema-json-projection-ClptDdAO.mjs} +2 -38
  85. package/dist/{transport-stream-shared-CytPVLIg.mjs → transport-stream-shared-Cu3ZPhNW.mjs} +5 -5
  86. package/dist/{transport-stream-shared-BrvFTkoO.d.mts → transport-stream-shared-DOxpGJ-H.d.mts} +4 -4
  87. package/dist/transport-utils-CCooe-cr.mjs +121 -0
  88. package/dist/transports.d.mts +114 -41
  89. package/dist/transports.mjs +796 -1596
  90. package/dist/types-BADKjDBI.d.mts +1 -0
  91. package/dist/{types-DbrhszyQ.d.mts → types-Dy1q0CSu.d.mts} +101 -64
  92. package/dist/types.d.mts +6 -6
  93. package/dist/types.mjs +4 -4
  94. package/dist/utf16-slice-CvGodqok.mjs +29 -0
  95. package/dist/{validation-CJZtym2g.mjs → validation-BDzVDnTs.mjs} +9 -1
  96. package/dist/{validation-BOwtcl9X.d.mts → validation-CaFUZN9B.d.mts} +1 -1
  97. package/dist/validation.d.mts +1 -1
  98. package/dist/validation.mjs +1 -1
  99. package/package.json +14 -4
  100. package/dist/anthropic-compaction-replay-OMJZ0uyo.mjs +0 -838
  101. package/dist/anthropic-hk7F7ptG.mjs +0 -883
  102. package/dist/anthropic-payload-policy-DBT1itQ-.d.mts +0 -51
  103. package/dist/event-stream-DeDhbCc5.d.mts +0 -1
  104. package/dist/google-shared-CjPY0hZM.mjs +0 -634
  105. package/dist/google-thinking-level-C-V3tecN.mjs +0 -9
  106. package/dist/openai-completions-D0QZ0AyB.mjs +0 -403
  107. package/dist/openai-prompt-cache-2uo_1OR1.d.mts +0 -7
  108. package/dist/openai-prompt-cache-mZTCdRPo.mjs +0 -12
  109. package/dist/transport-utils-CtuS1Upe.mjs +0 -138
  110. package/dist/types-B5EFUmXs.d.mts +0 -1
  111. package/dist/utf16-slice-qz3nsy87.mjs +0 -84
@@ -0,0 +1,1669 @@
1
+ import { _ as supportsClaudeAdaptiveThinking, b as supportsClaudeNativeXhighEffort, d as resolveClaudeModelIdentity, m as resolveClaudeOpus5ModelIdentity, u as resolveClaudeFable5ModelIdentity } from "./src-B2Q_6G8V.mjs";
2
+ import { r as appendAssistantThinking } from "./event-stream-D8PARQfL.mjs";
3
+ import { i as normalizeOptionalLowercaseString, r as normalizeNullableString } from "./string-coerce-fsri9iCu.mjs";
4
+ import { r as calculateCost, t as sanitizeSurrogates } from "./sanitize-unicode-Bb-v9meu.mjs";
5
+ import { a as describeToolResultMediaPlaceholder, c as extractToolResultText, d as isImageWithMediaPayload, f as ANTHROPIC_CLAUDE_CODE_BILLING_SYSTEM_BLOCK, g as mapAnthropicStopReason, n as getAiTransportHost, s as extractToolResultBlockText, v as requiresClaudeAdaptiveThinking } from "./host-CWuF-sS3.mjs";
6
+ import { a as asRecord, o as isRecord, r as asOptionalObjectRecord, s as readStringField } from "./record-coerce-DwRYMj3t.mjs";
7
+ import { i as asNonNegativeFiniteNumber, n as estimateBase64DecodedBytes } from "./base64-D-su8YVo.mjs";
8
+ import { a as parsePositiveInteger } from "./transport-utils-CCooe-cr.mjs";
9
+ import { a as resolveProviderRequestCapabilities, i as resolveProviderEndpoint } from "./host-policy-CAopLRKA.mjs";
10
+ import { t as resolveCacheRetention } from "./cache-retention-0x979a5V.mjs";
11
+ import { d as stripSystemPromptCacheBoundary, m as sortPromptCacheToolsByName, u as splitSystemPromptCacheBoundary } from "./simple-options-tcKOqnpF.mjs";
12
+ import { t as projectRuntimeToolInputSchema } from "./tool-schema-json-projection-ClptDdAO.mjs";
13
+ import { _ as transportAbortError, b as parseJsonObjectPreservingUnsafeIntegers, g as sanitizeTransportPayloadText, h as sanitizeNonEmptyTransportPayloadText, n as coerceTransportToolCallArguments, s as finalizeTerminalToolCallArguments } from "./transport-stream-shared-Cu3ZPhNW.mjs";
14
+ import { n as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-BuSUaAk5.mjs";
15
+ import { i as tagPendingCommentaryText } from "./assistant-text-phase-C20rxWwP.mjs";
16
+ import { r as parseStreamingJson, t as createToolArgumentPreviewSchedule } from "./json-parse-Dw_hnxsA.mjs";
17
+ import { t as notifyLlmRequestActivity } from "./llm-request-activity-BjtkplhG.mjs";
18
+ //#region packages/ai/src/providers/anthropic-auth-headers.ts
19
+ /** Inspect resolved credential shape for auth routing without exposing its value. */
20
+ function isAnthropicOAuthApiKey(apiKey) {
21
+ return typeof apiKey === "string" && getAiTransportHost().resolveSecretSentinel(apiKey).includes("sk-ant-oat");
22
+ }
23
+ function usesFoundryBearerAuth(model) {
24
+ return model.provider === "microsoft-foundry" && (model.authHeader === true || hasBearerAuthorizationHeader(model.headers));
25
+ }
26
+ function hasBearerAuthorizationHeader(headers) {
27
+ if (!headers) return false;
28
+ return Object.entries(headers).some(([key, value]) => key.toLowerCase() === "authorization" && /^bearer\s+\S+/i.test(value.trim()));
29
+ }
30
+ function omitFoundryBearerCredentialHeaders(headers) {
31
+ if (!headers) return;
32
+ const next = {};
33
+ for (const [key, value] of Object.entries(headers)) {
34
+ const lower = key.toLowerCase();
35
+ if (lower === "authorization" || lower === "x-api-key" || lower === "api-key") continue;
36
+ next[key] = value;
37
+ }
38
+ return Object.keys(next).length > 0 ? next : void 0;
39
+ }
40
+ //#endregion
41
+ //#region packages/ai/src/transports/anthropic-payload-policy.ts
42
+ /**
43
+ * Anthropic-family request payload policy helpers.
44
+ * Applies service-tier and cache-control markers only when provider endpoint
45
+ * capabilities allow them.
46
+ */
47
+ const ANTHROPIC_CACHE_CONTROL_LIMIT = 4;
48
+ const ANTHROPIC_COMPACT_THRESHOLD_MIN = 5e4;
49
+ /** Resolve the Anthropic input-token trigger, including the API's minimum. */
50
+ function resolveAnthropicCompactThreshold(contextWindow, configured) {
51
+ const configuredThreshold = parsePositiveInteger(configured);
52
+ if (configuredThreshold !== void 0) return Math.max(ANTHROPIC_COMPACT_THRESHOLD_MIN, configuredThreshold);
53
+ const resolvedContextWindow = parsePositiveInteger(contextWindow);
54
+ return Math.max(ANTHROPIC_COMPACT_THRESHOLD_MIN, resolvedContextWindow === void 0 ? ANTHROPIC_COMPACT_THRESHOLD_MIN : Math.floor(resolvedContextWindow * .7));
55
+ }
56
+ /** Resolve the server-compaction gate and effective threshold for an Anthropic route. */
57
+ function resolveAnthropicServerCompactionPlan(model, extraParams, apiKey) {
58
+ const enabled = extraParams?.anthropicServerCompaction === true && !isAnthropicOAuthApiKey(apiKey) && normalizeOptionalLowercaseString(model.api) === "anthropic-messages" && isDirectAnthropicModel(model);
59
+ return {
60
+ enabled,
61
+ ...enabled ? { threshold: resolveAnthropicCompactThreshold(model.contextWindow, extraParams?.anthropicCompactThreshold) } : {}
62
+ };
63
+ }
64
+ function isDirectAnthropicModel(model) {
65
+ const baseUrl = model.baseUrl?.trim() || process.env.ANTHROPIC_BASE_URL?.trim();
66
+ const endpointModel = baseUrl === model.baseUrl ? model : {
67
+ ...model,
68
+ baseUrl
69
+ };
70
+ const endpointClass = resolveProviderEndpoint(endpointModel).endpointClass;
71
+ return normalizeOptionalLowercaseString(model.provider) === "anthropic" && (endpointClass === "anthropic-public" || endpointClass === "default" && (!baseUrl || resolveBaseUrlHostname(baseUrl) === "api.anthropic.com"));
72
+ }
73
+ function isAnthropicServerToolClearingEnabled(model, apiKey) {
74
+ const resolvedApiKey = apiKey && getAiTransportHost().resolveSecretSentinel(apiKey);
75
+ return Boolean(resolvedApiKey?.trim()) && !isAnthropicOAuthApiKey(resolvedApiKey) && normalizeOptionalLowercaseString(model.api) === "anthropic-messages" && isDirectAnthropicModel(model);
76
+ }
77
+ function resolveBaseUrlHostname(baseUrl) {
78
+ try {
79
+ return new URL(baseUrl).hostname;
80
+ } catch {
81
+ return;
82
+ }
83
+ }
84
+ function isLongTtlEligibleEndpoint(baseUrl) {
85
+ if (typeof baseUrl !== "string") return false;
86
+ const hostname = resolveBaseUrlHostname(baseUrl);
87
+ if (!hostname) return false;
88
+ return hostname === "api.anthropic.com" || hostname === "aiplatform.googleapis.com" || hostname === "aiplatform.us.rep.googleapis.com" || hostname === "aiplatform.eu.rep.googleapis.com" || hostname.endsWith("-aiplatform.googleapis.com");
89
+ }
90
+ /** Resolve Anthropic cache-control marker retention for a request endpoint. */
91
+ function resolveAnthropicEphemeralCacheControl(baseUrl, cacheRetention) {
92
+ const retention = resolveCacheRetention(cacheRetention);
93
+ if (retention === "none") return;
94
+ const ttl = retention === "long" && (cacheRetention === "long" || isLongTtlEligibleEndpoint(baseUrl)) ? "1h" : void 0;
95
+ return {
96
+ type: "ephemeral",
97
+ ...ttl ? { ttl } : {}
98
+ };
99
+ }
100
+ function resolveAnthropicCacheOptions(model, cacheRetention) {
101
+ const supportsLongCacheRetention = model.compat?.supportsLongCacheRetention ?? model.provider !== "fireworks";
102
+ const cacheControl = resolveAnthropicEphemeralCacheControl(model.baseUrl?.trim() || process.env.ANTHROPIC_BASE_URL?.trim() || "https://api.anthropic.com", cacheRetention);
103
+ return {
104
+ cacheControl: cacheControl && !supportsLongCacheRetention ? { type: "ephemeral" } : cacheControl,
105
+ supportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? model.provider !== "fireworks"
106
+ };
107
+ }
108
+ function buildAnthropicSystemBlocks(systemPrompt, isOAuthToken, cacheControl) {
109
+ const blocks = systemPrompt ? [{
110
+ type: "text",
111
+ text: sanitizeSurrogates(systemPrompt)
112
+ }] : [];
113
+ if (cacheControl) applyAnthropicCacheControlToSystem(blocks, cacheControl);
114
+ else stripAnthropicSystemPromptBoundary(blocks);
115
+ if (systemPrompt && blocks.length === 0) blocks.push({
116
+ type: "text",
117
+ text: ""
118
+ });
119
+ if (isOAuthToken) {
120
+ const identityCacheControl = blocks.some((block) => block.cache_control) ? void 0 : cacheControl;
121
+ blocks.unshift({
122
+ type: "text",
123
+ text: ANTHROPIC_CLAUDE_CODE_BILLING_SYSTEM_BLOCK
124
+ }, {
125
+ type: "text",
126
+ text: "You are Claude Code, Anthropic's official CLI for Claude.",
127
+ ...identityCacheControl ? { cache_control: identityCacheControl } : {}
128
+ });
129
+ }
130
+ return blocks.length > 0 ? blocks : void 0;
131
+ }
132
+ /** Allocate tool and history checkpoints around the prepared stable system blocks. */
133
+ function applyAnthropicRequestCacheControl(payload, cacheControl, supportsCacheControlOnTools, cacheBreakpointOptOutMessageIndexes = /* @__PURE__ */ new Set()) {
134
+ if (!cacheControl) return;
135
+ if (supportsCacheControlOnTools && Array.isArray(payload.tools)) {
136
+ const lastTool = payload.tools.at(-1);
137
+ if (isRecord(lastTool)) lastTool.cache_control = cacheControl;
138
+ }
139
+ const usedMarkers = countAnthropicCacheControlMarkers(payload.system) + countAnthropicCacheControlMarkers(payload.tools);
140
+ applyAnthropicCacheControlToMessages(payload.messages, cacheControl, ANTHROPIC_CACHE_CONTROL_LIMIT - usedMarkers, cacheBreakpointOptOutMessageIndexes);
141
+ }
142
+ function applyAnthropicCacheControlToSystem(system, cacheControl) {
143
+ if (!Array.isArray(system)) return;
144
+ const normalizedBlocks = [];
145
+ for (const block of system) {
146
+ if (!block || typeof block !== "object") {
147
+ normalizedBlocks.push(block);
148
+ continue;
149
+ }
150
+ const record = block;
151
+ if (record.type !== "text" || typeof record.text !== "string") {
152
+ normalizedBlocks.push(block);
153
+ continue;
154
+ }
155
+ const split = splitSystemPromptCacheBoundary(record.text);
156
+ if (!split) {
157
+ if (record.cache_control === void 0) record.cache_control = cacheControl;
158
+ normalizedBlocks.push(record);
159
+ continue;
160
+ }
161
+ const { cache_control: existingCacheControl, ...rest } = record;
162
+ if (split.stablePrefix) normalizedBlocks.push({
163
+ ...rest,
164
+ text: split.stablePrefix,
165
+ cache_control: existingCacheControl ?? cacheControl
166
+ });
167
+ if (split.dynamicSuffix) normalizedBlocks.push({
168
+ ...rest,
169
+ text: split.dynamicSuffix
170
+ });
171
+ }
172
+ system.splice(0, system.length, ...normalizedBlocks);
173
+ }
174
+ function stripAnthropicSystemPromptBoundary(system) {
175
+ if (!Array.isArray(system)) return;
176
+ for (const block of system) {
177
+ if (!block || typeof block !== "object") continue;
178
+ const record = block;
179
+ if (record.type === "text" && typeof record.text === "string") record.text = stripSystemPromptCacheBoundary(record.text);
180
+ }
181
+ }
182
+ /** Apply one shared deepest-stable-message cache breakpoint policy. */
183
+ function applyAnthropicCacheControlToMessages(messages, cacheControl, markerLimit, cacheBreakpointOptOutMessageIndexes) {
184
+ if (!Array.isArray(messages) || messages.length === 0 || markerLimit <= 0) return;
185
+ let fallbackToolResult;
186
+ for (let i = messages.length - 1; i >= 0; i--) {
187
+ const message = messages[i];
188
+ if (!message || typeof message !== "object") continue;
189
+ const record = message;
190
+ if (record.role !== "user" || cacheBreakpointOptOutMessageIndexes.has(i)) continue;
191
+ const content = record.content;
192
+ if (typeof content === "string") {
193
+ if (fallbackToolResult && markerLimit === 1) {
194
+ fallbackToolResult.cache_control = cacheControl;
195
+ return;
196
+ }
197
+ record.content = [{
198
+ type: "text",
199
+ text: content,
200
+ cache_control: cacheControl
201
+ }];
202
+ if (fallbackToolResult && markerLimit > 1) fallbackToolResult.cache_control = cacheControl;
203
+ return;
204
+ }
205
+ if (!Array.isArray(content)) continue;
206
+ for (let j = content.length - 1; j >= 0; j--) {
207
+ const block = content[j];
208
+ if (!block || typeof block !== "object") continue;
209
+ const blockRecord = block;
210
+ if (blockRecord.type === "text" || blockRecord.type === "image") {
211
+ if (fallbackToolResult && markerLimit === 1) {
212
+ fallbackToolResult.cache_control = cacheControl;
213
+ return;
214
+ }
215
+ blockRecord.cache_control = cacheControl;
216
+ if (fallbackToolResult && markerLimit > 1) fallbackToolResult.cache_control = cacheControl;
217
+ return;
218
+ }
219
+ if (blockRecord.type === "tool_result" && fallbackToolResult === void 0) fallbackToolResult = blockRecord;
220
+ }
221
+ }
222
+ if (fallbackToolResult) fallbackToolResult.cache_control = cacheControl;
223
+ }
224
+ function countAnthropicCacheControlMarkers(blocks) {
225
+ if (!Array.isArray(blocks)) return 0;
226
+ let count = 0;
227
+ for (const block of blocks) if (block && typeof block === "object" && "cache_control" in block) count += 1;
228
+ return count;
229
+ }
230
+ /** @deprecated Anthropic-family provider payload helper; do not use from third-party plugins. */
231
+ function resolveAnthropicPayloadPolicy(input, model) {
232
+ const capabilities = resolveProviderRequestCapabilities({
233
+ provider: input.provider,
234
+ api: input.api,
235
+ baseUrl: input.baseUrl,
236
+ capability: "llm",
237
+ transport: "stream"
238
+ }, model);
239
+ const serverCompactionPlan = resolveAnthropicServerCompactionPlan(input, input.extraParams);
240
+ return {
241
+ allowsServiceTier: capabilities.allowsAnthropicServiceTier,
242
+ cacheControl: input.enableCacheControl === true ? resolveAnthropicEphemeralCacheControl(input.baseUrl, input.cacheRetention) : void 0,
243
+ compactThreshold: serverCompactionPlan.threshold ?? resolveAnthropicCompactThreshold(input.contextWindow, input.extraParams?.anthropicCompactThreshold),
244
+ serviceTier: input.serviceTier,
245
+ useServerCompaction: input.enableServerCompaction === true && serverCompactionPlan.enabled,
246
+ ...input.cacheTtlPruning && normalizeOptionalLowercaseString(input.api) === "anthropic-messages" && isDirectAnthropicModel(input) ? { toolClearing: {
247
+ trigger: Math.max(5e4, Math.floor((parsePositiveInteger(input.contextWindow) ?? 0) * .3)),
248
+ clearAtLeast: Math.max(12500, Math.floor((parsePositiveInteger(input.contextWindow) ?? 0) * .05)),
249
+ tools: input.cacheTtlPruning.tools
250
+ } } : {}
251
+ };
252
+ }
253
+ function resolveToolClearingExclusions(payload, filter) {
254
+ const compile = (patterns) => (patterns ?? []).map((pattern) => pattern.trim().toLowerCase()).filter(Boolean).map((pattern) => new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replaceAll("\\*", ".*")}$`));
255
+ const allow = compile(filter?.allow);
256
+ const deny = compile(filter?.deny);
257
+ if (allow.length === 0 && deny.length === 0) return [];
258
+ const excluded = new Set(filter?.deny?.map((name) => name.trim()).filter((name) => name && !name.includes("*")));
259
+ const candidates = /* @__PURE__ */ new Set();
260
+ for (const tool of Array.isArray(payload.tools) ? payload.tools : []) if (isRecord(tool) && typeof tool.name === "string") candidates.add(tool.name);
261
+ for (const message of Array.isArray(payload.messages) ? payload.messages : []) {
262
+ if (!isRecord(message) || !Array.isArray(message.content)) continue;
263
+ for (const block of message.content) if (isRecord(block) && block.type === "tool_use" && typeof block.name === "string") candidates.add(block.name);
264
+ }
265
+ for (const toolName of candidates) {
266
+ const name = toolName.trim().toLowerCase();
267
+ if (deny.some((pattern) => pattern.test(name)) || allow.length > 0 && !allow.some((pattern) => pattern.test(name))) excluded.add(toolName);
268
+ }
269
+ return [...excluded].toSorted();
270
+ }
271
+ function applyAnthropicContextManagementEdits(payload, policy) {
272
+ if (payload.context_management !== void 0) return;
273
+ const edits = [];
274
+ if (policy.toolClearing) edits.push({
275
+ type: "clear_tool_uses_20250919",
276
+ trigger: {
277
+ type: "input_tokens",
278
+ value: policy.toolClearing.trigger
279
+ },
280
+ keep: {
281
+ type: "tool_uses",
282
+ value: 3
283
+ },
284
+ clear_at_least: {
285
+ type: "input_tokens",
286
+ value: policy.toolClearing.clearAtLeast
287
+ },
288
+ exclude_tools: resolveToolClearingExclusions(payload, policy.toolClearing.tools),
289
+ clear_tool_inputs: false
290
+ });
291
+ if (policy.useServerCompaction) edits.push({
292
+ type: "compact_20260112",
293
+ trigger: {
294
+ type: "input_tokens",
295
+ value: policy.compactThreshold
296
+ }
297
+ });
298
+ if (edits.length > 0) payload.context_management = { edits };
299
+ }
300
+ function applyAnthropicContextManagementToRequest(payload, model, options, directApiKeyBetaHeader) {
301
+ if (directApiKeyBetaHeader === void 0 || !options?.cacheTtlPruning && !options?.anthropicServerCompaction) return;
302
+ applyAnthropicContextManagementEdits(payload, resolveAnthropicPayloadPolicy({
303
+ ...model,
304
+ api: "anthropic-messages",
305
+ enableServerCompaction: true,
306
+ extraParams: { ...options },
307
+ cacheTtlPruning: options?.cacheTtlPruning
308
+ }));
309
+ }
310
+ function resolveAnthropicContextManagementBetaHeader(payload, directApiKeyBetaHeader) {
311
+ if (directApiKeyBetaHeader === void 0 || !isRecord(payload.context_management)) return directApiKeyBetaHeader;
312
+ const edits = payload.context_management.edits;
313
+ const betas = new Set(directApiKeyBetaHeader.split(",").map((beta) => beta.trim()).filter(Boolean));
314
+ for (const edit of Array.isArray(edits) ? edits : []) {
315
+ if (!isRecord(edit)) continue;
316
+ if (edit.type === "clear_tool_uses_20250919") betas.add("context-management-2025-06-27");
317
+ else if (edit.type === "compact_20260112") betas.add("compact-2026-01-12");
318
+ }
319
+ return [...betas].join(",");
320
+ }
321
+ function logAnthropicContextEdits(event) {
322
+ if (!isRecord(event) || !isRecord(event.context_management)) return;
323
+ const edits = event.context_management.applied_edits;
324
+ let clearedTools = 0;
325
+ let clearedTokens = 0;
326
+ for (const edit of Array.isArray(edits) ? edits : []) {
327
+ if (!isRecord(edit) || edit.type !== "clear_tool_uses_20250919" || typeof edit.cleared_tool_uses !== "number" || !Number.isSafeInteger(edit.cleared_tool_uses) || edit.cleared_tool_uses < 0 || typeof edit.cleared_input_tokens !== "number" || !Number.isSafeInteger(edit.cleared_input_tokens) || edit.cleared_input_tokens < 0) continue;
328
+ clearedTools = Math.min(Number.MAX_SAFE_INTEGER, clearedTools + edit.cleared_tool_uses);
329
+ clearedTokens = Math.min(Number.MAX_SAFE_INTEGER, clearedTokens + edit.cleared_input_tokens);
330
+ }
331
+ if (clearedTools > 0 || clearedTokens > 0) getAiTransportHost().logInfo("anthropic", `server-side context edit: cleared ${clearedTools} tool results (${clearedTokens} input tokens)`);
332
+ }
333
+ /** @deprecated Anthropic-family provider payload helper; do not use from third-party plugins. */
334
+ function applyAnthropicPayloadPolicyToParams(payloadObj, policy, cacheBreakpointOptOutMessageIndexes) {
335
+ if (policy.allowsServiceTier && policy.serviceTier !== void 0 && payloadObj.service_tier === void 0) payloadObj.service_tier = policy.serviceTier;
336
+ if (policy.cacheControl) applyAnthropicCacheControlToSystem(payloadObj.system, policy.cacheControl);
337
+ else stripAnthropicSystemPromptBoundary(payloadObj.system);
338
+ applyAnthropicContextManagementEdits(payloadObj, policy);
339
+ applyAnthropicRequestCacheControl(payloadObj, policy.cacheControl, false, cacheBreakpointOptOutMessageIndexes);
340
+ }
341
+ /** @deprecated Anthropic-family provider payload helper; do not use from third-party plugins. */
342
+ function applyAnthropicEphemeralCacheControlMarkers(payloadObj, cacheControl = { type: "ephemeral" }) {
343
+ const messages = payloadObj.messages;
344
+ if (!Array.isArray(messages)) return;
345
+ for (const message of messages) {
346
+ if (message.role === "system" || message.role === "developer") {
347
+ if (!cacheControl) continue;
348
+ if (typeof message.content === "string") {
349
+ message.content = [{
350
+ type: "text",
351
+ text: message.content,
352
+ cache_control: cacheControl
353
+ }];
354
+ continue;
355
+ }
356
+ if (Array.isArray(message.content) && message.content.length > 0) {
357
+ const last = message.content[message.content.length - 1];
358
+ if (last && typeof last === "object") {
359
+ const record = last;
360
+ if (record.type !== "thinking" && record.type !== "redacted_thinking") record.cache_control = cacheControl;
361
+ }
362
+ }
363
+ continue;
364
+ }
365
+ if (message.role === "assistant" && Array.isArray(message.content)) for (const block of message.content) {
366
+ if (!block || typeof block !== "object") continue;
367
+ const record = block;
368
+ if (record.type === "thinking" || record.type === "redacted_thinking") delete record.cache_control;
369
+ }
370
+ }
371
+ }
372
+ //#endregion
373
+ //#region packages/ai/src/providers/anthropic-server-fallback.ts
374
+ /** Anthropic beta that re-serves safety refusals on an allowed fallback model. */
375
+ const ANTHROPIC_SERVER_SIDE_FALLBACK_BETA = "server-side-fallback-2026-07-01";
376
+ /** Let Anthropic select the recommended model for each refusal category. */
377
+ const ANTHROPIC_SERVER_SIDE_FALLBACKS = "default";
378
+ const CLAUDE_OPUS_FALLBACK_MODEL_COST = {
379
+ input: 5,
380
+ output: 25,
381
+ cacheRead: .5,
382
+ cacheWrite: 6.25
383
+ };
384
+ function resolveFallbackModelIdentity(modelId) {
385
+ if (!modelId?.trim()) return null;
386
+ const ref = { id: modelId };
387
+ const normalized = resolveClaudeModelIdentity(ref);
388
+ if (normalized === "opus" || normalized === "opus-5" || resolveClaudeOpus5ModelIdentity(ref)) return "claude-opus-5";
389
+ if (resolveClaudeFable5ModelIdentity(ref)) return "claude-fable-5";
390
+ if (/^claude-opus-4-8(?=$|[^a-z0-9])/.test(normalized)) return "claude-opus-4-8";
391
+ return normalized || null;
392
+ }
393
+ function isClaudeOpusFallbackModel(modelId) {
394
+ return modelId === "claude-opus-5" || modelId === "claude-opus-4-8";
395
+ }
396
+ /** Resolve billed rates from the serving model reported by Anthropic's fallback stream. */
397
+ function resolveAnthropicFallbackServingModelCost(params) {
398
+ const requestedModelId = resolveFallbackModelIdentity(params.requestedModelId);
399
+ const servingModelId = resolveFallbackModelIdentity(params.servingModelId);
400
+ if (!servingModelId || servingModelId === requestedModelId || !isClaudeOpusFallbackModel(servingModelId)) return params.requestedCost;
401
+ if (requestedModelId && isClaudeOpusFallbackModel(requestedModelId)) return params.requestedCost;
402
+ return CLAUDE_OPUS_FALLBACK_MODEL_COST;
403
+ }
404
+ function readBoundaryModel(value) {
405
+ if (!value || typeof value !== "object") return null;
406
+ const model = value.model;
407
+ return typeof model === "string" && model.trim() ? model : null;
408
+ }
409
+ /** Reads a `fallback` content block marking where one model's output gives way to the next. */
410
+ function readAnthropicFallbackBoundary(block) {
411
+ if (!block || typeof block !== "object") return null;
412
+ const record = block;
413
+ if (record.type !== "fallback") return null;
414
+ return {
415
+ fromModel: readBoundaryModel(record.from),
416
+ toModel: readBoundaryModel(record.to)
417
+ };
418
+ }
419
+ /**
420
+ * Drops pre-fallback thinking/tool calls while preserving the text prefix that
421
+ * the serving model continued. Dropped tool calls must never execute or replay.
422
+ */
423
+ function applyAnthropicFallbackBoundary(params) {
424
+ const { output, boundary } = params;
425
+ const survivors = output.content.filter((block) => block.type === "text");
426
+ for (const survivor of survivors) delete survivor.textSignature;
427
+ output.content.splice(0, output.content.length, ...survivors);
428
+ if (boundary.toModel) output.responseModel = boundary.toModel;
429
+ output.diagnostics = [...output.diagnostics ?? [], {
430
+ type: "provider_fallback",
431
+ timestamp: Date.now(),
432
+ details: {
433
+ provider: params.provider,
434
+ fromModel: boundary.fromModel,
435
+ toModel: boundary.toModel
436
+ }
437
+ }];
438
+ }
439
+ //#endregion
440
+ //#region packages/ai/src/providers/anthropic-thinking-replay.ts
441
+ const ANTHROPIC_OMITTED_REASONING_TEXT = "[assistant reasoning omitted]";
442
+ function applyAnthropicThinkingBindingControls(params, directApiKeyBetaHeader) {
443
+ if (directApiKeyBetaHeader === void 0 || !isRecord(params.thinking) || params.thinking.type !== "adaptive") return;
444
+ params.thinking.block_binding = { prefix_mismatch_behavior: "drop_block" };
445
+ const betas = directApiKeyBetaHeader.split(",").map((beta) => beta.trim()).filter(Boolean);
446
+ return { "anthropic-beta": [.../* @__PURE__ */ new Set([...betas, "thinking-binding-controls-2026-08-01"])].join(",") };
447
+ }
448
+ function readAnthropicInputTransformations(event) {
449
+ if (!isRecord(event) || event.type !== "message_start" && event.type !== "message_delta") return;
450
+ const transformations = (isRecord(event.message) ? event.message : void 0)?.input_transformations ?? event.input_transformations;
451
+ return Array.isArray(transformations) ? transformations : void 0;
452
+ }
453
+ function logAnthropicThinkingDrops(transformations) {
454
+ 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));
455
+ if (!drops?.length) return;
456
+ const paths = drops.slice(0, 5).map(({ reason, path }) => `${reason} at ${path}`);
457
+ getAiTransportHost().logWarn("anthropic", `replayed thinking dropped: ${drops.length} block(s) (${paths.join(", ")}${drops.length > 5 ? ", …" : ""})`);
458
+ }
459
+ function asReplayMessage(value) {
460
+ return value && typeof value === "object" ? value : void 0;
461
+ }
462
+ /**
463
+ * Anthropic tool results continue the preceding assistant turn. Preserve that
464
+ * turn's signed thinking even when the next request disables new thinking.
465
+ */
466
+ function findActiveAnthropicToolTurnAssistantIndex(messages) {
467
+ const toolResultIds = /* @__PURE__ */ new Set();
468
+ let index = messages.length - 1;
469
+ while (index >= 0) {
470
+ const message = asReplayMessage(messages[index]);
471
+ if (message?.role !== "toolResult") break;
472
+ if (typeof message.toolCallId === "string") toolResultIds.add(message.toolCallId);
473
+ index -= 1;
474
+ }
475
+ if (toolResultIds.size === 0) return -1;
476
+ const assistant = asReplayMessage(messages[index]);
477
+ if (assistant?.role !== "assistant" || !Array.isArray(assistant.content)) return -1;
478
+ const toolCallIds = /* @__PURE__ */ new Set();
479
+ for (const block of assistant.content) {
480
+ if (!block || typeof block !== "object") continue;
481
+ const record = block;
482
+ if ((record.type === "toolCall" || record.type === "tool_use" || record.type === "function_call") && typeof record.id === "string") toolCallIds.add(record.id);
483
+ }
484
+ return [...toolResultIds].every((toolCallId) => toolCallIds.has(toolCallId)) ? index : -1;
485
+ }
486
+ //#endregion
487
+ //#region packages/ai/src/providers/anthropic-tool-projection.ts
488
+ const CLAUDE_CODE_TOOL_LOOKUP = new Map([
489
+ "Read",
490
+ "Write",
491
+ "Edit",
492
+ "Bash",
493
+ "Grep",
494
+ "Glob",
495
+ "AskUserQuestion",
496
+ "EnterPlanMode",
497
+ "ExitPlanMode",
498
+ "KillShell",
499
+ "NotebookEdit",
500
+ "Skill",
501
+ "Task",
502
+ "TaskOutput",
503
+ "TodoWrite",
504
+ "WebFetch",
505
+ "WebSearch"
506
+ ].map((name) => [name.toLowerCase(), name]));
507
+ /** Preserve Claude Code's canonical tool casing for subscription OAuth requests. */
508
+ function toClaudeCodeToolName(name) {
509
+ return CLAUDE_CODE_TOOL_LOOKUP.get(name.toLowerCase()) ?? name;
510
+ }
511
+ /** Anthropic rejects forced tools while extended thinking is enabled. */
512
+ function normalizeAnthropicToolChoice(thinkingEnabled, toolChoice) {
513
+ if (thinkingEnabled && (toolChoice === "any" || typeof toolChoice === "object" && toolChoice.type === "tool")) return { type: "auto" };
514
+ return typeof toolChoice === "string" ? { type: toolChoice } : toolChoice;
515
+ }
516
+ /** Anthropic tool identifiers accept only ASCII word characters and dashes. */
517
+ function normalizeAnthropicToolCallId(id) {
518
+ return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
519
+ }
520
+ function isProviderSupportedViolation(violation) {
521
+ return violation.endsWith(".$dynamicRef") || violation.endsWith(".$dynamicAnchor");
522
+ }
523
+ const schemaValueKeywords = /* @__PURE__ */ new Set([
524
+ "additionalProperties",
525
+ "contains",
526
+ "contentSchema",
527
+ "else",
528
+ "if",
529
+ "items",
530
+ "not",
531
+ "propertyNames",
532
+ "then",
533
+ "unevaluatedItems",
534
+ "unevaluatedProperties"
535
+ ]);
536
+ const schemaArrayKeywords = /* @__PURE__ */ new Set([
537
+ "allOf",
538
+ "anyOf",
539
+ "oneOf",
540
+ "prefixItems"
541
+ ]);
542
+ const schemaMapKeywords = /* @__PURE__ */ new Set([
543
+ "$defs",
544
+ "definitions",
545
+ "dependencies",
546
+ "dependentSchemas",
547
+ "patternProperties",
548
+ "properties"
549
+ ]);
550
+ function normalizeAnthropicJsonSchema(schema) {
551
+ if (!isRecord(schema)) return schema;
552
+ let changed = false;
553
+ const normalized = { ...schema };
554
+ for (const [key, value] of Object.entries(schema)) {
555
+ if (schemaValueKeywords.has(key) && !Array.isArray(value)) {
556
+ const next = normalizeAnthropicJsonSchema(value);
557
+ normalized[key] = next;
558
+ changed ||= next !== value;
559
+ continue;
560
+ }
561
+ if (schemaArrayKeywords.has(key) && Array.isArray(value)) {
562
+ const next = value.map(normalizeAnthropicJsonSchema);
563
+ normalized[key] = next;
564
+ changed ||= next.some((entry, index) => entry !== value[index]);
565
+ continue;
566
+ }
567
+ if (schemaMapKeywords.has(key) && isRecord(value)) {
568
+ const next = Object.fromEntries(Object.entries(value).map(([entryKey, entryValue]) => [entryKey, normalizeAnthropicJsonSchema(entryValue)]));
569
+ normalized[key] = next;
570
+ changed ||= Object.entries(value).some(([entryKey, entryValue]) => next[entryKey] !== entryValue);
571
+ }
572
+ }
573
+ if (Array.isArray(schema.items)) {
574
+ normalized.prefixItems = schema.items.map(normalizeAnthropicJsonSchema);
575
+ const additionalItems = schema.additionalItems;
576
+ if (typeof additionalItems === "boolean" || isRecord(additionalItems)) normalized.items = normalizeAnthropicJsonSchema(additionalItems);
577
+ else delete normalized.items;
578
+ delete normalized.additionalItems;
579
+ changed = true;
580
+ }
581
+ if (changed) delete normalized.$schema;
582
+ return changed ? normalized : schema;
583
+ }
584
+ /** Snapshots direct/custom tool descriptors before Anthropic payload construction. */
585
+ function projectAnthropicTools(tools, toWireName) {
586
+ const projectedTools = [];
587
+ const originalNameByWireName = /* @__PURE__ */ new Map();
588
+ const unavailableOriginalNames = /* @__PURE__ */ new Set();
589
+ for (const tool of tools) {
590
+ let projectedTool;
591
+ let originalName;
592
+ try {
593
+ const name = tool.name;
594
+ originalName = name;
595
+ if (!name) continue;
596
+ const schemaProjection = projectRuntimeToolInputSchema(tool.parameters, `${name}.parameters`);
597
+ if (!isRecord(schemaProjection.schema) || schemaProjection.violations.some((violation) => !isProviderSupportedViolation(violation))) {
598
+ unavailableOriginalNames.add(name);
599
+ continue;
600
+ }
601
+ const anthropicSchema = normalizeAnthropicJsonSchema(schemaProjection.schema);
602
+ if (!isRecord(anthropicSchema)) {
603
+ unavailableOriginalNames.add(name);
604
+ continue;
605
+ }
606
+ const properties = anthropicSchema.properties;
607
+ const required = anthropicSchema.required;
608
+ if (properties !== void 0 && properties !== null && !isRecord(properties) || required !== void 0 && required !== null && (!Array.isArray(required) || required.some((entry) => typeof entry !== "string"))) {
609
+ unavailableOriginalNames.add(name);
610
+ continue;
611
+ }
612
+ let description;
613
+ try {
614
+ description = typeof tool.description === "string" ? tool.description : void 0;
615
+ } catch {}
616
+ projectedTool = {
617
+ originalName: name,
618
+ wireName: toWireName(name),
619
+ ...description ? { description } : {},
620
+ inputSchema: {
621
+ ...anthropicSchema,
622
+ type: "object",
623
+ properties: properties ?? {},
624
+ required: required ?? []
625
+ }
626
+ };
627
+ } catch {
628
+ if (originalName) unavailableOriginalNames.add(originalName);
629
+ continue;
630
+ }
631
+ const conflictingName = originalNameByWireName.get(projectedTool.wireName);
632
+ if (conflictingName !== void 0 && conflictingName !== projectedTool.originalName) throw new Error(`Anthropic tool names "${conflictingName}" and "${projectedTool.originalName}" both map to "${projectedTool.wireName}"`);
633
+ originalNameByWireName.set(projectedTool.wireName, projectedTool.originalName);
634
+ projectedTools.push(projectedTool);
635
+ }
636
+ return {
637
+ inputToolCount: tools.length,
638
+ unavailableOriginalNames,
639
+ tools: sortPromptCacheToolsByName(projectedTools)
640
+ };
641
+ }
642
+ /** Keeps forced Anthropic tool choices aligned with the projected wire names. */
643
+ function reconcileAnthropicToolChoice(choice, projection) {
644
+ if (projection.inputToolCount === 0) return choice;
645
+ if (choice.type === "tool") {
646
+ const requestedName = choice.name;
647
+ const originalMatch = projection.tools.find((tool) => tool.originalName === requestedName);
648
+ if (originalMatch) return {
649
+ ...choice,
650
+ name: originalMatch.wireName
651
+ };
652
+ if (projection.unavailableOriginalNames.has(requestedName)) throw new Error(`Anthropic tool_choice requested unavailable tool "${requestedName}" after schema conversion`);
653
+ const matchedTool = projection.tools.find((tool) => tool.wireName === requestedName);
654
+ if (!matchedTool) throw new Error(`Anthropic tool_choice requested unavailable tool "${requestedName}" after schema conversion`);
655
+ return {
656
+ ...choice,
657
+ name: matchedTool.wireName
658
+ };
659
+ }
660
+ if (projection.tools.length === 0) {
661
+ if (choice.type === "auto") return;
662
+ if (choice.type === "any") throw new Error("Anthropic tool_choice requires a tool, but no tools survived schema conversion");
663
+ }
664
+ return choice;
665
+ }
666
+ /** Maps Claude Code wire names without trusting every direct/custom descriptor. */
667
+ function resolveOriginalAnthropicToolName(name, projection) {
668
+ return projection?.tools.find((tool) => tool.wireName === name)?.originalName ?? name;
669
+ }
670
+ //#endregion
671
+ //#region packages/ai/src/transports/anthropic-compaction-replay.ts
672
+ const ANTHROPIC_COMPACTION_REPLAY_TYPE = "anthropic-compaction";
673
+ const ANTHROPIC_COMPACTION_SUPPRESSION_TYPE = "anthropic-compaction-suppression";
674
+ const ANTHROPIC_COMPACTION_SUPPRESSION_DATA = "rejected";
675
+ function createCompactionCapture(output, model, options) {
676
+ const pending = /* @__PURE__ */ new Map();
677
+ return {
678
+ begin(index, block, replayIndex) {
679
+ if (block?.type !== "compaction") return false;
680
+ const content = typeof block.content === "string" ? block.content : "";
681
+ pending.set(index, {
682
+ content,
683
+ replayIndex
684
+ });
685
+ return true;
686
+ },
687
+ delta(index, delta) {
688
+ const capture = pending.get(index);
689
+ if (!capture || delta?.type !== "compaction_delta") return false;
690
+ capture.content = typeof delta.content === "string" ? delta.content : capture.content;
691
+ return true;
692
+ },
693
+ complete(index) {
694
+ const capture = pending.get(index);
695
+ if (!capture) return false;
696
+ pending.delete(index);
697
+ captureAnthropicCompaction(output, capture.content, capture.replayIndex, model, options);
698
+ return true;
699
+ }
700
+ };
701
+ }
702
+ function isAnthropicCompactionState(state) {
703
+ if (state.v !== 1 || typeof state.data !== "string" || typeof state.provider !== "string" || typeof state.api !== "string" || typeof state.model !== "string" || typeof state.baseUrlHash !== "string" || state.sessionHash !== void 0 && typeof state.sessionHash !== "string" || state.authProfileHash !== void 0 && typeof state.authProfileHash !== "string") return false;
704
+ if (state.type === ANTHROPIC_COMPACTION_SUPPRESSION_TYPE) return state.data === ANTHROPIC_COMPACTION_SUPPRESSION_DATA;
705
+ return state.type === ANTHROPIC_COMPACTION_REPLAY_TYPE && state.data.length > 0 && (state.replayIndex === void 0 || typeof state.replayIndex === "number" && Number.isSafeInteger(state.replayIndex) && state.replayIndex >= 0);
706
+ }
707
+ function readAnthropicCompactionState(value) {
708
+ return isRecord(value) && isAnthropicCompactionState(value) ? value : void 0;
709
+ }
710
+ function captureAnthropicCompaction(output, summary, replayIndex, model, options) {
711
+ const context = buildProviderReplayContext(model, options);
712
+ if (!summary || !context.baseUrlHash || !Number.isSafeInteger(replayIndex) || replayIndex < 0) return;
713
+ output.providerReplay = {
714
+ v: 1,
715
+ type: ANTHROPIC_COMPACTION_REPLAY_TYPE,
716
+ data: summary,
717
+ replayIndex,
718
+ ...context,
719
+ baseUrlHash: context.baseUrlHash
720
+ };
721
+ }
722
+ function suppressAnthropicCompaction(output, model, options) {
723
+ const context = buildProviderReplayContext(model, options);
724
+ if (!context.baseUrlHash) return;
725
+ output.providerReplay = {
726
+ v: 1,
727
+ type: ANTHROPIC_COMPACTION_SUPPRESSION_TYPE,
728
+ data: ANTHROPIC_COMPACTION_SUPPRESSION_DATA,
729
+ ...context,
730
+ baseUrlHash: context.baseUrlHash
731
+ };
732
+ }
733
+ function resolveNewestAnthropicCompaction(messages, model, options) {
734
+ const context = buildProviderReplayContext(model, options);
735
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
736
+ const message = messages[index];
737
+ if (message?.role !== "assistant") continue;
738
+ const replayState = readAnthropicCompactionState(message.providerReplay);
739
+ if (replayState?.type === ANTHROPIC_COMPACTION_SUPPRESSION_TYPE) {
740
+ if (providerReplayContextMatches(replayState, context)) return;
741
+ continue;
742
+ }
743
+ if (message.providerReplay?.type !== ANTHROPIC_COMPACTION_REPLAY_TYPE) continue;
744
+ if (!replayState) return;
745
+ if (!providerReplayContextMatches(replayState, context)) return;
746
+ return {
747
+ owner: message,
748
+ replayIndex: replayState.replayIndex ?? 0,
749
+ summary: replayState.data
750
+ };
751
+ }
752
+ }
753
+ function buildAnthropicReplayPlan(messages, model, options) {
754
+ if (options?.enabled !== true) return { messages };
755
+ const checkpoint = resolveNewestAnthropicCompaction(messages, model, options);
756
+ if (!checkpoint) return { messages };
757
+ const ownerIndex = messages.indexOf(checkpoint.owner);
758
+ return {
759
+ messages: [{
760
+ ...checkpoint.owner,
761
+ content: checkpoint.owner.content.slice(checkpoint.replayIndex)
762
+ }, ...messages.slice(ownerIndex + 1)],
763
+ compaction: {
764
+ type: "compaction",
765
+ content: checkpoint.summary
766
+ }
767
+ };
768
+ }
769
+ /** Match Anthropic's 400 response when a replay block is no longer accepted. */
770
+ function isAnthropicReplayRejection(error) {
771
+ if (!error || typeof error !== "object") return false;
772
+ const record = error;
773
+ const nested = record.error && typeof record.error === "object" && !Array.isArray(record.error) ? record.error : void 0;
774
+ const text = [
775
+ record.message,
776
+ record.code,
777
+ nested?.message,
778
+ nested?.code
779
+ ].filter((value) => typeof value === "string").join(" ").toLowerCase();
780
+ return (record.status === 400 || text.startsWith("http 400:")) && (text.includes("compaction") || text.includes("context_management"));
781
+ }
782
+ //#endregion
783
+ //#region packages/ai/src/internal/anthropic-inline-images.ts
784
+ const ANTHROPIC_IMAGE_MEDIA_TYPE_SET = /* @__PURE__ */ new Set([
785
+ "image/jpeg",
786
+ "image/png",
787
+ "image/gif",
788
+ "image/webp"
789
+ ]);
790
+ const ANTHROPIC_INLINE_IMAGES_DECODE_SAFETY_BYTES = 67108864;
791
+ function createAnthropicInlineImageBudget() {
792
+ return { totalBytes: 0 };
793
+ }
794
+ function resolveAnthropicImageMediaType(value) {
795
+ if (ANTHROPIC_IMAGE_MEDIA_TYPE_SET.has(value)) return value;
796
+ throw new Error(`Unsupported Anthropic image media type after normalization: ${value}`);
797
+ }
798
+ async function normalizeAnthropicInlineContent(content, budget) {
799
+ if (!content.some((block) => block.type === "image")) return content.filter((block) => block.type === "text");
800
+ const inputBytes = content.reduce((total, block) => block.type === "image" ? total + estimateBase64DecodedBytes(block.data) : total, 0);
801
+ if (budget.totalBytes + inputBytes > ANTHROPIC_INLINE_IMAGES_DECODE_SAFETY_BYTES) throw new Error("Anthropic inline images exceed the 64 MB aggregate decoded safety limit.");
802
+ const normalized = [];
803
+ for (const block of content) {
804
+ if (block.type !== "image") {
805
+ normalized.push(block);
806
+ continue;
807
+ }
808
+ const normalizedBlocks = await getAiTransportHost().normalizeAnthropicInlineContentBlocks([block]);
809
+ const outputBytes = normalizedBlocks.reduce((total, normalizedBlock) => normalizedBlock.type === "image" ? total + estimateBase64DecodedBytes(normalizedBlock.data) : total, 0);
810
+ if (budget.totalBytes + outputBytes > ANTHROPIC_INLINE_IMAGES_DECODE_SAFETY_BYTES) throw new Error("Anthropic inline images exceed the 64 MB aggregate decoded safety limit.");
811
+ budget.totalBytes += outputBytes;
812
+ normalized.push(...normalizedBlocks);
813
+ }
814
+ return normalized;
815
+ }
816
+ //#endregion
817
+ //#region packages/ai/src/transports/anthropic-messages.ts
818
+ const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
819
+ async function convertContentBlocks(content, model, imageBudget, profile, isError) {
820
+ const mediaPlaceholder = describeToolResultMediaPlaceholder(content);
821
+ if (!((profile === "provider" || model.input.includes("image")) && content.some(isImageWithMediaPayload))) return sanitizeNonEmptyTransportPayloadText(extractToolResultText(content), mediaPlaceholder ?? (profile === "transport" ? "(no output)" : isError ? "[tool error with no output]" : ""));
822
+ const blocks = [];
823
+ let hasTextBlock = false;
824
+ for (const block of content) {
825
+ const record = asOptionalObjectRecord(block);
826
+ if (!record) continue;
827
+ const blockText = extractToolResultBlockText(block);
828
+ if (blockText) {
829
+ blocks.push({
830
+ type: "text",
831
+ text: sanitizeTransportPayloadText(blockText)
832
+ });
833
+ hasTextBlock = true;
834
+ }
835
+ if (!isImageWithMediaPayload(record)) continue;
836
+ const [normalizedImage] = await normalizeAnthropicInlineContent([{
837
+ type: "image",
838
+ data: typeof record.data === "string" ? record.data : "",
839
+ mimeType: typeof record.mimeType === "string" ? record.mimeType : profile === "provider" ? "image/jpeg" : "image/png"
840
+ }], imageBudget);
841
+ if (normalizedImage?.type !== "image") continue;
842
+ blocks.push({
843
+ type: "image",
844
+ source: {
845
+ type: "base64",
846
+ media_type: resolveAnthropicImageMediaType(normalizedImage.mimeType),
847
+ data: normalizedImage.data
848
+ }
849
+ });
850
+ }
851
+ if (!hasTextBlock) blocks.unshift({
852
+ type: "text",
853
+ text: mediaPlaceholder ?? "(see attached image)"
854
+ });
855
+ return blocks;
856
+ }
857
+ async function convertAnthropicMessages(transformedMessages, model, isOAuthToken, options) {
858
+ const params = [];
859
+ const imageBudget = createAnthropicInlineImageBudget();
860
+ const allowReasoningContentReplay = options.allowReasoningContentReplay === true;
861
+ const replayThinkingEnabled = options.replayThinkingEnabled !== false;
862
+ const managed = options.profile === "transport";
863
+ const activeToolTurnAssistantIndex = replayThinkingEnabled ? -1 : findActiveAnthropicToolTurnAssistantIndex(transformedMessages);
864
+ for (let i = 0; i < transformedMessages.length; i += 1) {
865
+ const msg = transformedMessages[i];
866
+ if (!msg) continue;
867
+ if (msg.role === "user") {
868
+ if (typeof msg.content === "string") {
869
+ if (msg.content.trim().length > 0) {
870
+ const userParam = {
871
+ role: "user",
872
+ content: sanitizeTransportPayloadText(msg.content)
873
+ };
874
+ params.push(userParam);
875
+ }
876
+ continue;
877
+ }
878
+ const blocks = (!managed || model.input.includes("image") ? await normalizeAnthropicInlineContent(msg.content, imageBudget) : msg.content.map((item) => item.type === "image" ? {
879
+ type: "text",
880
+ text: NON_VISION_USER_IMAGE_PLACEHOLDER
881
+ } : item)).map((item) => item.type === "text" ? {
882
+ type: "text",
883
+ text: sanitizeTransportPayloadText(item.text)
884
+ } : {
885
+ type: "image",
886
+ source: {
887
+ type: "base64",
888
+ media_type: resolveAnthropicImageMediaType(item.mimeType),
889
+ data: item.data
890
+ }
891
+ });
892
+ let filteredBlocks = !managed || model.input.includes("image") ? blocks : blocks.filter((block) => block.type !== "image");
893
+ filteredBlocks = filteredBlocks.filter((block) => block.type !== "text" || block.text.trim().length > 0);
894
+ if (filteredBlocks.length === 0) continue;
895
+ const userParam = {
896
+ role: "user",
897
+ content: filteredBlocks
898
+ };
899
+ params.push(userParam);
900
+ continue;
901
+ }
902
+ if (msg.role === "assistant") {
903
+ const blocks = i === 0 && options.compaction ? [options.compaction] : [];
904
+ const reasoningContent = [];
905
+ let omittedThinking = false;
906
+ for (const block of msg.content) {
907
+ if (block.type === "text") {
908
+ if (block.text.trim().length > 0) blocks.push({
909
+ type: "text",
910
+ text: sanitizeTransportPayloadText(block.text)
911
+ });
912
+ continue;
913
+ }
914
+ if (block.type === "thinking") {
915
+ const thinkingSignature = block.thinkingSignature?.trim();
916
+ const isReasoningContent = thinkingSignature === "reasoning_content";
917
+ if (!replayThinkingEnabled && i !== activeToolTurnAssistantIndex && (!managed || !isReasoningContent)) {
918
+ omittedThinking = true;
919
+ continue;
920
+ }
921
+ if (block.redacted) {
922
+ if (!managed && !block.thinkingSignature) throw new Error("redacted thinking block is missing its opaque signature");
923
+ blocks.push({
924
+ type: "redacted_thinking",
925
+ data: block.thinkingSignature
926
+ });
927
+ continue;
928
+ }
929
+ const hasNativeThinkingSignature = Boolean(thinkingSignature) && !isReasoningContent;
930
+ if (block.thinking.trim().length === 0 && !hasNativeThinkingSignature) continue;
931
+ if (!thinkingSignature && !options.allowEmptySignature) blocks.push({
932
+ type: "text",
933
+ text: sanitizeTransportPayloadText(block.thinking)
934
+ });
935
+ else {
936
+ const thinking = thinkingSignature === "reasoning_content" ? sanitizeTransportPayloadText(block.thinking) : block.thinking;
937
+ if (thinkingSignature === "reasoning_content") {
938
+ if (allowReasoningContentReplay) {
939
+ blocks.push({
940
+ type: "thinking",
941
+ thinking,
942
+ signature: thinkingSignature ?? ""
943
+ });
944
+ reasoningContent.push(thinking);
945
+ }
946
+ continue;
947
+ }
948
+ blocks.push({
949
+ type: "thinking",
950
+ thinking,
951
+ signature: thinkingSignature ?? ""
952
+ });
953
+ }
954
+ continue;
955
+ }
956
+ if (block.type === "toolCall") blocks.push({
957
+ type: "tool_use",
958
+ id: block.id,
959
+ name: isOAuthToken ? toClaudeCodeToolName(block.name) : block.name,
960
+ input: managed ? coerceTransportToolCallArguments(block.arguments) : block.arguments ?? {}
961
+ });
962
+ }
963
+ if (blocks.length === 0 && omittedThinking) blocks.push({
964
+ type: "text",
965
+ text: ANTHROPIC_OMITTED_REASONING_TEXT
966
+ });
967
+ if (blocks.length > 0) {
968
+ const assistantMsg = {
969
+ role: "assistant",
970
+ content: blocks
971
+ };
972
+ if (reasoningContent.length > 0) assistantMsg.reasoning_content = reasoningContent.join("\n");
973
+ else if (allowReasoningContentReplay) blocks.unshift({
974
+ type: "thinking",
975
+ thinking: "",
976
+ signature: "reasoning_content"
977
+ });
978
+ params.push(assistantMsg);
979
+ }
980
+ continue;
981
+ }
982
+ if (msg.role === "toolResult") {
983
+ const toolResults = [];
984
+ let j = i;
985
+ while (j < transformedMessages.length) {
986
+ const nextMsg = transformedMessages.at(j);
987
+ if (nextMsg?.role !== "toolResult") break;
988
+ toolResults.push({
989
+ type: "tool_result",
990
+ tool_use_id: nextMsg.toolCallId,
991
+ content: await convertContentBlocks(nextMsg.content, model, imageBudget, options.profile, nextMsg.isError),
992
+ is_error: nextMsg.isError
993
+ });
994
+ j += 1;
995
+ }
996
+ i = j - 1;
997
+ params.push({
998
+ role: "user",
999
+ content: toolResults
1000
+ });
1001
+ }
1002
+ }
1003
+ return params;
1004
+ }
1005
+ /** Shared generation contract, after each entry point resolves its defaults and tool policy. */
1006
+ function buildAnthropicGenerationParams({ model, options, tools, toolProjection, profile }) {
1007
+ const params = {};
1008
+ const mandatoryAdaptiveThinking = requiresClaudeAdaptiveThinking(model);
1009
+ if (options?.temperature !== void 0 && !options?.thinkingEnabled && !supportsClaudeNativeXhighEffort(model)) params.temperature = options.temperature;
1010
+ if (options?.stop !== void 0 && options.stop.length > 0) params.stop_sequences = options.stop;
1011
+ if (tools && tools.length > 0) params.tools = tools;
1012
+ if (mandatoryAdaptiveThinking || model.reasoning || supportsClaudeAdaptiveThinking(model)) {
1013
+ if (mandatoryAdaptiveThinking || options?.thinkingEnabled) {
1014
+ const display = options?.thinkingDisplay ?? "summarized";
1015
+ if (supportsClaudeAdaptiveThinking(model)) {
1016
+ params.thinking = {
1017
+ type: "adaptive",
1018
+ display
1019
+ };
1020
+ const effort = options?.effort ?? (mandatoryAdaptiveThinking ? "high" : void 0);
1021
+ if (effort) params.output_config = { effort };
1022
+ } else params.thinking = {
1023
+ type: "enabled",
1024
+ budget_tokens: options?.thinkingBudgetTokens ?? 1024,
1025
+ ...profile === "provider" ? { display } : {}
1026
+ };
1027
+ } else if (options?.thinkingEnabled === false) params.thinking = { type: "disabled" };
1028
+ }
1029
+ if (options?.metadata) {
1030
+ const userId = options.metadata.user_id;
1031
+ if (typeof userId === "string") params.metadata = { user_id: userId };
1032
+ }
1033
+ if (options?.toolChoice) {
1034
+ const normalizedToolChoice = normalizeAnthropicToolChoice(mandatoryAdaptiveThinking || options?.thinkingEnabled === true, options.toolChoice);
1035
+ const projectedToolChoice = toolProjection ? reconcileAnthropicToolChoice(normalizedToolChoice, toolProjection) : normalizedToolChoice;
1036
+ if (projectedToolChoice) params.tool_choice = projectedToolChoice;
1037
+ }
1038
+ return params;
1039
+ }
1040
+ function convertAnthropicTools(tools, isOAuthTokenLocal, supportsEagerToolInputStreaming = false) {
1041
+ const projection = projectAnthropicTools(tools, (name) => isOAuthTokenLocal ? toClaudeCodeToolName(name) : name);
1042
+ const convertedTools = [];
1043
+ for (const tool of projection.tools) {
1044
+ const convertedTool = {
1045
+ name: tool.wireName,
1046
+ description: tool.description,
1047
+ input_schema: tool.inputSchema
1048
+ };
1049
+ if (supportsEagerToolInputStreaming) convertedTool.eager_input_streaming = true;
1050
+ convertedTools.push(convertedTool);
1051
+ }
1052
+ return {
1053
+ projection,
1054
+ tools: convertedTools
1055
+ };
1056
+ }
1057
+ //#endregion
1058
+ //#region packages/ai/src/providers/anthropic-refusal.ts
1059
+ function readAnthropicRefusalDetails(value) {
1060
+ if (!value || typeof value !== "object") return {
1061
+ category: null,
1062
+ explanation: null
1063
+ };
1064
+ const details = value;
1065
+ return {
1066
+ category: normalizeNullableString(details.category),
1067
+ explanation: normalizeNullableString(details.explanation)
1068
+ };
1069
+ }
1070
+ function formatAnthropicRefusalMessage(details) {
1071
+ return `Anthropic refusal${details.category ? ` (category: ${details.category})` : ""}${details.explanation ? `: ${details.explanation}` : "."}`;
1072
+ }
1073
+ function applyAnthropicRefusal(output, stopDetails, provider) {
1074
+ const details = readAnthropicRefusalDetails(stopDetails);
1075
+ output.stopReason = "error";
1076
+ output.errorMessage = formatAnthropicRefusalMessage(details);
1077
+ output.diagnostics = [...output.diagnostics ?? [], {
1078
+ type: "provider_refusal",
1079
+ timestamp: Date.now(),
1080
+ details: {
1081
+ provider,
1082
+ category: details.category,
1083
+ explanation: details.explanation
1084
+ }
1085
+ }];
1086
+ }
1087
+ //#endregion
1088
+ //#region packages/ai/src/providers/anthropic-usage.ts
1089
+ function readAnthropicUsageTokenCount(value) {
1090
+ return asNonNegativeFiniteNumber(value);
1091
+ }
1092
+ function readAnthropicCacheWriteUsage(usage) {
1093
+ if (!usage.cache_creation || typeof usage.cache_creation !== "object") return {};
1094
+ const cacheCreation = usage.cache_creation;
1095
+ const cacheWrite5m = readAnthropicUsageTokenCount(cacheCreation.ephemeral_5m_input_tokens);
1096
+ const cacheWrite1h = readAnthropicUsageTokenCount(cacheCreation.ephemeral_1h_input_tokens);
1097
+ return {
1098
+ ...cacheWrite5m !== void 0 ? { cacheWrite5m } : {},
1099
+ ...cacheWrite1h !== void 0 ? { cacheWrite1h } : {}
1100
+ };
1101
+ }
1102
+ function readAnthropicPromptUsageSnapshot(usage) {
1103
+ const input = readAnthropicUsageTokenCount(usage.input_tokens);
1104
+ const cacheRead = usage.cache_read_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_read_input_tokens);
1105
+ const cacheWrite = usage.cache_creation_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_creation_input_tokens);
1106
+ if (input === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
1107
+ return {
1108
+ input,
1109
+ cacheRead,
1110
+ cacheWrite
1111
+ };
1112
+ }
1113
+ function readLastAnthropicIterationUsage(usage) {
1114
+ if (usage.iterations == null) return { state: "absent" };
1115
+ if (!Array.isArray(usage.iterations) || usage.iterations.length === 0) return { state: "invalid" };
1116
+ const iteration = usage.iterations.at(-1);
1117
+ if (!iteration || typeof iteration !== "object" || Array.isArray(iteration)) return { state: "invalid" };
1118
+ const record = iteration;
1119
+ const input = readAnthropicUsageTokenCount(record.input_tokens);
1120
+ const cacheRead = readAnthropicUsageTokenCount(record.cache_read_input_tokens);
1121
+ const cacheWrite = readAnthropicUsageTokenCount(record.cache_creation_input_tokens);
1122
+ const outputTokens = readAnthropicUsageTokenCount(record.output_tokens);
1123
+ if (input === void 0 || cacheRead === void 0 || cacheWrite === void 0 || outputTokens === void 0) return { state: "invalid" };
1124
+ const contextPromptTokens = input + cacheRead + cacheWrite;
1125
+ return {
1126
+ state: "valid",
1127
+ usage: {
1128
+ contextPromptTokens,
1129
+ totalTokens: contextPromptTokens + outputTokens
1130
+ }
1131
+ };
1132
+ }
1133
+ function readAnthropicCompactionBilledUsage(iterations) {
1134
+ if (!Array.isArray(iterations) || iterations.length === 0) return;
1135
+ let sawCompaction = false;
1136
+ const billed = {
1137
+ input: 0,
1138
+ output: 0,
1139
+ cacheRead: 0,
1140
+ cacheWrite: 0,
1141
+ cacheWrite1h: 0
1142
+ };
1143
+ for (const iteration of iterations) {
1144
+ if (!iteration || typeof iteration !== "object" || Array.isArray(iteration)) return;
1145
+ const record = iteration;
1146
+ const input = readAnthropicUsageTokenCount(record.input_tokens);
1147
+ const output = readAnthropicUsageTokenCount(record.output_tokens);
1148
+ const cacheRead = readAnthropicUsageTokenCount(record.cache_read_input_tokens);
1149
+ const cacheWrite = readAnthropicUsageTokenCount(record.cache_creation_input_tokens);
1150
+ if (input === void 0 || output === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
1151
+ sawCompaction ||= record.type === "compaction";
1152
+ billed.input += input;
1153
+ billed.output += output;
1154
+ billed.cacheRead += cacheRead;
1155
+ billed.cacheWrite += cacheWrite;
1156
+ billed.cacheWrite1h += readAnthropicCacheWriteUsage(record).cacheWrite1h ?? 0;
1157
+ }
1158
+ return sawCompaction ? billed : void 0;
1159
+ }
1160
+ /** Record independent billing buckets without treating zero placeholders as context proof. */
1161
+ function applyAnthropicMessageStartUsage(target, payload) {
1162
+ const promptUsage = readAnthropicPromptUsageSnapshot(payload);
1163
+ const promptTokens = promptUsage ? promptUsage.input + promptUsage.cacheRead + promptUsage.cacheWrite : 0;
1164
+ const inputTokens = readAnthropicUsageTokenCount(payload.input_tokens);
1165
+ if (inputTokens !== void 0) target.input = inputTokens;
1166
+ const outputTokens = readAnthropicUsageTokenCount(payload.output_tokens);
1167
+ if (outputTokens !== void 0) target.output = outputTokens;
1168
+ const cacheReadTokens = payload.cache_read_input_tokens == null ? 0 : readAnthropicUsageTokenCount(payload.cache_read_input_tokens);
1169
+ if (cacheReadTokens !== void 0) target.cacheRead = cacheReadTokens;
1170
+ const cacheWriteTokens = payload.cache_creation_input_tokens == null ? 0 : readAnthropicUsageTokenCount(payload.cache_creation_input_tokens);
1171
+ if (cacheWriteTokens !== void 0) target.cacheWrite = cacheWriteTokens;
1172
+ const { cacheWrite1h } = readAnthropicCacheWriteUsage(payload);
1173
+ if (cacheWrite1h !== void 0) target.cacheWrite1h = cacheWrite1h;
1174
+ target.totalTokens = target.input + target.output + target.cacheRead + target.cacheWrite;
1175
+ if (promptTokens > 0 && outputTokens !== void 0) target.contextUsage = {
1176
+ state: "available",
1177
+ promptTokens,
1178
+ totalTokens: promptTokens + target.output
1179
+ };
1180
+ return promptTokens > 0 ? promptUsage : void 0;
1181
+ }
1182
+ /** Keep billing and context distinct; omitted usage preserves the last snapshot. */
1183
+ function applyAnthropicMessageDeltaUsage(target, usage, messageStartPromptUsage) {
1184
+ if (!usage) return;
1185
+ const billedIterations = readAnthropicCompactionBilledUsage(usage.iterations);
1186
+ const inputTokens = readAnthropicUsageTokenCount(usage.input_tokens);
1187
+ const outputTokens = readAnthropicUsageTokenCount(usage.output_tokens);
1188
+ const cacheReadTokens = readAnthropicUsageTokenCount(usage.cache_read_input_tokens);
1189
+ const cacheWriteTokens = readAnthropicUsageTokenCount(usage.cache_creation_input_tokens);
1190
+ const resolved = billedIterations ?? {
1191
+ input: inputTokens,
1192
+ output: outputTokens,
1193
+ cacheRead: cacheReadTokens,
1194
+ cacheWrite: cacheWriteTokens,
1195
+ cacheWrite1h: readAnthropicCacheWriteUsage(usage).cacheWrite1h
1196
+ };
1197
+ if (resolved.input !== void 0) target.input = resolved.input;
1198
+ if (resolved.output !== void 0) target.output = resolved.output;
1199
+ if (resolved.cacheRead !== void 0) target.cacheRead = resolved.cacheRead;
1200
+ if (resolved.cacheWrite !== void 0) target.cacheWrite = resolved.cacheWrite;
1201
+ if (resolved.cacheWrite1h !== void 0) target.cacheWrite1h = resolved.cacheWrite1h;
1202
+ target.totalTokens = target.input + target.output + target.cacheRead + target.cacheWrite;
1203
+ const iterationUsage = readLastAnthropicIterationUsage(usage);
1204
+ if (iterationUsage.state === "valid") target.contextUsage = {
1205
+ state: "available",
1206
+ promptTokens: iterationUsage.usage.contextPromptTokens,
1207
+ totalTokens: iterationUsage.usage.totalTokens
1208
+ };
1209
+ else if (iterationUsage.state === "invalid") target.contextUsage = { state: "unavailable" };
1210
+ else if (outputTokens !== void 0 && (messageStartPromptUsage !== void 0 || (cacheReadTokens !== void 0 || cacheWriteTokens !== void 0) && readAnthropicPromptUsageSnapshot(usage) !== void 0)) {
1211
+ const promptTokens = target.input + target.cacheRead + target.cacheWrite;
1212
+ target.contextUsage = {
1213
+ state: "available",
1214
+ promptTokens,
1215
+ totalTokens: promptTokens + target.output
1216
+ };
1217
+ } else target.contextUsage = { state: "unavailable" };
1218
+ }
1219
+ //#endregion
1220
+ //#region packages/ai/src/transports/anthropic-stream-reducer.ts
1221
+ /** One Messages protocol reducer; entry points retain their established preview/replay contracts. */
1222
+ async function consumeAnthropicStream(params) {
1223
+ const { model, options, output, stream, refusalBuffer, isOAuthToken, toolProjection } = params;
1224
+ const managed = params.profile === "transport";
1225
+ const eventSink = refusalBuffer ?? stream;
1226
+ let costModel = model;
1227
+ let messageStartPromptUsage;
1228
+ let inputTransformations;
1229
+ const anthropicStream = params.events;
1230
+ try {
1231
+ const blocks = output.content;
1232
+ const blockIndexes = /* @__PURE__ */ new Map();
1233
+ const toolArgumentPreviewSchedules = /* @__PURE__ */ new WeakMap();
1234
+ const seededToolArguments = /* @__PURE__ */ new WeakMap();
1235
+ const sealedToolCalls = [];
1236
+ const compactionCapture = createCompactionCapture(output, model, options);
1237
+ const pendingThinkingSignatures = /* @__PURE__ */ new Map();
1238
+ const allowReasoningContentReplay = managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native";
1239
+ const reasoningContentThinkingBlocks = /* @__PURE__ */ new Map();
1240
+ const reasoningContentTextBlocks = /* @__PURE__ */ new Map();
1241
+ let sawMessageStop = false;
1242
+ const pendingTextEnds = [];
1243
+ const flushPendingTextEnds = () => {
1244
+ for (const event of pendingTextEnds) eventSink.push(event);
1245
+ pendingTextEnds.length = 0;
1246
+ };
1247
+ const emitTextEnd = (event) => {
1248
+ if (managed) pendingTextEnds.push(event);
1249
+ else eventSink.push(event);
1250
+ };
1251
+ const eventIndexKey = (eventIndex) => typeof eventIndex === "number" ? eventIndex : -1;
1252
+ const appendReasoningContentThinkingDelta = (eventIndex, rawText) => {
1253
+ if (typeof rawText !== "string") return false;
1254
+ const text = sanitizeTransportPayloadText(rawText);
1255
+ if (text.length === 0) return false;
1256
+ const key = eventIndexKey(eventIndex);
1257
+ let contentIndex = reasoningContentThinkingBlocks.get(key);
1258
+ let block = contentIndex === void 0 ? void 0 : blocks[contentIndex];
1259
+ if (!block || block.type !== "thinking") {
1260
+ block = {
1261
+ type: "thinking",
1262
+ thinking: "",
1263
+ thinkingSignature: "reasoning_content"
1264
+ };
1265
+ output.content.push(block);
1266
+ contentIndex = output.content.length - 1;
1267
+ reasoningContentThinkingBlocks.set(key, contentIndex);
1268
+ eventSink.push({
1269
+ type: "thinking_start",
1270
+ contentIndex,
1271
+ partial: output
1272
+ });
1273
+ }
1274
+ if (contentIndex === void 0) return false;
1275
+ appendAssistantThinking(block, text);
1276
+ block.thinkingSignature = "reasoning_content";
1277
+ eventSink.push({
1278
+ type: "thinking_delta",
1279
+ contentIndex,
1280
+ delta: text,
1281
+ partial: output
1282
+ });
1283
+ return true;
1284
+ };
1285
+ const appendReasoningContentTextDelta = (eventIndex, rawText) => {
1286
+ if (typeof rawText !== "string") return false;
1287
+ const text = sanitizeTransportPayloadText(rawText);
1288
+ if (text.length === 0) return false;
1289
+ const key = eventIndexKey(eventIndex);
1290
+ let contentIndex = reasoningContentTextBlocks.get(key);
1291
+ let block = contentIndex === void 0 ? void 0 : blocks[contentIndex];
1292
+ if (!block || block.type !== "text") {
1293
+ block = {
1294
+ type: "text",
1295
+ text: ""
1296
+ };
1297
+ output.content.push(block);
1298
+ contentIndex = output.content.length - 1;
1299
+ reasoningContentTextBlocks.set(key, contentIndex);
1300
+ eventSink.push({
1301
+ type: "text_start",
1302
+ contentIndex,
1303
+ partial: output
1304
+ });
1305
+ }
1306
+ if (contentIndex === void 0) return false;
1307
+ block.text += text;
1308
+ eventSink.push({
1309
+ type: "text_delta",
1310
+ contentIndex,
1311
+ delta: text,
1312
+ partial: output
1313
+ });
1314
+ return true;
1315
+ };
1316
+ const finishReasoningContentSidecars = (eventIndex) => {
1317
+ const key = eventIndexKey(eventIndex);
1318
+ const thinkingContentIndex = reasoningContentThinkingBlocks.get(key);
1319
+ if (thinkingContentIndex !== void 0) {
1320
+ reasoningContentThinkingBlocks.delete(key);
1321
+ const block = output.content[thinkingContentIndex];
1322
+ if (block?.type === "thinking") eventSink.push({
1323
+ type: "thinking_end",
1324
+ contentIndex: thinkingContentIndex,
1325
+ content: block.thinking,
1326
+ partial: output
1327
+ });
1328
+ }
1329
+ const textContentIndex = reasoningContentTextBlocks.get(key);
1330
+ if (textContentIndex === void 0) return;
1331
+ reasoningContentTextBlocks.delete(key);
1332
+ const block = output.content[textContentIndex];
1333
+ if (block?.type === "text") eventSink.push({
1334
+ type: "text_end",
1335
+ contentIndex: textContentIndex,
1336
+ content: block.text,
1337
+ partial: output
1338
+ });
1339
+ };
1340
+ for await (const rawEvent of anthropicStream) {
1341
+ const event = asRecord(rawEvent);
1342
+ inputTransformations = readAnthropicInputTransformations(event) ?? inputTransformations;
1343
+ if (managed) notifyLlmRequestActivity(options.signal);
1344
+ if (event.type === "error") {
1345
+ const error = asOptionalObjectRecord(event.error);
1346
+ throw new Error(readStringField(error, "message") || "Anthropic Messages stream failed");
1347
+ }
1348
+ if (event.type === "message_start") {
1349
+ const message = asOptionalObjectRecord(event.message);
1350
+ const usage = asRecord(message?.usage);
1351
+ output.responseId = typeof message?.id === "string" ? message.id : void 0;
1352
+ output.responseModel = typeof message?.model === "string" ? message.model : void 0;
1353
+ messageStartPromptUsage = applyAnthropicMessageStartUsage(output.usage, usage);
1354
+ calculateCost(costModel, output.usage);
1355
+ eventSink.push({
1356
+ type: "start",
1357
+ partial: output
1358
+ });
1359
+ continue;
1360
+ }
1361
+ if (event.type === "message_stop") {
1362
+ sawMessageStop = true;
1363
+ continue;
1364
+ }
1365
+ if (event.type === "content_block_start") {
1366
+ const contentBlock = asOptionalObjectRecord(event.content_block);
1367
+ const index = typeof event.index === "number" ? event.index : -1;
1368
+ if (options.anthropicServerCompaction === true && compactionCapture.begin(index, contentBlock, output.content.length)) continue;
1369
+ const fallbackBoundary = refusalBuffer ? readAnthropicFallbackBoundary(contentBlock) : null;
1370
+ if (fallbackBoundary) {
1371
+ refusalBuffer?.discard();
1372
+ sealedToolCalls.length = 0;
1373
+ pendingTextEnds.length = 0;
1374
+ blockIndexes.clear();
1375
+ pendingThinkingSignatures.clear();
1376
+ applyAnthropicFallbackBoundary({
1377
+ output,
1378
+ boundary: fallbackBoundary,
1379
+ provider: model.provider
1380
+ });
1381
+ costModel = {
1382
+ ...model,
1383
+ cost: resolveAnthropicFallbackServingModelCost({
1384
+ requestedModelId: model.id,
1385
+ servingModelId: fallbackBoundary.toModel,
1386
+ requestedCost: model.cost
1387
+ })
1388
+ };
1389
+ calculateCost(costModel, output.usage);
1390
+ eventSink.push({
1391
+ type: "start",
1392
+ partial: output
1393
+ });
1394
+ for (const [i, block] of blocks.entries()) {
1395
+ if (block.type !== "text") continue;
1396
+ delete block.index;
1397
+ eventSink.push({
1398
+ type: "text_start",
1399
+ contentIndex: i,
1400
+ partial: output
1401
+ });
1402
+ if (block.text) eventSink.push({
1403
+ type: "text_delta",
1404
+ contentIndex: i,
1405
+ delta: block.text,
1406
+ partial: output
1407
+ });
1408
+ emitTextEnd({
1409
+ type: "text_end",
1410
+ contentIndex: i,
1411
+ content: block.text,
1412
+ partial: output
1413
+ });
1414
+ }
1415
+ continue;
1416
+ }
1417
+ pendingThinkingSignatures.delete(index);
1418
+ if (contentBlock?.type === "text") {
1419
+ const text = typeof contentBlock.text === "string" ? sanitizeTransportPayloadText(contentBlock.text) : "";
1420
+ const block = {
1421
+ type: "text",
1422
+ text,
1423
+ index
1424
+ };
1425
+ output.content.push(block);
1426
+ const contentIndex = output.content.length - 1;
1427
+ blockIndexes.set(index, contentIndex);
1428
+ eventSink.push({
1429
+ type: "text_start",
1430
+ contentIndex,
1431
+ partial: output
1432
+ });
1433
+ if (text.length > 0) eventSink.push({
1434
+ type: "text_delta",
1435
+ contentIndex,
1436
+ delta: text,
1437
+ partial: output
1438
+ });
1439
+ continue;
1440
+ }
1441
+ if (contentBlock?.type === "thinking") {
1442
+ const thinking = typeof contentBlock.thinking === "string" ? contentBlock.thinking : "";
1443
+ const block = {
1444
+ type: "thinking",
1445
+ thinking,
1446
+ thinkingSignature: typeof contentBlock.signature === "string" ? contentBlock.signature : "",
1447
+ index
1448
+ };
1449
+ output.content.push(block);
1450
+ const contentIndex = output.content.length - 1;
1451
+ blockIndexes.set(index, contentIndex);
1452
+ eventSink.push({
1453
+ type: "thinking_start",
1454
+ contentIndex,
1455
+ partial: output
1456
+ });
1457
+ if (thinking.length > 0) eventSink.push({
1458
+ type: "thinking_delta",
1459
+ contentIndex,
1460
+ delta: thinking,
1461
+ partial: output
1462
+ });
1463
+ continue;
1464
+ }
1465
+ if (contentBlock?.type === "redacted_thinking") {
1466
+ const block = {
1467
+ type: "thinking",
1468
+ thinking: "[Reasoning redacted]",
1469
+ thinkingSignature: typeof contentBlock.data === "string" ? contentBlock.data : "",
1470
+ redacted: true,
1471
+ index
1472
+ };
1473
+ output.content.push(block);
1474
+ blockIndexes.set(index, output.content.length - 1);
1475
+ eventSink.push({
1476
+ type: "thinking_start",
1477
+ contentIndex: output.content.length - 1,
1478
+ partial: output
1479
+ });
1480
+ continue;
1481
+ }
1482
+ if (contentBlock?.type === "tool_use") {
1483
+ if (managed) tagPendingCommentaryText(output.content);
1484
+ flushPendingTextEnds();
1485
+ const block = {
1486
+ type: "toolCall",
1487
+ id: typeof contentBlock.id === "string" ? contentBlock.id : "",
1488
+ name: typeof contentBlock.name === "string" ? isOAuthToken ? resolveOriginalAnthropicToolName(contentBlock.name, toolProjection) : contentBlock.name : "",
1489
+ arguments: asRecord(contentBlock.input),
1490
+ partialJson: "",
1491
+ index
1492
+ };
1493
+ output.content.push(block);
1494
+ blockIndexes.set(index, output.content.length - 1);
1495
+ seededToolArguments.set(block, managed ? block.arguments : contentBlock.input ?? {});
1496
+ toolArgumentPreviewSchedules.set(block, createToolArgumentPreviewSchedule());
1497
+ eventSink.push({
1498
+ type: "toolcall_start",
1499
+ contentIndex: output.content.length - 1,
1500
+ partial: output
1501
+ });
1502
+ }
1503
+ continue;
1504
+ }
1505
+ if (event.type === "content_block_delta") {
1506
+ const delta = asOptionalObjectRecord(event.delta);
1507
+ const eventIndex = typeof event.index === "number" ? event.index : void 0;
1508
+ if (eventIndex !== void 0 && compactionCapture.delta(eventIndex, delta)) continue;
1509
+ let index = eventIndex === void 0 ? void 0 : blockIndexes.get(eventIndex);
1510
+ let block = index === void 0 ? void 0 : blocks[index];
1511
+ if (allowReasoningContentReplay) {
1512
+ const appendedThinking = appendReasoningContentThinkingDelta(event.index, delta?.reasoning_content);
1513
+ 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";
1514
+ let appendedContent = false;
1515
+ if (!hasNativeAnthropicDelta && typeof delta?.content === "string" && delta.content.length > 0) {
1516
+ const text = sanitizeTransportPayloadText(delta.content);
1517
+ if (text.length > 0) {
1518
+ if (block?.type === "text" && index !== void 0) {
1519
+ block.text += text;
1520
+ eventSink.push({
1521
+ type: "text_delta",
1522
+ contentIndex: index,
1523
+ delta: text,
1524
+ partial: output
1525
+ });
1526
+ appendedContent = true;
1527
+ } else appendedContent = appendReasoningContentTextDelta(event.index, text);
1528
+ }
1529
+ }
1530
+ if ((appendedThinking || appendedContent) && !hasNativeAnthropicDelta) continue;
1531
+ }
1532
+ if (managed && !block && delta?.type === "text_delta" && typeof delta.text === "string") {
1533
+ block = {
1534
+ type: "text",
1535
+ text: "",
1536
+ index: typeof event.index === "number" ? event.index : blocks.length
1537
+ };
1538
+ output.content.push(block);
1539
+ index = output.content.length - 1;
1540
+ if (typeof event.index === "number") blockIndexes.set(event.index, index);
1541
+ eventSink.push({
1542
+ type: "text_start",
1543
+ contentIndex: index,
1544
+ partial: output
1545
+ });
1546
+ }
1547
+ if (index === void 0) continue;
1548
+ if (block?.type === "text" && delta?.type === "text_delta" && typeof delta.text === "string") {
1549
+ block.text += delta.text;
1550
+ eventSink.push({
1551
+ type: "text_delta",
1552
+ contentIndex: index,
1553
+ delta: delta.text,
1554
+ partial: output
1555
+ });
1556
+ continue;
1557
+ }
1558
+ if (block?.type === "thinking" && delta?.type === "thinking_delta" && typeof delta.thinking === "string") {
1559
+ appendAssistantThinking(block, delta.thinking);
1560
+ eventSink.push({
1561
+ type: "thinking_delta",
1562
+ contentIndex: index,
1563
+ delta: delta.thinking,
1564
+ partial: output
1565
+ });
1566
+ continue;
1567
+ }
1568
+ if (block?.type === "toolCall" && delta?.type === "input_json_delta" && typeof delta.partial_json === "string") {
1569
+ const partialJson = `${block.partialJson ?? ""}${delta.partial_json}`;
1570
+ block.partialJson = partialJson;
1571
+ if (toolArgumentPreviewSchedules.get(block)?.(partialJson.length)) block.arguments = managed ? coerceTransportToolCallArguments(parseJsonObjectPreservingUnsafeIntegers(partialJson) ?? parseStreamingJson(partialJson)) : parseStreamingJson(partialJson);
1572
+ eventSink.push({
1573
+ type: "toolcall_delta",
1574
+ contentIndex: index,
1575
+ delta: delta.partial_json,
1576
+ partial: output
1577
+ });
1578
+ continue;
1579
+ }
1580
+ if (block?.type === "thinking" && delta?.type === "signature_delta" && typeof delta.signature === "string") {
1581
+ const signatureIndex = eventIndexKey(event.index);
1582
+ const pendingSignature = pendingThinkingSignatures.get(signatureIndex);
1583
+ if (pendingSignature === void 0) {
1584
+ block.thinkingSignature = "";
1585
+ pendingThinkingSignatures.set(signatureIndex, delta.signature);
1586
+ } else pendingThinkingSignatures.set(signatureIndex, pendingSignature + delta.signature);
1587
+ }
1588
+ continue;
1589
+ }
1590
+ if (event.type === "content_block_stop") {
1591
+ const eventIndex = typeof event.index === "number" ? event.index : void 0;
1592
+ if (eventIndex !== void 0 && compactionCapture.complete(eventIndex)) continue;
1593
+ const pendingSignature = eventIndex === void 0 ? void 0 : pendingThinkingSignatures.get(eventIndex);
1594
+ if (eventIndex !== void 0) pendingThinkingSignatures.delete(eventIndex);
1595
+ const index = eventIndex === void 0 ? void 0 : blockIndexes.get(eventIndex);
1596
+ const block = index === void 0 ? void 0 : blocks[index];
1597
+ if (eventIndex === void 0 || index === void 0 || !block) {
1598
+ finishReasoningContentSidecars(event.index);
1599
+ continue;
1600
+ }
1601
+ blockIndexes.delete(eventIndex);
1602
+ delete block.index;
1603
+ if (block.type === "text") {
1604
+ emitTextEnd({
1605
+ type: "text_end",
1606
+ contentIndex: index,
1607
+ content: block.text,
1608
+ partial: output
1609
+ });
1610
+ finishReasoningContentSidecars(event.index);
1611
+ continue;
1612
+ }
1613
+ if (block.type === "thinking") {
1614
+ if (pendingSignature !== void 0) block.thinkingSignature = pendingSignature;
1615
+ eventSink.push({
1616
+ type: "thinking_end",
1617
+ contentIndex: index,
1618
+ content: block.thinking,
1619
+ partial: output
1620
+ });
1621
+ finishReasoningContentSidecars(event.index);
1622
+ continue;
1623
+ }
1624
+ if (block.type === "toolCall") {
1625
+ sealedToolCalls.push({
1626
+ block,
1627
+ contentIndex: index
1628
+ });
1629
+ finishReasoningContentSidecars(event.index);
1630
+ }
1631
+ continue;
1632
+ }
1633
+ if (event.type === "message_delta") {
1634
+ logAnthropicContextEdits(event);
1635
+ const delta = asOptionalObjectRecord(event.delta);
1636
+ const usage = asOptionalObjectRecord(event.usage);
1637
+ if (typeof delta?.stop_reason === "string" && delta.stop_reason) {
1638
+ if (delta.stop_reason === "refusal") applyAnthropicRefusal(output, delta.stop_details, model.provider);
1639
+ else output.stopReason = mapAnthropicStopReason(delta.stop_reason);
1640
+ }
1641
+ applyAnthropicMessageDeltaUsage(output.usage, usage, messageStartPromptUsage);
1642
+ calculateCost(costModel, output.usage);
1643
+ if (managed && (output.stopReason === "toolUse" || output.content.some((block) => block.type === "toolCall"))) tagPendingCommentaryText(output.content);
1644
+ flushPendingTextEnds();
1645
+ }
1646
+ }
1647
+ if ((isDirectAnthropicModel(model) || !managed && refusalBuffer) && !sawMessageStop) throw new Error("Anthropic stream ended before message_stop");
1648
+ if (options.signal?.aborted) throw transportAbortError(options.signal);
1649
+ if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
1650
+ if ([...blockIndexes.values()].some((index) => blocks[index]?.type === "toolCall")) throw new Error("Provider completed stream with an incomplete tool call");
1651
+ finalizeTerminalToolCallArguments(sealedToolCalls.map(({ block }) => block), (block) => block.partialJson && block.partialJson.length > 0 ? block.partialJson : seededToolArguments.get(block));
1652
+ for (const sealed of sealedToolCalls) {
1653
+ delete sealed.block.partialJson;
1654
+ eventSink.push({
1655
+ type: "toolcall_end",
1656
+ contentIndex: sealed.contentIndex,
1657
+ toolCall: sealed.block,
1658
+ partial: output
1659
+ });
1660
+ }
1661
+ refusalBuffer?.flush();
1662
+ if (managed && (output.stopReason === "toolUse" || output.content.some((block) => block.type === "toolCall"))) tagPendingCommentaryText(output.content);
1663
+ flushPendingTextEnds();
1664
+ } finally {
1665
+ logAnthropicThinkingDrops(inputTransformations);
1666
+ }
1667
+ }
1668
+ //#endregion
1669
+ export { applyAnthropicFallbackBoundary as A, logAnthropicContextEdits as B, applyAnthropicThinkingBindingControls as C, ANTHROPIC_SERVER_SIDE_FALLBACKS as D, readAnthropicInputTransformations as E, applyAnthropicPayloadPolicyToParams as F, resolveAnthropicServerCompactionPlan as G, resolveAnthropicContextManagementBetaHeader as H, applyAnthropicRequestCacheControl as I, usesFoundryBearerAuth as J, isAnthropicOAuthApiKey as K, buildAnthropicSystemBlocks as L, resolveAnthropicFallbackServingModelCost as M, applyAnthropicContextManagementToRequest as N, ANTHROPIC_SERVER_SIDE_FALLBACK_BETA as O, applyAnthropicEphemeralCacheControlMarkers as P, isAnthropicServerToolClearingEnabled as R, ANTHROPIC_OMITTED_REASONING_TEXT as S, logAnthropicThinkingDrops as T, resolveAnthropicEphemeralCacheControl as U, resolveAnthropicCacheOptions as V, resolveAnthropicPayloadPolicy as W, normalizeAnthropicToolChoice as _, readAnthropicPromptUsageSnapshot as a, resolveOriginalAnthropicToolName as b, applyAnthropicRefusal as c, convertAnthropicTools as d, buildAnthropicReplayPlan as f, normalizeAnthropicToolCallId as g, suppressAnthropicCompaction as h, readAnthropicCacheWriteUsage as i, readAnthropicFallbackBoundary as j, CLAUDE_OPUS_FALLBACK_MODEL_COST as k, buildAnthropicGenerationParams as l, resolveNewestAnthropicCompaction as m, applyAnthropicMessageDeltaUsage as n, readAnthropicUsageTokenCount as o, isAnthropicReplayRejection as p, omitFoundryBearerCredentialHeaders as q, applyAnthropicMessageStartUsage as r, readLastAnthropicIterationUsage as s, consumeAnthropicStream as t, convertAnthropicMessages as u, projectAnthropicTools as v, findActiveAnthropicToolTurnAssistantIndex as w, toClaudeCodeToolName as x, reconcileAnthropicToolChoice as y, isDirectAnthropicModel as z };