@openclaw/ai 2026.7.2-beta.4 → 2026.7.2-beta.6

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 (68) hide show
  1. package/dist/{anthropic-CrUDIBpM.mjs → anthropic-CH4UUnZr.mjs} +26 -441
  2. package/dist/{anthropic-BoTnz8cv.d.mts → anthropic-SrGtwsJu.d.mts} +27 -1
  3. package/dist/anthropic-usage-DWU-x8MI.mjs +459 -0
  4. package/dist/{api-registry-BMphkFf1.d.mts → api-registry-DlMgPR39.d.mts} +1 -1
  5. package/dist/{azure-openai-responses-CbrpVeEv.mjs → azure-openai-responses-CImcwB83.mjs} +4 -4
  6. package/dist/cache-retention-0x979a5V.mjs +12 -0
  7. package/dist/deferred-event-buffer-DAvyP7qA.mjs +19 -0
  8. package/dist/error-coercion-DgxlWC0n.mjs +15 -0
  9. package/dist/{event-stream-Douf9dob.d.mts → event-stream-YjaPW20U.d.mts} +1 -1
  10. package/dist/event-stream.d.mts +1 -1
  11. package/dist/{github-copilot-headers-BsH5cqGj.mjs → github-copilot-headers-NCJtz9i0.mjs} +1 -12
  12. package/dist/{google-Cs62KA7t.mjs → google-CtSg0iTS.mjs} +3 -3
  13. package/dist/{google-shared-CMLI-tCZ.mjs → google-shared-DNBz5rcD.mjs} +7 -4
  14. package/dist/{google-vertex-B4SD3U0f.mjs → google-vertex-31f1uS9L.mjs} +3 -3
  15. package/dist/{host-WvWBo4h8.d.mts → host-B9GUmcra.d.mts} +2 -2
  16. package/dist/host-Dog2WQiR.mjs +369 -0
  17. package/dist/index.d.mts +7 -7
  18. package/dist/index.mjs +3 -3
  19. package/dist/internal/anthropic.d.mts +16 -62
  20. package/dist/internal/anthropic.mjs +5 -4
  21. package/dist/internal/openai.d.mts +260 -2
  22. package/dist/internal/openai.mjs +7 -5
  23. package/dist/internal/runtime.d.mts +8 -32
  24. package/dist/internal/runtime.mjs +7 -6
  25. package/dist/internal/shared.d.mts +14 -9
  26. package/dist/internal/shared.mjs +6 -2
  27. package/dist/{llm-request-activity-CehVkZP-.mjs → llm-request-activity-BjtkplhG.mjs} +1 -19
  28. package/dist/{mistral-D5Ps7Led.mjs → mistral-CWmpvWYh.mjs} +7 -4
  29. package/dist/number-coercion-DvG7SNMg.mjs +129 -0
  30. package/dist/{openai-chatgpt-responses-h0o5yV8Y.mjs → openai-chatgpt-responses-B84Ibtrd.mjs} +33 -29
  31. package/dist/{openai-completions-exO8NFQf.mjs → openai-completions-DsOxhOD1.mjs} +28 -482
  32. package/dist/openai-completions-compat-DBWjXoMZ.d.mts +43 -0
  33. package/dist/openai-prompt-cache-2uo_1OR1.d.mts +7 -0
  34. package/dist/openai-prompt-cache-mZTCdRPo.mjs +12 -0
  35. package/dist/openai-reasoning-compat-YgeLncHw.mjs +396 -0
  36. package/dist/{openai-responses-BHpmtUKo.mjs → openai-responses-BT7A3sLu.mjs} +7 -5
  37. package/dist/openai-responses-shared-pXl6Wd8S.mjs +392 -0
  38. package/dist/{openai-responses-shared-CzCurmY1.mjs → openai-responses-stream-internal-Cw5txaGW.mjs} +1609 -1037
  39. package/dist/{openai-tool-projection-ITOU9bG1.mjs → openai-tool-projection-OhX64DoP.mjs} +26 -11
  40. package/dist/prompt-cache-stability-Cwcjv_fx.d.mts +13 -0
  41. package/dist/{provider-error-C4VvV_3t.mjs → provider-error-CAEvRjry.mjs} +8 -2
  42. package/dist/provider-options-D8bB3z9b.d.mts +144 -0
  43. package/dist/providers.d.mts +3 -2
  44. package/dist/providers.mjs +10 -9
  45. package/dist/reasoning-tag-text-partitioner-CGDyLWUR.mjs +12209 -0
  46. package/dist/simple-options-9lhRrN73.mjs +50 -0
  47. package/dist/{src-CXno1H5g.mjs → src-QkygScBs.mjs} +23 -4
  48. package/dist/stream-first-event-timeout-BBys9hSb.mjs +86 -0
  49. package/dist/stream-first-event-timeout-DvDeSucC.d.mts +29 -0
  50. package/dist/tls-certificate-errors-DXSpluKI.mjs +93 -0
  51. package/dist/tool-result-text-CTpIRbYd.mjs +225 -0
  52. package/dist/transform-messages-C8mBqZxF.mjs +2 -0
  53. package/dist/transport-stream-shared-D81p90xq.mjs +297 -0
  54. package/dist/transports.d.mts +115 -132
  55. package/dist/transports.mjs +400 -1991
  56. package/dist/{types-AFwwWium.d.mts → types-bzp5k29J.d.mts} +7 -0
  57. package/dist/types.d.mts +5 -5
  58. package/dist/types.mjs +2 -2
  59. package/dist/{validation-sxvxC8J-.d.mts → validation-B-j7cOYp.d.mts} +1 -1
  60. package/dist/validation.d.mts +1 -1
  61. package/package.json +4 -5
  62. package/dist/host-XYGZcgO8.mjs +0 -98
  63. package/dist/model-utils-1GiZ2_rr.mjs +0 -64
  64. package/dist/openai-CoGicoDt.d.mts +0 -332
  65. package/dist/reasoning-tag-text-partitioner-BlVe67g6.mjs +0 -400
  66. package/dist/stream-first-event-timeout-DP4xEyBY.mjs +0 -150
  67. package/dist/system-prompt-cache-boundary-CbHeV4_l.mjs +0 -526
  68. package/npm-shrinkwrap.json +0 -638
