@openclaw/ai 2026.7.2-beta.5 → 2026.7.2-beta.7

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 (47) hide show
  1. package/dist/{anthropic-CQVj3le6.mjs → anthropic-CH4UUnZr.mjs} +14 -463
  2. package/dist/anthropic-usage-DWU-x8MI.mjs +459 -0
  3. package/dist/{azure-openai-responses-DIYgsqFM.mjs → azure-openai-responses-CImcwB83.mjs} +4 -3
  4. package/dist/azure-openai-responses-client-compat-C7K7QfUE.mjs +62 -0
  5. package/dist/cache-retention-0x979a5V.mjs +12 -0
  6. package/dist/deferred-event-buffer-DAvyP7qA.mjs +19 -0
  7. package/dist/github-copilot-headers-NCJtz9i0.mjs +37 -0
  8. package/dist/{google-f-A8xrae.mjs → google-CtSg0iTS.mjs} +3 -3
  9. package/dist/{google-shared-J6qvYINH.mjs → google-shared-DNBz5rcD.mjs} +5 -3
  10. package/dist/{google-vertex-D3yMVXIY.mjs → google-vertex-31f1uS9L.mjs} +3 -3
  11. package/dist/host-Dog2WQiR.mjs +369 -0
  12. package/dist/index.mjs +1 -1
  13. package/dist/internal/anthropic.d.mts +3 -53
  14. package/dist/internal/anthropic.mjs +3 -2
  15. package/dist/internal/openai.d.mts +259 -2
  16. package/dist/internal/openai.mjs +8 -4
  17. package/dist/internal/runtime.mjs +6 -4
  18. package/dist/internal/shared.d.mts +1 -1
  19. package/dist/internal/shared.mjs +5 -1
  20. package/dist/{llm-request-activity-CehVkZP-.mjs → llm-request-activity-BjtkplhG.mjs} +1 -19
  21. package/dist/{mistral-CKV-TOQj.mjs → mistral-CWmpvWYh.mjs} +5 -3
  22. package/dist/{openai-chatgpt-responses-CedIj0hk.mjs → openai-chatgpt-responses-B84Ibtrd.mjs} +18 -13
  23. package/dist/openai-completions-DsOxhOD1.mjs +630 -0
  24. package/dist/openai-completions-compat-DBWjXoMZ.d.mts +43 -0
  25. package/dist/openai-reasoning-compat-YgeLncHw.mjs +396 -0
  26. package/dist/openai-responses-BT7A3sLu.mjs +138 -0
  27. package/dist/openai-responses-shared-pXl6Wd8S.mjs +392 -0
  28. package/dist/{openai-D3PD6PE-.mjs → openai-responses-stream-internal-Cw5txaGW.mjs} +1409 -1863
  29. package/dist/openai-tool-projection-OhX64DoP.mjs +215 -0
  30. package/dist/{provider-error-apVOZI6G.mjs → provider-error-CAEvRjry.mjs} +1 -1
  31. package/dist/provider-options-D8bB3z9b.d.mts +144 -0
  32. package/dist/providers.mjs +8 -8
  33. package/dist/{stream-first-event-timeout-C3OgBjIk.mjs → reasoning-tag-text-partitioner-CGDyLWUR.mjs} +1 -86
  34. package/dist/simple-options-9lhRrN73.mjs +50 -0
  35. package/dist/stream-first-event-timeout-BBys9hSb.mjs +86 -0
  36. package/dist/tls-certificate-errors-DXSpluKI.mjs +93 -0
  37. package/dist/tool-result-text-CTpIRbYd.mjs +225 -0
  38. package/dist/{github-copilot-headers-BCoBNmL7.mjs → tool-schema-json-projection-BwNu3nDi.mjs} +1 -48
  39. package/dist/transform-messages-C8mBqZxF.mjs +2 -0
  40. package/dist/{transport-stream-shared-BbMELSI4.mjs → transport-stream-shared-D81p90xq.mjs} +4 -4
  41. package/dist/transports.d.mts +13 -33
  42. package/dist/transports.mjs +75 -34
  43. package/package.json +4 -4
  44. package/dist/host-XYGZcgO8.mjs +0 -98
  45. package/dist/openai-BPor_3WI.d.mts +0 -358
  46. package/dist/openai-completions-CiSutyu0.mjs +0 -1223
  47. package/dist/shared-CdjNZd35.mjs +0 -634
