@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
@@ -1,883 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
- import { g as supportsClaudeAdaptiveThinking, m as resolveClaudeSonnet5ModelIdentity, p as resolveClaudeOpus5ModelIdentity, y as supportsClaudeNativeXhighEffort } from "./src-C8U7lkoa.mjs";
3
- import { t as AssistantMessageEventStream } from "./event-stream-uSMZJ3FA.mjs";
4
- import { o as isRecord } from "./utf16-slice-qz3nsy87.mjs";
5
- import { r as calculateCost, t as sanitizeSurrogates } from "./sanitize-unicode-S6binQG-.mjs";
6
- import { S as usesClaudeStreamingRefusalContract, _ as prepareClaudeNoPrefillRequestContext, a as describeToolResultMediaPlaceholder, c as extractToolResultText, d as isImageWithMediaPayload, f as ANTHROPIC_CLAUDE_CODE_BILLING_SYSTEM_BLOCK, g as mapAnthropicStopReason, m as applyClaudeRequestContract, n as getAiTransportHost, p as ANTHROPIC_CLAUDE_CODE_VERSION, r as resolveAiTransportHeaderSentinels, s as extractToolResultBlockText, v as requiresClaudeAdaptiveThinking, x as usesClaudeFable5MessagesContract, y as resolveAnthropicThinkingEffort } from "./host-BIaiBURL.mjs";
7
- import { A as applyAnthropicCacheControlToMessages, C as applyAnthropicFallbackBoundary, D as createAnthropicInlineImageBudget, E as applyAnthropicRefusal, I as isAnthropicOAuthApiKey, L as omitFoundryBearerCredentialHeaders, O as normalizeAnthropicInlineContent, R as usesFoundryBearerAuth, T as resolveAnthropicFallbackServingModelCost, _ as toClaudeCodeToolName, a as suppressAnthropicCompaction, b as ANTHROPIC_SERVER_SIDE_FALLBACKS, f as normalizeAnthropicToolCallId, g as resolveOriginalAnthropicToolName, h as reconcileAnthropicToolChoice, k as resolveAnthropicImageMediaType, m as projectAnthropicTools, n as createCompactionCapture, o as applyAnthropicMessageDeltaUsage, p as normalizeAnthropicToolChoice, r as isAnthropicReplayRejection, s as applyAnthropicMessageStartUsage, t as buildAnthropicReplayPlan, v as ANTHROPIC_OMITTED_REASONING_TEXT, w as readAnthropicFallbackBoundary, x as ANTHROPIC_SERVER_SIDE_FALLBACK_BETA, y as findActiveAnthropicToolTurnAssistantIndex } from "./anthropic-compaction-replay-OMJZ0uyo.mjs";
8
- import { t as resolveCacheRetention } from "./cache-retention-0x979a5V.mjs";
9
- import { d as stripSystemPromptCacheBoundary, n as buildBaseOptions, r as clampMaxTokensToModel, t as adjustMaxTokensForThinking, u as splitSystemPromptCacheBoundary } from "./simple-options-0PLDyJ-d.mjs";
10
- import { t as MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "./transport-utils-CtuS1Upe.mjs";
11
- import { n as getEnvApiKey } from "./env-api-keys-bktO00EJ.mjs";
12
- import { _ as transportAbortError, f as notifyProviderHttpResponse, s as finalizeTerminalToolCallArguments, t as assignTransportErrorDetails } from "./transport-stream-shared-CytPVLIg.mjs";
13
- import { t as createDeferredEventBuffer } from "./deferred-event-buffer-DAvyP7qA.mjs";
14
- import { n as parseJsonWithRepair, r as parseStreamingJson, t as createToolArgumentPreviewSchedule } from "./json-parse-BuAJEbdW.mjs";
15
- import { t as notifyLlmRequestActivity } from "./llm-request-activity-BjtkplhG.mjs";
16
- import { t as transformProviderMessages } from "./provider-transcript-transform-WvJmFUAf.mjs";
17
- import { i as resolveCloudflareBaseUrl, n as hasCopilotVisionInput, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-NCJtz9i0.mjs";
18
- import Anthropic from "@anthropic-ai/sdk";
19
- import { Stream } from "@anthropic-ai/sdk/core/streaming.js";
20
- //#region packages/ai/src/providers/anthropic.ts
21
- var anthropic_exports = /* @__PURE__ */ __exportAll({
22
- streamAnthropic: () => streamAnthropic,
23
- streamSimpleAnthropic: () => streamSimpleAnthropic
24
- });
25
- const ANTHROPIC_CACHE_CONTROL_LIMIT = 4;
26
- const EMPTY_ERROR_TOOL_RESULT_TEXT = "[tool error with no output]";
27
- function getCacheControl(model, cacheRetention) {
28
- const retention = resolveCacheRetention(cacheRetention);
29
- if (retention === "none") return { retention };
30
- const ttl = retention === "long" && getAnthropicCompat(model).supportsLongCacheRetention ? "1h" : void 0;
31
- return {
32
- retention,
33
- cacheControl: {
34
- type: "ephemeral",
35
- ...ttl && { ttl }
36
- }
37
- };
38
- }
39
- /**
40
- * Convert content blocks to Anthropic API format
41
- */
42
- async function convertContentBlocks(content, isError, imageBudget) {
43
- const text = extractToolResultText(content);
44
- const mediaPlaceholder = describeToolResultMediaPlaceholder(content);
45
- if (!content.some(isImageWithMediaPayload)) {
46
- const sanitized = sanitizeSurrogates(text);
47
- return sanitized.trim().length > 0 ? sanitized : mediaPlaceholder ?? (isError ? EMPTY_ERROR_TOOL_RESULT_TEXT : "");
48
- }
49
- const blocks = [];
50
- let hasTextBlock = false;
51
- for (const block of content) {
52
- if (!block || typeof block !== "object") continue;
53
- const record = block;
54
- const blockText = extractToolResultBlockText(block);
55
- if (blockText) {
56
- blocks.push({
57
- type: "text",
58
- text: sanitizeSurrogates(blockText)
59
- });
60
- hasTextBlock = true;
61
- }
62
- if (!isImageWithMediaPayload(record)) continue;
63
- const [normalizedImage] = await normalizeAnthropicInlineContent([{
64
- type: "image",
65
- data: typeof record.data === "string" ? record.data : "",
66
- mimeType: typeof record.mimeType === "string" ? record.mimeType : "image/jpeg"
67
- }], imageBudget);
68
- if (normalizedImage?.type !== "image") continue;
69
- blocks.push({
70
- type: "image",
71
- source: {
72
- type: "base64",
73
- media_type: resolveAnthropicImageMediaType(normalizedImage.mimeType),
74
- data: normalizedImage.data
75
- }
76
- });
77
- }
78
- if (!hasTextBlock) blocks.unshift({
79
- type: "text",
80
- text: mediaPlaceholder ?? "(see attached image)"
81
- });
82
- return blocks;
83
- }
84
- const FINE_GRAINED_TOOL_STREAMING_BETA = "fine-grained-tool-streaming-2025-05-14";
85
- const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
86
- const ANTHROPIC_MIN_THINKING_BUDGET_TOKENS = 1024;
87
- function getAnthropicCompat(model) {
88
- const isFireworks = model.provider === "fireworks";
89
- const isCloudflareAiGatewayAnthropic = model.provider === "cloudflare-ai-gateway" && model.baseUrl.includes("anthropic");
90
- return {
91
- supportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? !isFireworks,
92
- supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? !isFireworks,
93
- sendSessionAffinityHeaders: model.compat?.sendSessionAffinityHeaders ?? (isFireworks || isCloudflareAiGatewayAnthropic),
94
- supportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? !isFireworks,
95
- allowEmptySignature: model.compat?.allowEmptySignature ?? false
96
- };
97
- }
98
- function mergeHeaders(...headerSources) {
99
- const merged = {};
100
- for (const headers of headerSources) if (headers) Object.assign(merged, headers);
101
- return merged;
102
- }
103
- const ANTHROPIC_MESSAGE_EVENTS = /* @__PURE__ */ new Set([
104
- "message_start",
105
- "message_delta",
106
- "message_stop",
107
- "content_block_start",
108
- "content_block_delta",
109
- "content_block_stop"
110
- ]);
111
- async function* iterateAnthropicEvents(response, requireMessageStop = false) {
112
- if (!response.body) throw new Error("Attempted to iterate over an Anthropic response with no body");
113
- let sawMessageEnd = false;
114
- for await (const sse of Stream.rawEvents(response)) {
115
- if (sse.event === "error") throw new Error(sse.data);
116
- if (!ANTHROPIC_MESSAGE_EVENTS.has(sse.event ?? "")) continue;
117
- try {
118
- const event = parseJsonWithRepair(sse.data);
119
- if (event.type === "message_stop") sawMessageEnd = true;
120
- yield event;
121
- } catch (error) {
122
- if (error instanceof SyntaxError) throw new Error(MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE, { cause: error });
123
- throw error;
124
- }
125
- }
126
- if (requireMessageStop && !sawMessageEnd) throw new Error("Anthropic stream ended before message_stop");
127
- }
128
- const streamAnthropic = (model, context, options) => {
129
- const stream = new AssistantMessageEventStream();
130
- const requestContext = prepareClaudeNoPrefillRequestContext(model, context);
131
- const requestOptions = normalizeAnthropicThinkingOptions(model, options);
132
- (async () => {
133
- const output = {
134
- role: "assistant",
135
- content: [],
136
- api: model.api,
137
- provider: model.provider,
138
- model: model.id,
139
- usage: {
140
- input: 0,
141
- output: 0,
142
- cacheRead: 0,
143
- cacheWrite: 0,
144
- totalTokens: 0,
145
- cost: {
146
- input: 0,
147
- output: 0,
148
- cacheRead: 0,
149
- cacheWrite: 0,
150
- total: 0
151
- }
152
- },
153
- stopReason: "stop",
154
- timestamp: Date.now()
155
- };
156
- const refusalBuffer = usesClaudeStreamingRefusalContract(model) ? createDeferredEventBuffer(stream, () => notifyLlmRequestActivity(requestOptions?.signal)) : void 0;
157
- const eventSink = refusalBuffer ?? stream;
158
- let costModel = model;
159
- let messageStartPromptUsage;
160
- let usedCompactionReplay = false;
161
- try {
162
- let client;
163
- let isOAuth;
164
- let serverSideFallback = false;
165
- if (requestOptions?.client) {
166
- client = requestOptions.client;
167
- isOAuth = false;
168
- } else {
169
- const apiKey = requestOptions?.apiKey ?? getEnvApiKey(model.provider) ?? "";
170
- let copilotDynamicHeaders;
171
- if (model.provider === "github-copilot") {
172
- const hasImages = hasCopilotVisionInput(requestContext.messages);
173
- copilotDynamicHeaders = buildCopilotDynamicHeaders({
174
- messages: requestContext.messages,
175
- hasImages
176
- });
177
- }
178
- const cacheSessionId = (requestOptions?.cacheRetention ?? resolveCacheRetention()) === "none" ? void 0 : requestOptions?.sessionId;
179
- const created = createClient(model, apiKey, requestOptions?.thinkingEnabled === true, requestOptions?.interleavedThinking ?? true, shouldUseFineGrainedToolStreamingBeta(model, requestContext), requestOptions?.headers, copilotDynamicHeaders, cacheSessionId);
180
- client = created.client;
181
- isOAuth = created.isOAuthToken;
182
- serverSideFallback = created.serverSideFallback;
183
- }
184
- const builtParams = await buildParams(model, requestContext, isOAuth, requestOptions, serverSideFallback);
185
- usedCompactionReplay = builtParams.usedCompactionReplay;
186
- let params = builtParams.params;
187
- const toolProjection = builtParams.toolProjection;
188
- const nextParams = await requestOptions?.onPayload?.(params, model);
189
- if (nextParams !== void 0) params = nextParams;
190
- applyClaudeRequestContract(params, model);
191
- const sdkRequestOptions = {
192
- ...requestOptions?.signal ? { signal: requestOptions.signal } : {},
193
- ...requestOptions?.timeoutMs !== void 0 ? { timeout: requestOptions.timeoutMs } : {},
194
- maxRetries: 0
195
- };
196
- const response = await client.messages.create({
197
- ...params,
198
- stream: true
199
- }, sdkRequestOptions).asResponse();
200
- await notifyProviderHttpResponse({
201
- options: requestOptions,
202
- response,
203
- model
204
- });
205
- const blocks = output.content;
206
- const blockIndexes = /* @__PURE__ */ new Map();
207
- const toolArgumentPreviewSchedules = /* @__PURE__ */ new WeakMap();
208
- const sealedToolCalls = [];
209
- const compactionCapture = createCompactionCapture(output, model, requestOptions);
210
- const requireMessageStop = refusalBuffer !== void 0 || model.provider === "anthropic" && isAnthropicPublicEndpoint(model.baseUrl);
211
- for await (const event of iterateAnthropicEvents(response, requireMessageStop)) if (event.type === "message_start") {
212
- output.responseId = event.message.id;
213
- output.responseModel = event.message.model;
214
- messageStartPromptUsage = applyAnthropicMessageStartUsage(output.usage, event.message.usage);
215
- calculateCost(costModel, output.usage);
216
- eventSink.push({
217
- type: "start",
218
- partial: output
219
- });
220
- } else if (event.type === "content_block_start") {
221
- const rawContentBlock = isRecord(event.content_block) ? event.content_block : void 0;
222
- if (requestOptions?.anthropicServerCompaction === true && compactionCapture.begin(event.index, rawContentBlock, output.content.length)) continue;
223
- const fallbackBoundary = refusalBuffer ? readAnthropicFallbackBoundary(event.content_block) : null;
224
- if (fallbackBoundary) {
225
- refusalBuffer?.discard();
226
- sealedToolCalls.length = 0;
227
- blockIndexes.clear();
228
- applyAnthropicFallbackBoundary({
229
- output,
230
- boundary: fallbackBoundary,
231
- provider: model.provider
232
- });
233
- costModel = {
234
- ...model,
235
- cost: resolveAnthropicFallbackServingModelCost({
236
- requestedModelId: model.id,
237
- servingModelId: fallbackBoundary.toModel,
238
- requestedCost: model.cost
239
- })
240
- };
241
- calculateCost(costModel, output.usage);
242
- eventSink.push({
243
- type: "start",
244
- partial: output
245
- });
246
- for (const [i, block] of blocks.entries()) {
247
- if (block.type !== "text") continue;
248
- delete block.index;
249
- eventSink.push({
250
- type: "text_start",
251
- contentIndex: i,
252
- partial: output
253
- });
254
- if (block.text) eventSink.push({
255
- type: "text_delta",
256
- contentIndex: i,
257
- delta: block.text,
258
- partial: output
259
- });
260
- eventSink.push({
261
- type: "text_end",
262
- contentIndex: i,
263
- content: block.text,
264
- partial: output
265
- });
266
- }
267
- } else if (event.content_block.type === "text") {
268
- const block = {
269
- type: "text",
270
- text: "",
271
- index: event.index
272
- };
273
- output.content.push(block);
274
- blockIndexes.set(event.index, output.content.length - 1);
275
- eventSink.push({
276
- type: "text_start",
277
- contentIndex: output.content.length - 1,
278
- partial: output
279
- });
280
- } else if (event.content_block.type === "thinking") {
281
- const block = {
282
- type: "thinking",
283
- thinking: "",
284
- thinkingSignature: "",
285
- index: event.index
286
- };
287
- output.content.push(block);
288
- blockIndexes.set(event.index, output.content.length - 1);
289
- eventSink.push({
290
- type: "thinking_start",
291
- contentIndex: output.content.length - 1,
292
- partial: output
293
- });
294
- } else if (event.content_block.type === "redacted_thinking") {
295
- const block = {
296
- type: "thinking",
297
- thinking: "[Reasoning redacted]",
298
- thinkingSignature: event.content_block.data,
299
- redacted: true,
300
- index: event.index
301
- };
302
- output.content.push(block);
303
- blockIndexes.set(event.index, output.content.length - 1);
304
- eventSink.push({
305
- type: "thinking_start",
306
- contentIndex: output.content.length - 1,
307
- partial: output
308
- });
309
- } else if (event.content_block.type === "tool_use") {
310
- const block = {
311
- type: "toolCall",
312
- id: event.content_block.id,
313
- name: isOAuth ? resolveOriginalAnthropicToolName(event.content_block.name, toolProjection) : event.content_block.name,
314
- arguments: event.content_block.input ?? {},
315
- partialJson: "",
316
- index: event.index
317
- };
318
- output.content.push(block);
319
- blockIndexes.set(event.index, output.content.length - 1);
320
- toolArgumentPreviewSchedules.set(block, createToolArgumentPreviewSchedule());
321
- eventSink.push({
322
- type: "toolcall_start",
323
- contentIndex: output.content.length - 1,
324
- partial: output
325
- });
326
- }
327
- } else if (event.type === "content_block_delta") {
328
- const rawDelta = isRecord(event.delta) ? event.delta : void 0;
329
- if (compactionCapture.delta(event.index, rawDelta)) continue;
330
- else if (event.delta.type === "text_delta") {
331
- const index = blockIndexes.get(event.index);
332
- const block = index === void 0 ? void 0 : blocks[index];
333
- if (index !== void 0 && block?.type === "text") {
334
- block.text += event.delta.text;
335
- eventSink.push({
336
- type: "text_delta",
337
- contentIndex: index,
338
- delta: event.delta.text,
339
- partial: output
340
- });
341
- }
342
- } else if (event.delta.type === "thinking_delta") {
343
- const index = blockIndexes.get(event.index);
344
- const block = index === void 0 ? void 0 : blocks[index];
345
- if (index !== void 0 && block?.type === "thinking") {
346
- block.thinking += event.delta.thinking;
347
- eventSink.push({
348
- type: "thinking_delta",
349
- contentIndex: index,
350
- delta: event.delta.thinking,
351
- partial: output
352
- });
353
- }
354
- } else if (event.delta.type === "input_json_delta") {
355
- const index = blockIndexes.get(event.index);
356
- const block = index === void 0 ? void 0 : blocks[index];
357
- if (index !== void 0 && block?.type === "toolCall") {
358
- block.partialJson = (block.partialJson ?? "") + event.delta.partial_json;
359
- if (toolArgumentPreviewSchedules.get(block)?.(block.partialJson.length)) block.arguments = parseStreamingJson(block.partialJson);
360
- eventSink.push({
361
- type: "toolcall_delta",
362
- contentIndex: index,
363
- delta: event.delta.partial_json,
364
- partial: output
365
- });
366
- }
367
- } else if (event.delta.type === "signature_delta") {
368
- const index = blockIndexes.get(event.index);
369
- const block = index === void 0 ? void 0 : blocks[index];
370
- if (index !== void 0 && block?.type === "thinking") {
371
- block.thinkingSignature = block.thinkingSignature || "";
372
- block.thinkingSignature += event.delta.signature;
373
- }
374
- }
375
- } else if (event.type === "content_block_stop") {
376
- if (compactionCapture.complete(event.index)) continue;
377
- const index = blockIndexes.get(event.index);
378
- const block = index === void 0 ? void 0 : blocks[index];
379
- if (index !== void 0 && block) {
380
- blockIndexes.delete(event.index);
381
- delete block.index;
382
- if (block.type === "text") eventSink.push({
383
- type: "text_end",
384
- contentIndex: index,
385
- content: block.text,
386
- partial: output
387
- });
388
- else if (block.type === "thinking") eventSink.push({
389
- type: "thinking_end",
390
- contentIndex: index,
391
- content: block.thinking,
392
- partial: output
393
- });
394
- else if (block.type === "toolCall") sealedToolCalls.push({
395
- block,
396
- contentIndex: index
397
- });
398
- }
399
- } else if (event.type === "message_delta") {
400
- if (event.delta.stop_reason) {
401
- if (event.delta.stop_reason === "refusal") applyAnthropicRefusal(output, event.delta.stop_details, model.provider);
402
- else output.stopReason = mapAnthropicStopReason(event.delta.stop_reason);
403
- }
404
- applyAnthropicMessageDeltaUsage(output.usage, event.usage, messageStartPromptUsage);
405
- calculateCost(costModel, output.usage);
406
- }
407
- if (requestOptions?.signal?.aborted) throw transportAbortError(requestOptions.signal);
408
- if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
409
- if ([...blockIndexes.values()].some((index) => blocks[index]?.type === "toolCall")) throw new Error("Provider completed stream with an incomplete tool call");
410
- finalizeTerminalToolCallArguments(sealedToolCalls.map(({ block }) => block), (block) => block.partialJson && block.partialJson.length > 0 ? block.partialJson : block.arguments);
411
- for (const sealed of sealedToolCalls) {
412
- delete sealed.block.partialJson;
413
- eventSink.push({
414
- type: "toolcall_end",
415
- contentIndex: sealed.contentIndex,
416
- toolCall: sealed.block,
417
- partial: output
418
- });
419
- }
420
- refusalBuffer?.flush();
421
- stream.push({
422
- type: "done",
423
- reason: output.stopReason,
424
- message: output
425
- });
426
- stream.end();
427
- } catch (error) {
428
- const terminal = assignTransportErrorDetails(output, error, requestOptions?.signal);
429
- output.content = output.content.filter((block) => block.type !== "toolCall");
430
- for (const block of output.content) {
431
- delete block.index;
432
- delete block.partialJson;
433
- }
434
- if (refusalBuffer) {
435
- refusalBuffer.discard();
436
- output.content = [];
437
- }
438
- if (usedCompactionReplay && isAnthropicReplayRejection(error)) suppressAnthropicCompaction(output, model, requestOptions);
439
- stream.push({
440
- type: "error",
441
- reason: terminal.stopReason,
442
- error: output
443
- });
444
- stream.end();
445
- }
446
- })();
447
- return stream;
448
- };
449
- function normalizeAnthropicThinkingOptions(model, options) {
450
- if (options?.thinkingEnabled !== true || supportsClaudeAdaptiveThinking(model)) return options;
451
- const budgetTokens = options.thinkingBudgetTokens ?? ANTHROPIC_MIN_THINKING_BUDGET_TOKENS;
452
- const maxTokens = options.maxTokens ?? model.maxTokens;
453
- if (budgetTokens >= ANTHROPIC_MIN_THINKING_BUDGET_TOKENS && budgetTokens < maxTokens) return options;
454
- return {
455
- ...options,
456
- thinkingEnabled: false,
457
- thinkingBudgetTokens: void 0
458
- };
459
- }
460
- const streamSimpleAnthropic = (model, context, options) => {
461
- const apiKey = options?.apiKey || getEnvApiKey(model.provider);
462
- if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
463
- const base = {
464
- ...buildBaseOptions(model, options, apiKey),
465
- anthropicServerCompaction: options?.anthropicServerCompaction,
466
- authProfileId: options?.authProfileId,
467
- maxTokens: clampMaxTokensToModel(model, options?.maxTokens ?? model.maxTokens),
468
- toolChoice: options?.toolChoice
469
- };
470
- const mandatoryAdaptiveThinking = requiresClaudeAdaptiveThinking(model);
471
- if (options?.reasoning === "off" && !mandatoryAdaptiveThinking) return streamAnthropic(model, context, {
472
- ...base,
473
- thinkingEnabled: false
474
- });
475
- const reasoning = options?.reasoning === "off" ? mandatoryAdaptiveThinking ? "low" : "high" : options?.reasoning;
476
- if (resolveClaudeOpus5ModelIdentity(model) || resolveClaudeSonnet5ModelIdentity(model)) return streamAnthropic(model, context, {
477
- ...base,
478
- thinkingEnabled: true,
479
- effort: resolveAnthropicThinkingEffort(model, reasoning ?? "high")
480
- });
481
- if (!reasoning) return streamAnthropic(model, context, {
482
- ...base,
483
- thinkingEnabled: mandatoryAdaptiveThinking,
484
- ...mandatoryAdaptiveThinking ? { effort: "high" } : {}
485
- });
486
- if (supportsClaudeAdaptiveThinking(model)) {
487
- const effort = resolveAnthropicThinkingEffort(model, reasoning);
488
- return streamAnthropic(model, context, {
489
- ...base,
490
- thinkingEnabled: true,
491
- effort
492
- });
493
- }
494
- const adjusted = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens, reasoning, options?.thinkingBudgets);
495
- const thinkingEnabled = adjusted.thinkingBudget >= ANTHROPIC_MIN_THINKING_BUDGET_TOKENS;
496
- const maxTokens = thinkingEnabled ? adjusted.maxTokens : clampMaxTokensToModel(model, options?.maxTokens ?? model.maxTokens);
497
- return streamAnthropic(model, context, {
498
- ...base,
499
- maxTokens,
500
- thinkingEnabled,
501
- thinkingBudgetTokens: thinkingEnabled ? adjusted.thinkingBudget : void 0
502
- });
503
- };
504
- function isAnthropicPublicEndpoint(baseUrl) {
505
- if (!baseUrl) return true;
506
- try {
507
- return new URL(baseUrl).hostname.toLowerCase() === "api.anthropic.com";
508
- } catch {
509
- return false;
510
- }
511
- }
512
- /**
513
- * Server-side refusal fallback is a first-party Claude API beta: proxies and
514
- * Bedrock/Vertex/Foundry reject the `fallbacks` param, and OAuth (Claude Code
515
- * identity) requests are excluded until the beta is verified there.
516
- */
517
- function supportsAnthropicServerSideFallback(model) {
518
- if (!usesClaudeFable5MessagesContract(model) && resolveClaudeOpus5ModelIdentity(model) === void 0 || model.provider !== "anthropic") return false;
519
- return isAnthropicPublicEndpoint(model.baseUrl);
520
- }
521
- function createClient(model, apiKey, thinkingEnabled, interleavedThinking, useFineGrainedToolStreamingBeta, optionsHeaders, dynamicHeaders, sessionId) {
522
- const needsInterleavedBeta = interleavedThinking && !supportsClaudeAdaptiveThinking(model);
523
- const betaFeatures = [];
524
- if (useFineGrainedToolStreamingBeta) betaFeatures.push(FINE_GRAINED_TOOL_STREAMING_BETA);
525
- if (needsInterleavedBeta) betaFeatures.push(INTERLEAVED_THINKING_BETA);
526
- const fetchOptions = /^kimi(?:-|$)/.test(model.provider) && thinkingEnabled ? { sanitizeSse: false } : void 0;
527
- const fetch = getAiTransportHost().buildModelFetch(model, void 0, fetchOptions);
528
- if (model.provider === "cloudflare-ai-gateway") return {
529
- client: new Anthropic({
530
- apiKey,
531
- authToken: null,
532
- baseURL: resolveCloudflareBaseUrl(model),
533
- dangerouslyAllowBrowser: true,
534
- defaultHeaders: mergeHeaders({
535
- accept: "application/json",
536
- "anthropic-dangerous-direct-browser-access": "true",
537
- Authorization: null,
538
- ...betaFeatures.length > 0 ? { "anthropic-beta": betaFeatures.join(",") } : {}
539
- }, model.headers, optionsHeaders),
540
- fetch,
541
- maxRetries: 0
542
- }),
543
- isOAuthToken: false,
544
- serverSideFallback: false
545
- };
546
- if (model.provider === "github-copilot") return {
547
- client: new Anthropic({
548
- apiKey: null,
549
- authToken: apiKey,
550
- baseURL: model.baseUrl,
551
- dangerouslyAllowBrowser: true,
552
- defaultHeaders: mergeHeaders({
553
- accept: "application/json",
554
- "anthropic-dangerous-direct-browser-access": "true",
555
- ...betaFeatures.length > 0 ? { "anthropic-beta": betaFeatures.join(",") } : {}
556
- }, model.headers, dynamicHeaders, optionsHeaders),
557
- fetch,
558
- maxRetries: 0
559
- }),
560
- isOAuthToken: false,
561
- serverSideFallback: false
562
- };
563
- if (usesFoundryBearerAuth({
564
- ...model,
565
- headers: resolveAiTransportHeaderSentinels(model.headers)
566
- })) return {
567
- client: new Anthropic({
568
- apiKey: null,
569
- authToken: apiKey,
570
- baseURL: model.baseUrl,
571
- dangerouslyAllowBrowser: true,
572
- defaultHeaders: mergeHeaders({
573
- accept: "application/json",
574
- "anthropic-dangerous-direct-browser-access": "true",
575
- ...betaFeatures.length > 0 ? { "anthropic-beta": betaFeatures.join(",") } : {}
576
- }, omitFoundryBearerCredentialHeaders(model.headers), dynamicHeaders, optionsHeaders),
577
- fetch,
578
- maxRetries: 0
579
- }),
580
- isOAuthToken: false,
581
- serverSideFallback: false
582
- };
583
- if (isAnthropicOAuthApiKey(apiKey)) return {
584
- client: new Anthropic({
585
- apiKey: null,
586
- authToken: apiKey,
587
- baseURL: model.baseUrl,
588
- dangerouslyAllowBrowser: true,
589
- defaultHeaders: mergeHeaders({
590
- accept: "application/json",
591
- "anthropic-dangerous-direct-browser-access": "true",
592
- "anthropic-beta": [
593
- "claude-code-20250219",
594
- "oauth-2025-04-20",
595
- ...betaFeatures
596
- ].join(","),
597
- "user-agent": `claude-cli/${ANTHROPIC_CLAUDE_CODE_VERSION}`,
598
- "x-app": "cli"
599
- }, model.headers, optionsHeaders),
600
- fetch,
601
- maxRetries: 0
602
- }),
603
- isOAuthToken: true,
604
- serverSideFallback: false
605
- };
606
- const serverSideFallback = supportsAnthropicServerSideFallback(model);
607
- if (serverSideFallback) betaFeatures.push(ANTHROPIC_SERVER_SIDE_FALLBACK_BETA);
608
- const sessionAffinityHeaders = sessionId && getAnthropicCompat(model).sendSessionAffinityHeaders ? { "x-session-affinity": sessionId } : {};
609
- return {
610
- client: new Anthropic({
611
- apiKey,
612
- authToken: null,
613
- baseURL: model.baseUrl,
614
- dangerouslyAllowBrowser: true,
615
- defaultHeaders: mergeHeaders({
616
- accept: "application/json",
617
- "anthropic-dangerous-direct-browser-access": "true",
618
- ...betaFeatures.length > 0 ? { "anthropic-beta": betaFeatures.join(",") } : {}
619
- }, sessionAffinityHeaders, model.headers, optionsHeaders),
620
- fetch,
621
- maxRetries: 0
622
- }),
623
- isOAuthToken: false,
624
- serverSideFallback
625
- };
626
- }
627
- async function buildParams(model, context, isOAuthTokenResult, options, serverSideFallback = false) {
628
- const mandatoryAdaptiveThinking = requiresClaudeAdaptiveThinking(model);
629
- const replayThinkingEnabled = mandatoryAdaptiveThinking || options?.thinkingEnabled === true;
630
- const { cacheControl } = getCacheControl(model, options?.cacheRetention);
631
- const system = buildAnthropicSystemBlocks(context.systemPrompt, isOAuthTokenResult, cacheControl);
632
- const compat = getAnthropicCompat(model);
633
- const convertedTools = context.tools ? convertTools(context.tools, isOAuthTokenResult, compat.supportsEagerToolInputStreaming, compat.supportsCacheControlOnTools ? cacheControl : void 0) : void 0;
634
- const tools = convertedTools?.tools;
635
- const toolProjection = convertedTools?.projection;
636
- const systemCacheControlCount = countNativeCacheControlMarkers(system);
637
- const toolCacheControlCount = countNativeCacheControlMarkers(tools);
638
- const messageCacheControlLimit = Math.max(0, ANTHROPIC_CACHE_CONTROL_LIMIT - systemCacheControlCount - toolCacheControlCount);
639
- const replayPlan = buildAnthropicReplayPlan(context.messages, model, {
640
- enabled: !isOAuthTokenResult && options?.anthropicServerCompaction === true,
641
- authProfileId: options?.authProfileId,
642
- sessionId: options?.sessionId
643
- });
644
- const params = {
645
- model: model.id,
646
- messages: await convertMessages(replayPlan.messages, model, isOAuthTokenResult, cacheControl, messageCacheControlLimit, replayThinkingEnabled, compat.allowEmptySignature, replayPlan.compaction),
647
- max_tokens: options?.maxTokens ?? model.maxTokens,
648
- stream: true
649
- };
650
- if (system) params.system = system;
651
- if (serverSideFallback) params.fallbacks = ANTHROPIC_SERVER_SIDE_FALLBACKS;
652
- if (options?.temperature !== void 0 && !options?.thinkingEnabled && !supportsClaudeNativeXhighEffort(model)) params.temperature = options.temperature;
653
- if (options?.stop !== void 0 && options.stop.length > 0) params.stop_sequences = options.stop;
654
- if (tools && tools.length > 0) params.tools = tools;
655
- if (mandatoryAdaptiveThinking || model.reasoning || supportsClaudeAdaptiveThinking(model)) {
656
- if (mandatoryAdaptiveThinking || options?.thinkingEnabled) {
657
- const display = options?.thinkingDisplay ?? "summarized";
658
- if (supportsClaudeAdaptiveThinking(model)) {
659
- params.thinking = {
660
- type: "adaptive",
661
- display
662
- };
663
- const effort = options?.effort ?? (mandatoryAdaptiveThinking ? "high" : void 0);
664
- if (effort) params.output_config = { effort };
665
- } else params.thinking = {
666
- type: "enabled",
667
- budget_tokens: options?.thinkingBudgetTokens ?? ANTHROPIC_MIN_THINKING_BUDGET_TOKENS,
668
- display
669
- };
670
- } else if (options?.thinkingEnabled === false) params.thinking = { type: "disabled" };
671
- }
672
- if (options?.metadata) {
673
- const userId = options.metadata.user_id;
674
- if (typeof userId === "string") params.metadata = { user_id: userId };
675
- }
676
- if (options?.toolChoice) {
677
- const normalizedToolChoice = normalizeAnthropicToolChoice(replayThinkingEnabled, options.toolChoice);
678
- const projectedToolChoice = toolProjection ? reconcileAnthropicToolChoice(normalizedToolChoice, toolProjection) : normalizedToolChoice;
679
- if (projectedToolChoice) params.tool_choice = projectedToolChoice;
680
- }
681
- return {
682
- params,
683
- toolProjection,
684
- usedCompactionReplay: replayPlan.compaction !== void 0
685
- };
686
- }
687
- async function convertMessages(messages, model, isOAuthTokenValue, cacheControl, messageCacheControlLimit = 4, replayThinkingEnabled = true, allowEmptySignature = false, compaction) {
688
- const params = [];
689
- const imageBudget = createAnthropicInlineImageBudget();
690
- const cacheBreakpointOptOutParamIndexes = /* @__PURE__ */ new Set();
691
- const transformedMessages = transformProviderMessages(messages, model, normalizeAnthropicToolCallId);
692
- const activeToolTurnAssistantIndex = replayThinkingEnabled ? -1 : findActiveAnthropicToolTurnAssistantIndex(transformedMessages);
693
- for (let i = 0; i < transformedMessages.length; i++) {
694
- const msg = transformedMessages[i];
695
- if (!msg) continue;
696
- if (msg.role === "user") {
697
- const isRuntimeContextCarrier = msg.runtimeContextCarrier === true;
698
- if (typeof msg.content === "string") {
699
- if (msg.content.trim().length > 0) {
700
- if (isRuntimeContextCarrier) cacheBreakpointOptOutParamIndexes.add(params.length);
701
- params.push({
702
- role: "user",
703
- content: sanitizeSurrogates(msg.content)
704
- });
705
- }
706
- } else {
707
- const filteredBlocks = (await normalizeAnthropicInlineContent(msg.content, imageBudget)).map((item) => {
708
- if (item.type === "text") return {
709
- type: "text",
710
- text: sanitizeSurrogates(item.text)
711
- };
712
- return {
713
- type: "image",
714
- source: {
715
- type: "base64",
716
- media_type: resolveAnthropicImageMediaType(item.mimeType),
717
- data: item.data
718
- }
719
- };
720
- }).filter((b) => {
721
- if (b.type === "text") return b.text.trim().length > 0;
722
- return true;
723
- });
724
- if (filteredBlocks.length === 0) continue;
725
- if (isRuntimeContextCarrier) cacheBreakpointOptOutParamIndexes.add(params.length);
726
- params.push({
727
- role: "user",
728
- content: filteredBlocks
729
- });
730
- }
731
- } else if (msg.role === "assistant") {
732
- const blocks = i === 0 && compaction ? [compaction] : [];
733
- let omittedThinking = false;
734
- for (const block of msg.content) if (block.type === "text") {
735
- if (block.text.trim().length === 0) continue;
736
- blocks.push({
737
- type: "text",
738
- text: sanitizeSurrogates(block.text)
739
- });
740
- } else if (block.type === "thinking") {
741
- if (!replayThinkingEnabled && i !== activeToolTurnAssistantIndex) {
742
- omittedThinking = true;
743
- continue;
744
- }
745
- if (block.redacted) {
746
- if (!block.thinkingSignature) throw new Error("redacted thinking block is missing its opaque signature");
747
- blocks.push({
748
- type: "redacted_thinking",
749
- data: block.thinkingSignature
750
- });
751
- continue;
752
- }
753
- const thinkingSignature = block.thinkingSignature?.trim();
754
- const hasNativeThinkingSignature = Boolean(thinkingSignature) && thinkingSignature !== "reasoning_content";
755
- if (block.thinking.trim().length === 0 && !hasNativeThinkingSignature) continue;
756
- if (!thinkingSignature && !allowEmptySignature) blocks.push({
757
- type: "text",
758
- text: sanitizeSurrogates(block.thinking)
759
- });
760
- else {
761
- if (thinkingSignature === "reasoning_content") continue;
762
- blocks.push({
763
- type: "thinking",
764
- thinking: block.thinking,
765
- signature: thinkingSignature ?? ""
766
- });
767
- }
768
- } else if (block.type === "toolCall") blocks.push({
769
- type: "tool_use",
770
- id: block.id,
771
- name: isOAuthTokenValue ? toClaudeCodeToolName(block.name) : block.name,
772
- input: block.arguments ?? {}
773
- });
774
- if (blocks.length === 0 && omittedThinking) blocks.push({
775
- type: "text",
776
- text: ANTHROPIC_OMITTED_REASONING_TEXT
777
- });
778
- if (blocks.length === 0) continue;
779
- params.push({
780
- role: "assistant",
781
- content: blocks
782
- });
783
- } else if (msg.role === "toolResult") {
784
- const toolResults = [];
785
- toolResults.push({
786
- type: "tool_result",
787
- tool_use_id: msg.toolCallId,
788
- content: await convertContentBlocks(msg.content, msg.isError, imageBudget),
789
- is_error: msg.isError
790
- });
791
- let j = i + 1;
792
- while (j < transformedMessages.length) {
793
- const nextMsg = transformedMessages.at(j);
794
- if (nextMsg?.role !== "toolResult") break;
795
- toolResults.push({
796
- type: "tool_result",
797
- tool_use_id: nextMsg.toolCallId,
798
- content: await convertContentBlocks(nextMsg.content, nextMsg.isError, imageBudget),
799
- is_error: nextMsg.isError
800
- });
801
- j++;
802
- }
803
- i = j - 1;
804
- params.push({
805
- role: "user",
806
- content: toolResults
807
- });
808
- }
809
- }
810
- if (cacheControl) applyAnthropicCacheControlToMessages(params, cacheControl, messageCacheControlLimit, cacheBreakpointOptOutParamIndexes);
811
- return params;
812
- }
813
- function buildAnthropicSystemBlocks(systemPrompt, isOAuthTokenResult, cacheControl) {
814
- const blocks = [];
815
- if (isOAuthTokenResult) {
816
- blocks.push({
817
- type: "text",
818
- text: ANTHROPIC_CLAUDE_CODE_BILLING_SYSTEM_BLOCK
819
- });
820
- blocks.push({
821
- type: "text",
822
- text: "You are Claude Code, Anthropic's official CLI for Claude.",
823
- ...cacheControl ? { cache_control: cacheControl } : {}
824
- });
825
- }
826
- if (systemPrompt) blocks.push(...buildSystemPromptBlocks(systemPrompt, cacheControl));
827
- return blocks.length > 0 ? blocks : void 0;
828
- }
829
- function buildSystemPromptBlocks(systemPrompt, cacheControl) {
830
- if (!cacheControl) return [{
831
- type: "text",
832
- text: sanitizeSurrogates(stripSystemPromptCacheBoundary(systemPrompt))
833
- }];
834
- const split = splitSystemPromptCacheBoundary(systemPrompt);
835
- if (!split) return [{
836
- type: "text",
837
- text: sanitizeSurrogates(systemPrompt),
838
- cache_control: cacheControl
839
- }];
840
- const blocks = [];
841
- if (split.stablePrefix) blocks.push({
842
- type: "text",
843
- text: sanitizeSurrogates(split.stablePrefix),
844
- cache_control: cacheControl
845
- });
846
- if (split.dynamicSuffix) blocks.push({
847
- type: "text",
848
- text: sanitizeSurrogates(split.dynamicSuffix)
849
- });
850
- return blocks.length > 0 ? blocks : [{
851
- type: "text",
852
- text: ""
853
- }];
854
- }
855
- function countNativeCacheControlMarkers(blocks) {
856
- if (!Array.isArray(blocks)) return 0;
857
- let count = 0;
858
- for (const block of blocks) if (block && typeof block === "object" && "cache_control" in block) count += 1;
859
- return count;
860
- }
861
- function shouldUseFineGrainedToolStreamingBeta(model, context) {
862
- return Boolean(context.tools?.length) && !getAnthropicCompat(model).supportsEagerToolInputStreaming;
863
- }
864
- function convertTools(tools, isOAuthTokenLocal, supportsEagerToolInputStreaming, cacheControl) {
865
- const projection = projectAnthropicTools(tools, (name) => isOAuthTokenLocal ? toClaudeCodeToolName(name) : name);
866
- const convertedTools = [];
867
- for (const [index, tool] of projection.tools.entries()) {
868
- const convertedTool = {
869
- name: tool.wireName,
870
- description: tool.description,
871
- input_schema: tool.inputSchema
872
- };
873
- if (supportsEagerToolInputStreaming) convertedTool.eager_input_streaming = true;
874
- if (cacheControl && index === projection.tools.length - 1) convertedTool.cache_control = cacheControl;
875
- convertedTools.push(convertedTool);
876
- }
877
- return {
878
- projection,
879
- tools: convertedTools
880
- };
881
- }
882
- //#endregion
883
- export { streamAnthropic as n, streamSimpleAnthropic as r, anthropic_exports as t };