@@ -1,442 +1,23 @@
1
1
  import { n as getEnvApiKey, r as __exportAll } from "./env-api-keys-DrgeBuva.mjs";
2
- import { c as resolveClaudeNativeThinkingLevelMap, d as supportsClaudeNativeMaxEffort, f as supportsClaudeNativeXhighEffort, l as resolveClaudeSonnet5ModelIdentity, u as supportsClaudeAdaptiveThinking } from "./src-CXno1H5g.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 { C as isImageWithMediaPayload, D as buildBaseOptions, E as adjustMaxTokensForThinking, O as clampMaxTokensToModel, T as isRecord, a as stripSystemPromptCacheBoundary, b as extractToolResultBlockText, c as transformMessages, d as prepareClaudeSonnet5RequestContext, f as requiresClaudeAdaptiveThinking, h as usesClaudeStreamingRefusalContract, i as splitSystemPromptCacheBoundary, l as applyClaudeRequestContract, m as usesClaudeFable5MessagesContract, x as extractToolResultText, y as describeToolResultMediaPlaceholder } from "./system-prompt-cache-boundary-CbHeV4_l.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 { n as calculateCost, r as clampThinkingLevel } from "./model-utils-1GiZ2_rr.mjs";
8
- import { r as createDeferredEventBuffer, t as notifyLlmRequestActivity } from "./llm-request-activity-CehVkZP-.mjs";
9
- import { t as headersToRecord } from "./headers-B_e4-1J0.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";
9
+ import { c as calculateCost, l as clampThinkingLevel } from "./number-coercion-DvG7SNMg.mjs";
10
+ import { t as createDeferredEventBuffer } from "./deferred-event-buffer-DAvyP7qA.mjs";
10
11
  import { n as parseStreamingJson, t as parseJsonWithRepair } from "./json-parse-BvXNt1-7.mjs";