@@ -1,472 +1,23 @@
1
1
  import { n as getEnvApiKey, r as __exportAll } from "./env-api-keys-DrgeBuva.mjs";
2
- import { d as resolveClaudeSonnet5ModelIdentity, g as supportsClaudeNativeXhighEffort, h as supportsClaudeNativeMaxEffort, l as resolveClaudeNativeThinkingLevelMap, o as resolveClaudeFable5ModelIdentity, p as supportsClaudeAdaptiveThinking, s as resolveClaudeModelIdentity, u as resolveClaudeOpus5ModelIdentity } from "./src-QkygScBs.mjs";
2
+ import { d as resolveClaudeSonnet5ModelIdentity, g as supportsClaudeNativeXhighEffort, h as supportsClaudeNativeMaxEffort, l as resolveClaudeNativeThinkingLevelMap, p as supportsClaudeAdaptiveThinking, u as resolveClaudeOpus5ModelIdentity } from "./src-QkygScBs.mjs";
3
3
  import { t as AssistantMessageEventStream } from "./event-stream-D8n2uFee.mjs";
4
- import { n as getAiTransportHost, r as resolveAiTransportHeaderSentinels } from "./host-XYGZcgO8.mjs";
5
- import { A as buildBaseOptions, C as extractToolResultBlockText, E as isImageWithMediaPayload, O as isRecord, S as describeToolResultMediaPlaceholder, _ as usesClaudeStreamingRefusalContract, a as splitSystemPromptCacheBoundary, d as applyClaudeRequestContract, g as usesClaudeFable5MessagesContract, j as clampMaxTokensToModel, k as adjustMaxTokensForThinking, l as sortPromptCacheToolsByName, m as requiresClaudeAdaptiveThinking, o as stripSystemPromptCacheBoundary, p as prepareClaudeNoPrefillRequestContext, u as transformMessages, w as extractToolResultText } from "./shared-CdjNZd35.mjs";
4
+ import { a as applyClaudeRequestContract, c as requiresClaudeAdaptiveThinking, d as usesClaudeStreamingRefusalContract, i as transformMessages, n as getAiTransportHost, r as resolveAiTransportHeaderSentinels, s as prepareClaudeNoPrefillRequestContext, u as usesClaudeFable5MessagesContract } from "./host-Dog2WQiR.mjs";
5
+ import { t as resolveCacheRetention } from "./cache-retention-0x979a5V.mjs";
6
6
  import { t as sanitizeSurrogates } from "./sanitize-unicode-DT5o51ur.mjs";
7
+ import { a as isImageWithMediaPayload, d as stripSystemPromptCacheBoundary, n as extractToolResultBlockText, r as extractToolResultText, t as describeToolResultMediaPlaceholder, u as splitSystemPromptCacheBoundary } from "./tool-result-text-CTpIRbYd.mjs";
8
+ import { _ as omitFoundryBearerCredentialHeaders, a as projectAnthropicTools, b as normalizeAnthropicInlineContent, c as ANTHROPIC_OMITTED_REASONING_TEXT, d as ANTHROPIC_SERVER_SIDE_FALLBACK_BETA, g as applyAnthropicRefusal, h as resolveAnthropicFallbackServingModelCost, i as readLastAnthropicIterationUsage, l as findActiveAnthropicToolTurnAssistantIndex, m as readAnthropicFallbackBoundary, n as readAnthropicPromptUsageSnapshot, o as reconcileAnthropicToolChoice, p as applyAnthropicFallbackBoundary, r as readAnthropicUsageTokenCount, s as resolveOriginalAnthropicToolName, t as readAnthropicCacheWriteUsage, u as ANTHROPIC_SERVER_SIDE_FALLBACKS, v as usesFoundryBearerAuth, x as resolveAnthropicImageMediaType, y as createAnthropicInlineImageBudget } from "./anthropic-usage-DWU-x8MI.mjs";
7
9
  import { c as calculateCost, l as clampThinkingLevel } from "./number-coercion-DvG7SNMg.mjs";
8
- import { d as transportAbortError } from "./transport-stream-shared-BbMELSI4.mjs";
9
- import { r as createDeferredEventBuffer, t as notifyLlmRequestActivity } from "./llm-request-activity-CehVkZP-.mjs";
10
- import { t as headersToRecord } from "./headers-B_e4-1J0.mjs";
10
+ import { t as createDeferredEventBuffer } from "./deferred-event-buffer-DAvyP7qA.mjs";
11
11
  import { n as parseStreamingJson, t as parseJsonWithRepair } from "./json-parse-BvXNt1-7.mjs";
12
- import { t as formatProviderError } from "./provider-error-apVOZI6G.mjs";
13
- import { a as resolveCacheRetention, i as resolveCloudflareBaseUrl, n as hasCopilotVisionInput, o as projectRuntimeToolInputSchema, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-BCoBNmL7.mjs";
12
+ import { t as notifyLlmRequestActivity } from "./llm-request-activity-BjtkplhG.mjs";
13
+ import { d as transportAbortError } from "./transport-stream-shared-D81p90xq.mjs";
14
+ import { t as headersToRecord } from "./headers-B_e4-1J0.mjs";
15
+ import { t as formatProviderError } from "./provider-error-CAEvRjry.mjs";
16
+ import { i as resolveCloudflareBaseUrl, n as hasCopilotVisionInput, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-NCJtz9i0.mjs";
17
+ import { n as buildBaseOptions, r as clampMaxTokensToModel, t as adjustMaxTokensForThinking } from "./simple-options-9lhRrN73.mjs";
18
+ import "./transform-messages-C8mBqZxF.mjs";
14
19
  import Anthropic from "@anthropic-ai/sdk";
15
20
  import { Stream } from "@anthropic-ai/sdk/core/streaming.js";
16
- //#region packages/media-core/src/base64.ts
17
- /** Estimates decoded bytes without allocating a cleaned copy of the base64 payload. */
18
- function estimateBase64DecodedBytes(base64) {
19
- let effectiveLen = 0;
20
- for (let i = 0; i < base64.length; i += 1) {
21
- if (base64.charCodeAt(i) <= 32) continue;
22
- effectiveLen += 1;
23
- }
24
- if (effectiveLen === 0) return 0;
25
- let padding = 0;
26
- let end = base64.length - 1;
27
- while (end >= 0 && base64.charCodeAt(end) <= 32) end -= 1;
28
- if (end >= 0 && base64[end] === "=") {
29
- padding = 1;
30
- end -= 1;
31
- while (end >= 0 && base64.charCodeAt(end) <= 32) end -= 1;
32
- if (end >= 0 && base64[end] === "=") padding = 2;
33
- }
34
- const estimated = Math.floor(effectiveLen * 3 / 4) - padding;
35
- return Math.max(0, estimated);
36
- }
37
- const CANONICALIZE_BASE64_CHUNK_SIZE = 8192;
38
- function isBase64DataChar(code) {
39
- return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 43 || code === 47;
40
- }
41
- function base64DataValue(code) {
42
- if (code >= 65 && code <= 90) return code - 65;
43
- if (code >= 97 && code <= 122) return code - 97 + 26;
44
- if (code >= 48 && code <= 57) return code - 48 + 52;
45
- return code === 43 ? 62 : 63;
46
- }
47
- /**
48
- * Normalizes and validates a base64 string, returning canonical no-whitespace
49
- * base64 only when the input has valid alphabet, padding, and length.
50
- */
51
- function canonicalizeBase64(base64) {
52
- const chunks = [];
53
- let current = "";
54
- let cleanedLength = 0;
55
- let padding = 0;
56
- let sawPadding = false;
57
- let lastDataCode = 0;
58
- const append = (char) => {
59
- current += char;
60
- cleanedLength += 1;
61
- if (current.length >= CANONICALIZE_BASE64_CHUNK_SIZE) {
62
- chunks.push(current);
63
- current = "";
64
- }
65
- };
66
- for (let i = 0; i < base64.length; i += 1) {
67
- const code = base64.charCodeAt(i);
68
- if (code <= 32) continue;
69
- if (code === 61) {
70
- padding += 1;
71
- if (padding > 2) return;
72
- sawPadding = true;
73
- append("=");
74
- continue;
75
- }
76
- if (sawPadding || !isBase64DataChar(code)) return;
77
- lastDataCode = code;
78
- append(base64[i] ?? "");
79
- }
80
- if (cleanedLength === 0) return;
81
- const remainder = cleanedLength % 4;
82
- if (remainder !== 0) {
83
- if (sawPadding || remainder === 1) return;
84
- current += "=".repeat(4 - remainder);
85
- }
86
- const effectivePadding = remainder === 0 ? padding : 4 - remainder;
87
- const padBitMask = effectivePadding === 2 ? 15 : effectivePadding === 1 ? 3 : 0;
88
- if (padBitMask !== 0 && (base64DataValue(lastDataCode) & padBitMask) !== 0) return;
89
- if (current) chunks.push(current);
90
- return chunks.join("");
91
- }
92
- //#endregion
93
- //#region packages/ai/src/internal/anthropic-inline-images.ts
94
- const ANTHROPIC_IMAGE_MEDIA_TYPE_SET = /* @__PURE__ */ new Set([
95
- "image/jpeg",
96
- "image/png",
97
- "image/gif",
98
- "image/webp"
99
- ]);
100
- const ANTHROPIC_INLINE_IMAGES_DECODE_SAFETY_BYTES = 64 * 1024 * 1024;
101
- function createAnthropicInlineImageBudget() {
102
- return { totalBytes: 0 };
103
- }
104
- function resolveAnthropicImageMediaType(value) {
105
- if (ANTHROPIC_IMAGE_MEDIA_TYPE_SET.has(value)) return value;
106
- throw new Error(`Unsupported Anthropic image media type after normalization: ${value}`);
107
- }
108
- async function normalizeAnthropicInlineContent(content, budget) {
109
- if (!content.some((block) => block.type === "image")) return content.filter((block) => block.type === "text");
110
- const inputBytes = content.reduce((total, block) => block.type === "image" ? total + estimateBase64DecodedBytes(block.data) : total, 0);
111
- if (budget.totalBytes + inputBytes > ANTHROPIC_INLINE_IMAGES_DECODE_SAFETY_BYTES) throw new Error("Anthropic inline images exceed the 64 MB aggregate decoded safety limit.");
112
- const normalized = [];
113
- for (const block of content) {
114
- if (block.type !== "image") {
115
- normalized.push(block);
116
- continue;
117
- }
118
- const normalizedBlocks = await getAiTransportHost().normalizeAnthropicInlineContentBlocks([block]);
119
- const outputBytes = normalizedBlocks.reduce((total, normalizedBlock) => normalizedBlock.type === "image" ? total + estimateBase64DecodedBytes(normalizedBlock.data) : total, 0);
120
- if (budget.totalBytes + outputBytes > ANTHROPIC_INLINE_IMAGES_DECODE_SAFETY_BYTES) throw new Error("Anthropic inline images exceed the 64 MB aggregate decoded safety limit.");
121
- budget.totalBytes += outputBytes;
122
- normalized.push(...normalizedBlocks);
123
- }
124
- return normalized;
125
- }
126
- //#endregion
127
- //#region packages/ai/src/providers/anthropic-auth-headers.ts
128
- function usesFoundryBearerAuth(model) {
129
- return model.provider === "microsoft-foundry" && (model.authHeader === true || hasBearerAuthorizationHeader(model.headers));
130
- }
131
- function hasBearerAuthorizationHeader(headers) {
132
- if (!headers) return false;
133
- return Object.entries(headers).some(([key, value]) => key.toLowerCase() === "authorization" && /^bearer\s+\S+/i.test(value.trim()));
134
- }
135
- function omitFoundryBearerCredentialHeaders(headers) {
136
- if (!headers) return;
137
- const next = {};
138
- for (const [key, value] of Object.entries(headers)) {
139
- const lower = key.toLowerCase();
140
- if (lower === "authorization" || lower === "x-api-key" || lower === "api-key") continue;
141
- next[key] = value;
142
- }
143
- return Object.keys(next).length > 0 ? next : void 0;
144
- }
145
- //#endregion
146
- //#region packages/ai/src/providers/anthropic-refusal.ts
147
- function readNullableString(value) {
148
- return typeof value === "string" && value.trim() ? value.trim() : null;
149
- }
150
- function readAnthropicRefusalDetails(value) {
151
- if (!value || typeof value !== "object") return {
152
- category: null,
153
- explanation: null
154
- };
155
- const details = value;
156
- return {
157
- category: readNullableString(details.category),
158
- explanation: readNullableString(details.explanation)
159
- };
160
- }
161
- function formatAnthropicRefusalMessage(details) {
162
- return `Anthropic refusal${details.category ? ` (category: ${details.category})` : ""}${details.explanation ? `: ${details.explanation}` : "."}`;
163
- }
164
- function applyAnthropicRefusal(output, stopDetails, provider) {
165
- const details = readAnthropicRefusalDetails(stopDetails);
166
- output.stopReason = "error";
167
- output.errorMessage = formatAnthropicRefusalMessage(details);
168
- output.diagnostics = [...output.diagnostics ?? [], {
169
- type: "provider_refusal",
170
- timestamp: Date.now(),
171
- details: {
172
- provider,
173
- category: details.category,
174
- explanation: details.explanation
175
- }
176
- }];
177
- }
178
- //#endregion
179
- //#region packages/ai/src/providers/anthropic-server-fallback.ts
180
- /** Anthropic beta that re-serves safety refusals on an allowed fallback model. */
181
- const ANTHROPIC_SERVER_SIDE_FALLBACK_BETA = "server-side-fallback-2026-07-01";
182
- /** Let Anthropic select the recommended model for each refusal category. */
183
- const ANTHROPIC_SERVER_SIDE_FALLBACKS = "default";
184
- const CLAUDE_OPUS_FALLBACK_MODEL_COST = {
185
- input: 5,
186
- output: 25,
187
- cacheRead: .5,
188
- cacheWrite: 6.25
189
- };
190
- function resolveFallbackModelIdentity(modelId) {
191
- if (!modelId?.trim()) return null;
192
- const ref = { id: modelId };
193
- const normalized = resolveClaudeModelIdentity(ref);
194
- if (normalized === "opus" || normalized === "opus-5" || resolveClaudeOpus5ModelIdentity(ref)) return "claude-opus-5";
195
- if (resolveClaudeFable5ModelIdentity(ref)) return "claude-fable-5";
196
- if (/^claude-opus-4-8(?=$|[^a-z0-9])/.test(normalized)) return "claude-opus-4-8";
197
- return normalized || null;
198
- }
199
- function isClaudeOpusFallbackModel(modelId) {
200
- return modelId === "claude-opus-5" || modelId === "claude-opus-4-8";
201
- }
202
- /** Resolve billed rates from the serving model reported by Anthropic's fallback stream. */
203
- function resolveAnthropicFallbackServingModelCost(params) {
204
- const requestedModelId = resolveFallbackModelIdentity(params.requestedModelId);
205
- const servingModelId = resolveFallbackModelIdentity(params.servingModelId);
206
- if (!servingModelId || servingModelId === requestedModelId || !isClaudeOpusFallbackModel(servingModelId)) return params.requestedCost;
207
- if (requestedModelId && isClaudeOpusFallbackModel(requestedModelId)) return params.requestedCost;
208
- return CLAUDE_OPUS_FALLBACK_MODEL_COST;
209
- }
210
- function readBoundaryModel(value) {
211
- if (!value || typeof value !== "object") return null;
212
- const model = value.model;
213
- return typeof model === "string" && model.trim() ? model : null;
214
- }
215
- /** Reads a `fallback` content block marking where one model's output gives way to the next. */
216
- function readAnthropicFallbackBoundary(block) {
217
- if (!block || typeof block !== "object") return null;
218
- const record = block;
219
- if (record.type !== "fallback") return null;
220
- return {
221
- fromModel: readBoundaryModel(record.from),
222
- toModel: readBoundaryModel(record.to)
223
- };
224
- }
225
- /**
226
- * Drops pre-fallback thinking/tool calls while preserving the text prefix that
227
- * the serving model continued. Dropped tool calls must never execute or replay.
228
- */
229
- function applyAnthropicFallbackBoundary(params) {
230
- const { output, boundary } = params;
231
- const survivors = output.content.filter((block) => block.type === "text");
232
- for (const survivor of survivors) delete survivor.textSignature;
233
- output.content.splice(0, output.content.length, ...survivors);
234
- if (boundary.toModel) output.responseModel = boundary.toModel;
235
- output.diagnostics = [...output.diagnostics ?? [], {
236
- type: "provider_fallback",
237
- timestamp: Date.now(),
238
- details: {
239
- provider: params.provider,
240
- fromModel: boundary.fromModel,
241
- toModel: boundary.toModel
242
- }
243
- }];
244
- }
245
- //#endregion
246
- //#region packages/ai/src/providers/anthropic-thinking-replay.ts
247
- const ANTHROPIC_OMITTED_REASONING_TEXT = "[assistant reasoning omitted]";
248
- function asReplayMessage(value) {
249
- return value && typeof value === "object" ? value : void 0;
250
- }
251
- /**
252
- * Anthropic tool results continue the preceding assistant turn. Preserve that
253
- * turn's signed thinking even when the next request disables new thinking.
254
- */
255
- function findActiveAnthropicToolTurnAssistantIndex(messages) {
256
- const toolResultIds = /* @__PURE__ */ new Set();
257
- let index = messages.length - 1;
258
- while (index >= 0) {
259
- const message = asReplayMessage(messages[index]);
260
- if (message?.role !== "toolResult") break;
261
- if (typeof message.toolCallId === "string") toolResultIds.add(message.toolCallId);
262
- index -= 1;
263
- }
264
- if (toolResultIds.size === 0) return -1;
265
- const assistant = asReplayMessage(messages[index]);
266
- if (assistant?.role !== "assistant" || !Array.isArray(assistant.content)) return -1;
267
- const toolCallIds = /* @__PURE__ */ new Set();
268
- for (const block of assistant.content) {
269
- if (!block || typeof block !== "object") continue;
270
- const record = block;
271
- if ((record.type === "toolCall" || record.type === "tool_use" || record.type === "function_call") && typeof record.id === "string") toolCallIds.add(record.id);
272
- }
273
- return [...toolResultIds].every((toolCallId) => toolCallIds.has(toolCallId)) ? index : -1;
274
- }
275
- //#endregion
276
- //#region packages/ai/src/providers/anthropic-tool-projection.ts
277
- function isProviderSupportedViolation(violation) {
278
- return violation.endsWith(".$dynamicRef") || violation.endsWith(".$dynamicAnchor");
279
- }
280
- const schemaValueKeywords = /* @__PURE__ */ new Set([
281
- "additionalProperties",
282
- "contains",
283
- "contentSchema",
284
- "else",
285
- "if",
286
- "items",
287
- "not",
288
- "propertyNames",
289
- "then",
290
- "unevaluatedItems",
291
- "unevaluatedProperties"
292
- ]);
293
- const schemaArrayKeywords = /* @__PURE__ */ new Set([
294
- "allOf",
295
- "anyOf",
296
- "oneOf",
297
- "prefixItems"
298
- ]);
299
- const schemaMapKeywords = /* @__PURE__ */ new Set([
300
- "$defs",
301
- "definitions",
302
- "dependencies",
303
- "dependentSchemas",
304
- "patternProperties",
305
- "properties"
306
- ]);
307
- function normalizeAnthropicJsonSchema(schema) {
308
- if (!isRecord(schema)) return schema;
309
- let changed = false;
310
- const normalized = { ...schema };
311
- for (const [key, value] of Object.entries(schema)) {
312
- if (schemaValueKeywords.has(key) && !Array.isArray(value)) {
313
- const next = normalizeAnthropicJsonSchema(value);
314
- normalized[key] = next;
315
- changed ||= next !== value;
316
- continue;
317
- }
318
- if (schemaArrayKeywords.has(key) && Array.isArray(value)) {
319
- const next = value.map(normalizeAnthropicJsonSchema);
320
- normalized[key] = next;
321
- changed ||= next.some((entry, index) => entry !== value[index]);
322
- continue;
323
- }
324
- if (schemaMapKeywords.has(key) && isRecord(value)) {
325
- const next = Object.fromEntries(Object.entries(value).map(([entryKey, entryValue]) => [entryKey, normalizeAnthropicJsonSchema(entryValue)]));
326
- normalized[key] = next;
327
- changed ||= Object.entries(value).some(([entryKey, entryValue]) => next[entryKey] !== entryValue);
328
- }
329
- }
330
- if (Array.isArray(schema.items)) {
331
- normalized.prefixItems = schema.items.map(normalizeAnthropicJsonSchema);
332
- const additionalItems = schema.additionalItems;
333
- if (typeof additionalItems === "boolean" || isRecord(additionalItems)) normalized.items = normalizeAnthropicJsonSchema(additionalItems);
334
- else delete normalized.items;
335
- delete normalized.additionalItems;
336
- changed = true;
337
- }
338
- return changed ? normalized : schema;
339
- }
340
- /** Snapshots direct/custom tool descriptors before Anthropic payload construction. */
341
- function projectAnthropicTools(tools, toWireName) {
342
- const projectedTools = [];
343
- const unavailableOriginalNames = /* @__PURE__ */ new Set();
344
- for (const tool of tools) {
345
- let projectedTool;
346
- let originalName;
347
- try {
348
- const name = tool.name;
349
- originalName = name;
350
- if (!name) continue;
351
- const schemaProjection = projectRuntimeToolInputSchema(tool.parameters, `${name}.parameters`);
352
- if (!isRecord(schemaProjection.schema) || schemaProjection.violations.some((violation) => !isProviderSupportedViolation(violation))) {
353
- unavailableOriginalNames.add(name);
354
- continue;
355
- }
356
- const anthropicSchema = normalizeAnthropicJsonSchema(schemaProjection.schema);
357
- if (!isRecord(anthropicSchema)) {
358
- unavailableOriginalNames.add(name);
359
- continue;
360
- }
361
- const properties = anthropicSchema.properties;
362
- const required = anthropicSchema.required;
363
- if (properties !== void 0 && properties !== null && !isRecord(properties) || required !== void 0 && required !== null && (!Array.isArray(required) || required.some((entry) => typeof entry !== "string"))) {
364
- unavailableOriginalNames.add(name);
365
- continue;
366
- }
367
- let description;
368
- try {
369
- description = typeof tool.description === "string" ? tool.description : void 0;
370
- } catch {}
371
- projectedTool = {
372
- originalName: name,
373
- wireName: toWireName(name),
374
- ...description ? { description } : {},
375
- inputSchema: {
376
- type: "object",
377
- properties: properties ?? {},
378
- required: required ?? []
379
- }
380
- };
381
- } catch {
382
- if (originalName) unavailableOriginalNames.add(originalName);
383
- continue;
384
- }
385
- const conflictingTool = projectedTools.find((entry) => entry.wireName === projectedTool.wireName);
386
- if (conflictingTool && conflictingTool.originalName !== projectedTool.originalName) throw new Error(`Anthropic tool names "${conflictingTool.originalName}" and "${projectedTool.originalName}" both map to "${projectedTool.wireName}"`);
387
- projectedTools.push(projectedTool);
388
- }
389
- return {
390
- inputToolCount: tools.length,
391
- unavailableOriginalNames,
392
- tools: sortPromptCacheToolsByName(projectedTools)
393
- };
394
- }
395
- /** Keeps forced Anthropic tool choices aligned with the projected wire names. */
396
- function reconcileAnthropicToolChoice(choice, projection) {
397
- if (projection.inputToolCount === 0) return choice;
398
- if (choice.type === "tool") {
399
- const requestedName = choice.name;
400
- const originalMatch = projection.tools.find((tool) => tool.originalName === requestedName);
401
- if (originalMatch) return {
402
- ...choice,
403
- name: originalMatch.wireName
404
- };
405
- if (projection.unavailableOriginalNames.has(requestedName)) throw new Error(`Anthropic tool_choice requested unavailable tool "${requestedName}" after schema conversion`);
406
- const matchedTool = projection.tools.find((tool) => tool.wireName === requestedName);
407
- if (!matchedTool) throw new Error(`Anthropic tool_choice requested unavailable tool "${requestedName}" after schema conversion`);
408
- return {
409
- ...choice,
410
- name: matchedTool.wireName
411
- };
412
- }
413
- if (projection.tools.length === 0) {
414
- if (choice.type === "auto") return;
415
- if (choice.type === "any") throw new Error("Anthropic tool_choice requires a tool, but no tools survived schema conversion");
416
- }
417
- return choice;
418
- }
419
- /** Maps Claude Code wire names without trusting every direct/custom descriptor. */
420
- function resolveOriginalAnthropicToolName(name, projection) {
421
- return projection?.tools.find((tool) => tool.wireName === name)?.originalName ?? name;
422
- }
423
- //#endregion
424
- //#region packages/ai/src/providers/anthropic-usage.ts
425
- function readAnthropicUsageTokenCount(value) {
426
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
427
- }
428
- function readAnthropicCacheWriteUsage(usage) {
429
- if (!usage.cache_creation || typeof usage.cache_creation !== "object") return {};
430
- const cacheCreation = usage.cache_creation;
431
- const cacheWrite5m = readAnthropicUsageTokenCount(cacheCreation.ephemeral_5m_input_tokens);
432
- const cacheWrite1h = readAnthropicUsageTokenCount(cacheCreation.ephemeral_1h_input_tokens);
433
- return {
434
- ...cacheWrite5m !== void 0 ? { cacheWrite5m } : {},
435
- ...cacheWrite1h !== void 0 ? { cacheWrite1h } : {}
436
- };
437
- }
438
- function readAnthropicPromptUsageSnapshot(usage) {
439
- const input = readAnthropicUsageTokenCount(usage.input_tokens);
440
- const cacheRead = usage.cache_read_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_read_input_tokens);
441
- const cacheWrite = usage.cache_creation_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_creation_input_tokens);
442
- if (input === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
443
- return {
444
- input,
445
- cacheRead,
446
- cacheWrite
447
- };
448
- }
449
- function readLastAnthropicIterationUsage(usage) {
450
- if (usage.iterations == null) return { state: "absent" };
451
- if (!Array.isArray(usage.iterations) || usage.iterations.length === 0) return { state: "invalid" };
452
- const iteration = usage.iterations.at(-1);
453
- if (!iteration || typeof iteration !== "object" || Array.isArray(iteration)) return { state: "invalid" };
454
- const record = iteration;
455
- const input = readAnthropicUsageTokenCount(record.input_tokens);
456
- const cacheRead = readAnthropicUsageTokenCount(record.cache_read_input_tokens);
457
- const cacheWrite = readAnthropicUsageTokenCount(record.cache_creation_input_tokens);
458
- const outputTokens = readAnthropicUsageTokenCount(record.output_tokens);
459
- if (input === void 0 || cacheRead === void 0 || cacheWrite === void 0 || outputTokens === void 0) return { state: "invalid" };
460
- const contextPromptTokens = input + cacheRead + cacheWrite;
461
- return {
462
- state: "valid",
463
- usage: {
464
- contextPromptTokens,
465
- totalTokens: contextPromptTokens + outputTokens
466
- }
467
- };
468
- }
469
- //#endregion
470
21
  //#region packages/ai/src/providers/anthropic.ts
471
22
  var anthropic_exports = /* @__PURE__ */ __exportAll({
472
23
  streamAnthropic: () => streamAnthropic,
@@ -1462,4 +1013,4 @@ function mapStopReason(reason) {
1462
1013
  }
1463
1014
  }
1464
1015
  //#endregion
1465
- export { normalizeAnthropicInlineContent as C, createAnthropicInlineImageBudget as S, canonicalizeBase64 as T, readAnthropicFallbackBoundary as _, readAnthropicPromptUsageSnapshot as a, omitFoundryBearerCredentialHeaders as b, projectAnthropicTools as c, ANTHROPIC_OMITTED_REASONING_TEXT as d, findActiveAnthropicToolTurnAssistantIndex as f, applyAnthropicFallbackBoundary as g, CLAUDE_OPUS_FALLBACK_MODEL_COST as h, readAnthropicCacheWriteUsage as i, reconcileAnthropicToolChoice as l, ANTHROPIC_SERVER_SIDE_FALLBACK_BETA as m, streamAnthropic as n, readAnthropicUsageTokenCount as o, ANTHROPIC_SERVER_SIDE_FALLBACKS as p, streamSimpleAnthropic as r, readLastAnthropicIterationUsage as s, anthropic_exports as t, resolveOriginalAnthropicToolName as u, resolveAnthropicFallbackServingModelCost as v, resolveAnthropicImageMediaType as w, usesFoundryBearerAuth as x, applyAnthropicRefusal as y };
1016
+ export { streamAnthropic as n, streamSimpleAnthropic as r, anthropic_exports as t };