11
- import { t as projectRuntimeToolInputSchema } from "./tool-schema-json-projection-BwNu3nDi.mjs";
12
- import { a as resolveCacheRetention, i as resolveCloudflareBaseUrl, n as hasCopilotVisionInput, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-BsH5cqGj.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";
13
19
  import Anthropic from "@anthropic-ai/sdk";
14
20
  import { Stream } from "@anthropic-ai/sdk/core/streaming.js";
15
- //#region packages/media-core/src/base64.ts
16
- /** Estimates decoded bytes without allocating a cleaned copy of the base64 payload. */
17
- function estimateBase64DecodedBytes(base64) {
18
- let effectiveLen = 0;
19
- for (let i = 0; i < base64.length; i += 1) {
20
- if (base64.charCodeAt(i) <= 32) continue;
21
- effectiveLen += 1;
22
- }
23
- if (effectiveLen === 0) return 0;
24
- let padding = 0;
25
- let end = base64.length - 1;
26
- while (end >= 0 && base64.charCodeAt(end) <= 32) end -= 1;
27
- if (end >= 0 && base64[end] === "=") {
28
- padding = 1;
29
- end -= 1;
30
- while (end >= 0 && base64.charCodeAt(end) <= 32) end -= 1;
31
- if (end >= 0 && base64[end] === "=") padding = 2;
32
- }
33
- const estimated = Math.floor(effectiveLen * 3 / 4) - padding;
34
- return Math.max(0, estimated);
35
- }
36
- const CANONICALIZE_BASE64_CHUNK_SIZE = 8192;
37
- function isBase64DataChar(code) {
38
- return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 43 || code === 47;
39
- }
40
- /**
41
- * Normalizes and validates a base64 string, returning canonical no-whitespace
42
- * base64 only when the input has valid alphabet, padding, and length.
43
- */
44
- function canonicalizeBase64(base64) {
45
- const chunks = [];
46
- let current = "";
47
- let cleanedLength = 0;
48
- let padding = 0;
49
- let sawPadding = false;
50
- const append = (char) => {
51
- current += char;
52
- cleanedLength += 1;
53
- if (current.length >= CANONICALIZE_BASE64_CHUNK_SIZE) {
54
- chunks.push(current);
55
- current = "";
56
- }
57
- };
58
- for (let i = 0; i < base64.length; i += 1) {
59
- const code = base64.charCodeAt(i);
60
- if (code <= 32) continue;
61
- if (code === 61) {
62
- padding += 1;
63
- if (padding > 2) return;
64
- sawPadding = true;
65
- append("=");
66
- continue;
67
- }
68
- if (sawPadding || !isBase64DataChar(code)) return;
69
- append(base64[i] ?? "");
70
- }
71
- if (cleanedLength === 0) return;
72
- const remainder = cleanedLength % 4;
73
- if (remainder !== 0) {
74
- if (sawPadding || remainder === 1) return;
75
- current += "=".repeat(4 - remainder);
76
- }
77
- if (current) chunks.push(current);
78
- return chunks.join("");
79
- }
80
- //#endregion
81
- //#region packages/ai/src/internal/anthropic-inline-images.ts
82
- const ANTHROPIC_IMAGE_MEDIA_TYPE_SET = /* @__PURE__ */ new Set([
83
- "image/jpeg",
84
- "image/png",
85
- "image/gif",
86
- "image/webp"
87
- ]);
88
- const ANTHROPIC_INLINE_IMAGES_DECODE_SAFETY_BYTES = 64 * 1024 * 1024;
89
- function createAnthropicInlineImageBudget() {
90
- return { totalBytes: 0 };
91
- }
92
- function resolveAnthropicImageMediaType(value) {
93
- if (ANTHROPIC_IMAGE_MEDIA_TYPE_SET.has(value)) return value;
94
- throw new Error(`Unsupported Anthropic image media type after normalization: ${value}`);
95
- }
96
- async function normalizeAnthropicInlineContent(content, budget) {
97
- if (!content.some((block) => block.type === "image")) return content.filter((block) => block.type === "text");
98
- const inputBytes = content.reduce((total, block) => block.type === "image" ? total + estimateBase64DecodedBytes(block.data) : total, 0);
99
- if (budget.totalBytes + inputBytes > ANTHROPIC_INLINE_IMAGES_DECODE_SAFETY_BYTES) throw new Error("Anthropic inline images exceed the 64 MB aggregate decoded safety limit.");
100
- const normalized = [];
101
- for (const block of content) {
102
- if (block.type !== "image") {
103
- normalized.push(block);
104
- continue;
105
- }
106
- const normalizedBlocks = await getAiTransportHost().normalizeAnthropicInlineContentBlocks([block]);
107
- const outputBytes = normalizedBlocks.reduce((total, normalizedBlock) => normalizedBlock.type === "image" ? total + estimateBase64DecodedBytes(normalizedBlock.data) : total, 0);
108
- if (budget.totalBytes + outputBytes > ANTHROPIC_INLINE_IMAGES_DECODE_SAFETY_BYTES) throw new Error("Anthropic inline images exceed the 64 MB aggregate decoded safety limit.");
109
- budget.totalBytes += outputBytes;
110
- normalized.push(...normalizedBlocks);
111
- }
112
- return normalized;
113
- }
114
- //#endregion
115
- //#region packages/ai/src/providers/anthropic-auth-headers.ts
116
- function usesFoundryBearerAuth(model) {
117
- return model.provider === "microsoft-foundry" && (model.authHeader === true || hasBearerAuthorizationHeader(model.headers));
118
- }
119
- function hasBearerAuthorizationHeader(headers) {
120
- if (!headers) return false;
121
- return Object.entries(headers).some(([key, value]) => key.toLowerCase() === "authorization" && /^bearer\s+\S+/i.test(value.trim()));
122
- }
123
- function omitFoundryBearerCredentialHeaders(headers) {
124
- if (!headers) return;
125
- const next = {};
126
- for (const [key, value] of Object.entries(headers)) {
127
- const lower = key.toLowerCase();
128
- if (lower === "authorization" || lower === "x-api-key" || lower === "api-key") continue;
129
- next[key] = value;
130
- }
131
- return Object.keys(next).length > 0 ? next : void 0;
132
- }
133
- //#endregion
134
- //#region packages/ai/src/providers/anthropic-refusal.ts
135
- function readNullableString(value) {
136
- return typeof value === "string" && value.trim() ? value.trim() : null;
137
- }
138
- function readAnthropicRefusalDetails(value) {
139
- if (!value || typeof value !== "object") return {
140
- category: null,
141
- explanation: null
142
- };
143
- const details = value;
144
- return {
145
- category: readNullableString(details.category),
146
- explanation: readNullableString(details.explanation)
147
- };
148
- }
149
- function formatAnthropicRefusalMessage(details) {
150
- return `Anthropic refusal${details.category ? ` (category: ${details.category})` : ""}${details.explanation ? `: ${details.explanation}` : "."}`;
151
- }
152
- function applyAnthropicRefusal(output, stopDetails, provider) {
153
- const details = readAnthropicRefusalDetails(stopDetails);
154
- output.stopReason = "error";
155
- output.errorMessage = formatAnthropicRefusalMessage(details);
156
- output.diagnostics = [...output.diagnostics ?? [], {
157
- type: "provider_refusal",
158
- timestamp: Date.now(),
159
- details: {
160
- provider,
161
- category: details.category,
162
- explanation: details.explanation
163
- }
164
- }];
165
- }
166
- //#endregion
167
- //#region packages/ai/src/providers/anthropic-server-fallback.ts
168
- /** Anthropic beta that re-serves safety refusals on an allowed fallback model. */
169
- const ANTHROPIC_SERVER_SIDE_FALLBACK_BETA = "server-side-fallback-2026-06-01";
170
- const CLAUDE_FABLE_5_FALLBACK_MODEL = "claude-opus-4-8";
171
- const CLAUDE_FABLE_5_FALLBACK_MODEL_COST = {
172
- input: 5,
173
- output: 25,
174
- cacheRead: .5,
175
- cacheWrite: 6.25
176
- };
177
- function buildAnthropicServerSideFallbacks() {
178
- return [{ model: CLAUDE_FABLE_5_FALLBACK_MODEL }];
179
- }
180
- function readBoundaryModel(value) {
181
- if (!value || typeof value !== "object") return null;
182
- const model = value.model;
183
- return typeof model === "string" && model.trim() ? model : null;
184
- }
185
- /** Reads a `fallback` content block marking where one model's output gives way to the next. */
186
- function readAnthropicFallbackBoundary(block) {
187
- if (!block || typeof block !== "object") return null;
188
- const record = block;
189
- if (record.type !== "fallback") return null;
190
- return {
191
- fromModel: readBoundaryModel(record.from),
192
- toModel: readBoundaryModel(record.to)
193
- };
194
- }
195
- /**
196
- * Drops pre-fallback thinking/tool calls while preserving the text prefix that
197
- * the serving model continued. Dropped tool calls must never execute or replay.
198
- */
199
- function applyAnthropicFallbackBoundary(params) {
200
- const { output, boundary } = params;
201
- const survivors = output.content.filter((block) => block.type === "text");
202
- for (const survivor of survivors) delete survivor.textSignature;
203
- output.content.splice(0, output.content.length, ...survivors);
204
- if (boundary.toModel) output.responseModel = boundary.toModel;
205
- output.diagnostics = [...output.diagnostics ?? [], {
206
- type: "provider_fallback",
207
- timestamp: Date.now(),
208
- details: {
209
- provider: params.provider,
210
- fromModel: boundary.fromModel,
211
- toModel: boundary.toModel
212
- }
213
- }];
214
- }
215
- //#endregion
216
- //#region packages/ai/src/providers/anthropic-thinking-replay.ts
217
- const ANTHROPIC_OMITTED_REASONING_TEXT = "[assistant reasoning omitted]";
218
- function asReplayMessage(value) {
219
- return value && typeof value === "object" ? value : void 0;
220
- }
221
- /**
222
- * Anthropic tool results continue the preceding assistant turn. Preserve that
223
- * turn's signed thinking even when the next request disables new thinking.
224
- */
225
- function findActiveAnthropicToolTurnAssistantIndex(messages) {
226
- const toolResultIds = /* @__PURE__ */ new Set();
227
- let index = messages.length - 1;
228
- while (index >= 0) {
229
- const message = asReplayMessage(messages[index]);
230
- if (message?.role !== "toolResult") break;
231
- if (typeof message.toolCallId === "string") toolResultIds.add(message.toolCallId);
232
- index -= 1;
233
- }
234
- if (toolResultIds.size === 0) return -1;
235
- const assistant = asReplayMessage(messages[index]);
236
- if (assistant?.role !== "assistant" || !Array.isArray(assistant.content)) return -1;
237
- const toolCallIds = /* @__PURE__ */ new Set();
238
- for (const block of assistant.content) {
239
- if (!block || typeof block !== "object") continue;
240
- const record = block;
241
- if ((record.type === "toolCall" || record.type === "tool_use" || record.type === "function_call") && typeof record.id === "string") toolCallIds.add(record.id);
242
- }
243
- return [...toolResultIds].every((toolCallId) => toolCallIds.has(toolCallId)) ? index : -1;
244
- }
245
- //#endregion
246
- //#region packages/ai/src/providers/anthropic-tool-projection.ts
247
- function isProviderSupportedViolation(violation) {
248
- return violation.endsWith(".$dynamicRef") || violation.endsWith(".$dynamicAnchor");
249
- }
250
- const schemaValueKeywords = /* @__PURE__ */ new Set([
251
- "additionalProperties",
252
- "contains",
253
- "contentSchema",
254
- "else",
255
- "if",
256
- "items",
257
- "not",
258
- "propertyNames",
259
- "then",
260
- "unevaluatedItems",
261
- "unevaluatedProperties"
262
- ]);
263
- const schemaArrayKeywords = /* @__PURE__ */ new Set([
264
- "allOf",
265
- "anyOf",
266
- "oneOf",
267
- "prefixItems"
268
- ]);
269
- const schemaMapKeywords = /* @__PURE__ */ new Set([
270
- "$defs",
271
- "definitions",
272
- "dependencies",
273
- "dependentSchemas",
274
- "patternProperties",
275
- "properties"
276
- ]);
277
- function normalizeAnthropicJsonSchema(schema) {
278
- if (!isRecord(schema)) return schema;
279
- let changed = false;
280
- const normalized = { ...schema };
281
- for (const [key, value] of Object.entries(schema)) {
282
- if (schemaValueKeywords.has(key) && !Array.isArray(value)) {
283
- const next = normalizeAnthropicJsonSchema(value);
284
- normalized[key] = next;
285
- changed ||= next !== value;
286
- continue;
287
- }
288
- if (schemaArrayKeywords.has(key) && Array.isArray(value)) {
289
- const next = value.map(normalizeAnthropicJsonSchema);
290
- normalized[key] = next;
291
- changed ||= next.some((entry, index) => entry !== value[index]);
292
- continue;
293
- }
294
- if (schemaMapKeywords.has(key) && isRecord(value)) {
295
- const next = Object.fromEntries(Object.entries(value).map(([entryKey, entryValue]) => [entryKey, normalizeAnthropicJsonSchema(entryValue)]));
296
- normalized[key] = next;
297
- changed ||= Object.entries(value).some(([entryKey, entryValue]) => next[entryKey] !== entryValue);
298
- }
299
- }
300
- if (Array.isArray(schema.items)) {
301
- normalized.prefixItems = schema.items.map(normalizeAnthropicJsonSchema);
302
- const additionalItems = schema.additionalItems;
303
- if (typeof additionalItems === "boolean" || isRecord(additionalItems)) normalized.items = normalizeAnthropicJsonSchema(additionalItems);
304
- else delete normalized.items;
305
- delete normalized.additionalItems;
306
- changed = true;
307
- }
308
- return changed ? normalized : schema;
309
- }
310
- /** Snapshots direct/custom tool descriptors before Anthropic payload construction. */
311
- function projectAnthropicTools(tools, toWireName) {
312
- const projectedTools = [];
313
- const unavailableOriginalNames = /* @__PURE__ */ new Set();
314
- for (const tool of tools) {
315
- let projectedTool;
316
- let originalName;
317
- try {
318
- const name = tool.name;
319
- originalName = name;
320
- if (!name) continue;
321
- const schemaProjection = projectRuntimeToolInputSchema(tool.parameters, `${name}.parameters`);
322
- if (!isRecord(schemaProjection.schema) || schemaProjection.violations.some((violation) => !isProviderSupportedViolation(violation))) {
323
- unavailableOriginalNames.add(name);
324
- continue;
325
- }
326
- const anthropicSchema = normalizeAnthropicJsonSchema(schemaProjection.schema);
327
- if (!isRecord(anthropicSchema)) {
328
- unavailableOriginalNames.add(name);
329
- continue;
330
- }
331
- const properties = anthropicSchema.properties;
332
- const required = anthropicSchema.required;
333
- if (properties !== void 0 && properties !== null && !isRecord(properties) || required !== void 0 && required !== null && (!Array.isArray(required) || required.some((entry) => typeof entry !== "string"))) {
334
- unavailableOriginalNames.add(name);
335
- continue;
336
- }
337
- let description;
338
- try {
339
- description = typeof tool.description === "string" ? tool.description : void 0;
340
- } catch {}
341
- projectedTool = {
342
- originalName: name,
343
- wireName: toWireName(name),
344
- ...description ? { description } : {},
345
- inputSchema: {
346
- type: "object",
347
- properties: properties ?? {},
348
- required: required ?? []
349
- }
350
- };
351
- } catch {
352
- if (originalName) unavailableOriginalNames.add(originalName);
353
- continue;
354
- }
355
- const conflictingTool = projectedTools.find((entry) => entry.wireName === projectedTool.wireName);
356
- if (conflictingTool && conflictingTool.originalName !== projectedTool.originalName) throw new Error(`Anthropic tool names "${conflictingTool.originalName}" and "${projectedTool.originalName}" both map to "${projectedTool.wireName}"`);
357
- projectedTools.push(projectedTool);
358
- }
359
- return {
360
- inputToolCount: tools.length,
361
- unavailableOriginalNames,
362
- tools: projectedTools
363
- };
364
- }
365
- /** Keeps forced Anthropic tool choices aligned with the projected wire names. */
366
- function reconcileAnthropicToolChoice(choice, projection) {
367
- if (projection.inputToolCount === 0) return choice;
368
- if (choice.type === "tool") {
369
- const requestedName = choice.name;
370
- const originalMatch = projection.tools.find((tool) => tool.originalName === requestedName);
371
- if (originalMatch) return {
372
- ...choice,
373
- name: originalMatch.wireName
374
- };
375
- if (projection.unavailableOriginalNames.has(requestedName)) throw new Error(`Anthropic tool_choice requested unavailable tool "${requestedName}" after schema conversion`);
376
- const matchedTool = projection.tools.find((tool) => tool.wireName === requestedName);
377
- if (!matchedTool) throw new Error(`Anthropic tool_choice requested unavailable tool "${requestedName}" after schema conversion`);
378
- return {
379
- ...choice,
380
- name: matchedTool.wireName
381
- };
382
- }
383
- if (projection.tools.length === 0) {
384
- if (choice.type === "auto") return;
385
- if (choice.type === "any") throw new Error("Anthropic tool_choice requires a tool, but no tools survived schema conversion");
386
- }
387
- return choice;
388
- }
389
- /** Maps Claude Code wire names without trusting every direct/custom descriptor. */
390
- function resolveOriginalAnthropicToolName(name, projection) {
391
- return projection?.tools.find((tool) => tool.wireName === name)?.originalName ?? name;
392
- }
393
- //#endregion
394
- //#region packages/ai/src/providers/anthropic-usage.ts
395
- function readAnthropicUsageTokenCount(value) {
396
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
397
- }
398
- function readAnthropicCacheWriteUsage(usage) {
399
- if (!usage.cache_creation || typeof usage.cache_creation !== "object") return {};
400
- const cacheCreation = usage.cache_creation;
401
- const cacheWrite5m = readAnthropicUsageTokenCount(cacheCreation.ephemeral_5m_input_tokens);
402
- const cacheWrite1h = readAnthropicUsageTokenCount(cacheCreation.ephemeral_1h_input_tokens);
403
- return {
404
- ...cacheWrite5m !== void 0 ? { cacheWrite5m } : {},
405
- ...cacheWrite1h !== void 0 ? { cacheWrite1h } : {}
406
- };
407
- }
408
- function readAnthropicPromptUsageSnapshot(usage) {
409
- const input = readAnthropicUsageTokenCount(usage.input_tokens);
410
- const cacheRead = usage.cache_read_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_read_input_tokens);
411
- const cacheWrite = usage.cache_creation_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_creation_input_tokens);
412
- if (input === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
413
- return {
414
- input,
415
- cacheRead,
416
- cacheWrite
417
- };
418
- }
419
- function readLastAnthropicIterationUsage(usage) {
420
- if (usage.iterations == null) return { state: "absent" };
421
- if (!Array.isArray(usage.iterations) || usage.iterations.length === 0) return { state: "invalid" };
422
- const iteration = usage.iterations.at(-1);
423
- if (!iteration || typeof iteration !== "object" || Array.isArray(iteration)) return { state: "invalid" };
424
- const record = iteration;
425
- const input = readAnthropicUsageTokenCount(record.input_tokens);
426
- const cacheRead = readAnthropicUsageTokenCount(record.cache_read_input_tokens);
427
- const cacheWrite = readAnthropicUsageTokenCount(record.cache_creation_input_tokens);
428
- const outputTokens = readAnthropicUsageTokenCount(record.output_tokens);
429
- if (input === void 0 || cacheRead === void 0 || cacheWrite === void 0 || outputTokens === void 0) return { state: "invalid" };
430
- const contextPromptTokens = input + cacheRead + cacheWrite;
431
- return {
432
- state: "valid",
433
- usage: {
434
- contextPromptTokens,
435
- totalTokens: contextPromptTokens + outputTokens
436
- }
437
- };
438
- }
439
- //#endregion
440
21
  //#region packages/ai/src/providers/anthropic.ts
441
22
  var anthropic_exports = /* @__PURE__ */ __exportAll({
442
23
  streamAnthropic: () => streamAnthropic,
@@ -571,7 +152,7 @@ async function* iterateAnthropicEvents(response, requireMessageStop = false) {
571
152
  }
572
153
  const streamAnthropic = (model, context, options) => {
573
154
  const stream = new AssistantMessageEventStream();
574
- const requestContext = prepareClaudeSonnet5RequestContext(model, context);
155
+ const requestContext = prepareClaudeNoPrefillRequestContext(model, context);
575
156
  const requestOptions = normalizeAnthropicThinkingOptions(model, options);
576
157
  (async () => {
577
158
  const output = {
@@ -684,7 +265,11 @@ const streamAnthropic = (model, context, options) => {
684
265
  });
685
266
  costModel = {
686
267
  ...model,
687
- cost: CLAUDE_FABLE_5_FALLBACK_MODEL_COST
268
+ cost: resolveAnthropicFallbackServingModelCost({
269
+ requestedModelId: model.id,
270
+ servingModelId: fallbackBoundary.toModel,
271
+ requestedCost: model.cost
272
+ })
688
273
  };
689
274
  calculateCost(costModel, output.usage);
690
275
  eventSink.push({
@@ -879,7 +464,7 @@ const streamAnthropic = (model, context, options) => {
879
464
  }
880
465
  calculateCost(costModel, output.usage);
881
466
  }
882
- if (requestOptions?.signal?.aborted) throw new Error("Request was aborted");
467
+ if (requestOptions?.signal?.aborted) throw transportAbortError(requestOptions.signal);
883
468
  if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
884
469
  refusalBuffer?.flush();
885
470
  stream.push({
@@ -898,7 +483,7 @@ const streamAnthropic = (model, context, options) => {
898
483
  output.content = [];
899
484
  }
900
485
  output.stopReason = requestOptions?.signal?.aborted ? "aborted" : "error";
901
- output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
486
+ output.errorMessage = formatProviderError(error);
902
487
  stream.push({
903
488
  type: "error",
904
489
  reason: output.stopReason,
@@ -974,7 +559,7 @@ const streamSimpleAnthropic = (model, context, options) => {
974
559
  thinkingEnabled: false
975
560
  });
976
561
  const reasoning = options?.reasoning === "off" ? mandatoryAdaptiveThinking ? "low" : "high" : options?.reasoning;
977
- if (resolveClaudeSonnet5ModelIdentity(model)) return streamAnthropic(model, context, {
562
+ if (resolveClaudeOpus5ModelIdentity(model) || resolveClaudeSonnet5ModelIdentity(model)) return streamAnthropic(model, context, {
978
563
  ...base,
979
564
  thinkingEnabled: true,
980
565
  effort: mapThinkingLevelToEffort(model, reasoning ?? "high")
@@ -1019,7 +604,7 @@ function isAnthropicPublicEndpoint(baseUrl) {
1019
604
  * identity) requests are excluded until the beta is verified there.
1020
605
  */
1021
606
  function supportsAnthropicServerSideFallback(model) {
1022
- if (!usesClaudeFable5MessagesContract(model) || model.provider !== "anthropic") return false;
607
+ if (!usesClaudeFable5MessagesContract(model) && resolveClaudeOpus5ModelIdentity(model) === void 0 || model.provider !== "anthropic") return false;
1023
608
  return isAnthropicPublicEndpoint(model.baseUrl);
1024
609
  }
1025
610
  function createClient(model, apiKey, thinkingEnabled, interleavedThinking, useFineGrainedToolStreamingBeta, optionsHeaders, dynamicHeaders, sessionId) {
@@ -1142,7 +727,7 @@ async function buildParams(model, context, isOAuthTokenResult, options, serverSi
1142
727
  stream: true
1143
728
  };
1144
729
  if (system) params.system = system;
1145
- if (serverSideFallback) params.fallbacks = buildAnthropicServerSideFallbacks();
730
+ if (serverSideFallback) params.fallbacks = ANTHROPIC_SERVER_SIDE_FALLBACKS;
1146
731
  if (options?.temperature !== void 0 && !options?.thinkingEnabled && !supportsNativeXhighEffort(model)) params.temperature = options.temperature;
1147
732
  if (options?.stop !== void 0 && options.stop.length > 0) params.stop_sequences = options.stop;
1148
733
  if (tools && tools.length > 0) params.tools = tools;
@@ -1428,4 +1013,4 @@ function mapStopReason(reason) {
1428
1013
  }
1429
1014
  }
1430
1015
  //#endregion
1431
- export { normalizeAnthropicInlineContent as C, createAnthropicInlineImageBudget as S, canonicalizeBase64 as T, buildAnthropicServerSideFallbacks as _, readAnthropicPromptUsageSnapshot as a, omitFoundryBearerCredentialHeaders as b, projectAnthropicTools as c, ANTHROPIC_OMITTED_REASONING_TEXT as d, findActiveAnthropicToolTurnAssistantIndex as f, applyAnthropicFallbackBoundary as g, CLAUDE_FABLE_5_FALLBACK_MODEL_COST as h, readAnthropicCacheWriteUsage as i, reconcileAnthropicToolChoice as l, CLAUDE_FABLE_5_FALLBACK_MODEL as m, streamAnthropic as n, readAnthropicUsageTokenCount as o, ANTHROPIC_SERVER_SIDE_FALLBACK_BETA as p, streamSimpleAnthropic as r, readLastAnthropicIterationUsage as s, anthropic_exports as t, resolveOriginalAnthropicToolName as u, readAnthropicFallbackBoundary as v, resolveAnthropicImageMediaType as w, usesFoundryBearerAuth as x, applyAnthropicRefusal as y };
1016
+ export { streamAnthropic as n, streamSimpleAnthropic as r, anthropic_exports as t };
@@ -47,6 +47,26 @@ declare const CLAUDE_SONNET_5_THINKING_PROFILE: {
47
47
  }];
48
48
  readonly defaultLevel: "high";
49
49
  };
50
+ declare const CLAUDE_OPUS_5_THINKING_PROFILE: {
51
+ readonly levels: readonly [{
52
+ readonly id: "off";
53
+ }, {
54
+ readonly id: "minimal";
55
+ }, {
56
+ readonly id: "low";
57
+ }, {
58
+ readonly id: "medium";
59
+ }, {
60
+ readonly id: "high";
61
+ }, {
62
+ readonly id: "xhigh";
63
+ }, {
64
+ readonly id: "adaptive";
65
+ }, {
66
+ readonly id: "max";
67
+ }];
68
+ readonly defaultLevel: "high";
69
+ };
50
70
  /** Resolve the canonical normalized Claude model id for one runtime model ref. */
51
71
  declare function resolveClaudeModelIdentity(ref: ClaudeModelRef): string;
52
72
  /** Resolve Claude Fable 5 through direct ids, cloud ids, or deployment metadata. */
@@ -57,8 +77,14 @@ declare function resolveClaudeMythos5ModelIdentity(ref: ClaudeModelRef): string
57
77
  declare function requiresClaudeMandatoryAdaptiveThinking(ref: ClaudeModelRef): boolean;
58
78
  /** Resolve Claude Sonnet 5 through direct ids, cloud ids, or deployment metadata. */
59
79
  declare function resolveClaudeSonnet5ModelIdentity(ref: ClaudeModelRef): string | undefined;
80
+ /** Resolve Claude Opus 5 through aliases, direct ids, cloud ids, or deployment metadata. */
81
+ declare function resolveClaudeOpus5ModelIdentity(ref: ClaudeModelRef): string | undefined;
60
82
  /** Return whether a Claude model supports adaptive thinking. */
61
83
  declare function supportsClaudeAdaptiveThinking(ref: ClaudeModelRef): boolean;
84
+ /** Return whether a Claude model has a native 1M-token context window. */
85
+ declare function supportsClaude1MContext(ref: ClaudeModelRef): boolean;
86
+ /** Return whether a Claude model supports Anthropic's native fast mode. */
87
+ declare function supportsClaudeFastMode(ref: ClaudeModelRef): boolean;
62
88
  /** Return whether a Claude model supports native max effort. */
63
89
  declare function supportsClaudeNativeMaxEffort(ref: ClaudeModelRef): boolean;
64
90
  /** Return whether a Claude model supports native xhigh effort. */
@@ -71,4 +97,4 @@ declare function requiresClaudeDefaultSampling(ref: ClaudeModelRef): boolean;
71
97
  */
72
98
  declare function resolveClaudeNativeThinkingLevelMap(ref: ClaudeEffortModelRef): Record<string, string | null | undefined> | undefined;
73
99
  //#endregion
74
- export { resolveClaudeFable5ModelIdentity as a, resolveClaudeNativeThinkingLevelMap as c, supportsClaudeNativeMaxEffort as d, supportsClaudeNativeXhighEffort as f, requiresClaudeMandatoryAdaptiveThinking as i, resolveClaudeSonnet5ModelIdentity as l, CLAUDE_SONNET_5_THINKING_PROFILE as n, resolveClaudeModelIdentity as o, requiresClaudeDefaultSampling as r, resolveClaudeMythos5ModelIdentity as s, CLAUDE_FABLE_5_THINKING_PROFILE as t, supportsClaudeAdaptiveThinking as u };
100
+ export { requiresClaudeMandatoryAdaptiveThinking as a, resolveClaudeMythos5ModelIdentity as c, resolveClaudeSonnet5ModelIdentity as d, supportsClaude1MContext as f, supportsClaudeNativeXhighEffort as g, supportsClaudeNativeMaxEffort as h, requiresClaudeDefaultSampling as i, resolveClaudeNativeThinkingLevelMap as l, supportsClaudeFastMode as m, CLAUDE_OPUS_5_THINKING_PROFILE as n, resolveClaudeFable5ModelIdentity as o, supportsClaudeAdaptiveThinking as p, CLAUDE_SONNET_5_THINKING_PROFILE as r, resolveClaudeModelIdentity as s, CLAUDE_FABLE_5_THINKING_PROFILE as t, resolveClaudeOpus5ModelIdentity as u };