pagegraph 0.12.0 → 0.14.0

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 (160) hide show
  1. package/README.md +325 -66
  2. package/dist/anthropic-messages-TqKpKmfW.js +1067 -0
  3. package/dist/anthropic-messages-TqKpKmfW.js.map +1 -0
  4. package/dist/audit.d.ts +4 -2
  5. package/dist/audit.js +5 -5
  6. package/dist/audit.js.map +1 -1
  7. package/dist/azure-openai-responses-DJjBLwoI.js +231 -0
  8. package/dist/azure-openai-responses-DJjBLwoI.js.map +1 -0
  9. package/dist/build-only/audit.js +1 -1
  10. package/dist/build-only/claims.d.ts +1 -0
  11. package/dist/build-only/claims.js +6 -0
  12. package/dist/build-only/claims.js.map +1 -0
  13. package/dist/build-only/config.js +1 -1
  14. package/dist/build-only/oxlint.d.ts +1 -0
  15. package/dist/build-only/oxlint.js +6 -0
  16. package/dist/build-only/oxlint.js.map +1 -0
  17. package/dist/build-only/tanstack-start.js +1 -1
  18. package/dist/build-only/vite.js +1 -1
  19. package/dist/{checks-uZk5Em9A.js → checks-BS-aDXB_.js} +2 -2
  20. package/dist/checks-BS-aDXB_.js.map +1 -0
  21. package/dist/claims-Bch7Lxlo.d.ts +92 -0
  22. package/dist/claims-Bv7voeEV.js +431 -0
  23. package/dist/claims-Bv7voeEV.js.map +1 -0
  24. package/dist/claims.d.ts +94 -0
  25. package/dist/claims.js +2 -0
  26. package/dist/cli.js +17607 -43387
  27. package/dist/cli.js.map +1 -1
  28. package/dist/cloudflare-workers-ai-system-one-f3ZrvNYZ.js +41 -0
  29. package/dist/cloudflare-workers-ai-system-one-f3ZrvNYZ.js.map +1 -0
  30. package/dist/config.d.ts +9 -29
  31. package/dist/config.js +2 -2
  32. package/dist/config.js.map +1 -1
  33. package/dist/{content-kcEnQdfi.js → content-CHd0X4s6.js} +2 -2
  34. package/dist/{content-kcEnQdfi.js.map → content-CHd0X4s6.js.map} +1 -1
  35. package/dist/{content-B1cPtL8b.d.ts → content-DgNr7apS.d.ts} +4 -5
  36. package/dist/declare-D5o7hwmv.js.map +1 -1
  37. package/dist/diagnostics-Wt5faNDM.js +108 -0
  38. package/dist/diagnostics-Wt5faNDM.js.map +1 -0
  39. package/dist/dist-B6zg_Z3Z.js +4794 -0
  40. package/dist/dist-B6zg_Z3Z.js.map +1 -0
  41. package/dist/document-CztEu3Vd.d.ts +109 -0
  42. package/dist/document-Dvemcv7V.js +379 -0
  43. package/dist/document-Dvemcv7V.js.map +1 -0
  44. package/dist/env-api-keys-C-OA0yM-.js +124 -0
  45. package/dist/env-api-keys-C-OA0yM-.js.map +1 -0
  46. package/dist/error-body-CyiejW4b.js +103 -0
  47. package/dist/error-body-CyiejW4b.js.map +1 -0
  48. package/dist/facts-1OKclPOk.js +115 -0
  49. package/dist/facts-1OKclPOk.js.map +1 -0
  50. package/dist/github-copilot-headers-CEpMOpQF.js +24 -0
  51. package/dist/github-copilot-headers-CEpMOpQF.js.map +1 -0
  52. package/dist/google-generative-ai-BxABKIKO.js +330 -0
  53. package/dist/google-generative-ai-BxABKIKO.js.map +1 -0
  54. package/dist/google-shared-0gpM2jFi.js +19471 -0
  55. package/dist/google-shared-0gpM2jFi.js.map +1 -0
  56. package/dist/google-vertex-D8Eb5cbu.js +376 -0
  57. package/dist/google-vertex-D8Eb5cbu.js.map +1 -0
  58. package/dist/{declare-DVgdEdOL.d.ts → graph-D1PIndsC.d.ts} +117 -6
  59. package/dist/{graph-Bcsourlv.js → graph-DMNOLXLu.js} +23 -13
  60. package/dist/graph-DMNOLXLu.js.map +1 -0
  61. package/dist/hash-Dp7EzZUo.js +18 -0
  62. package/dist/hash-Dp7EzZUo.js.map +1 -0
  63. package/dist/headers-BRNMVpzu.js +19 -0
  64. package/dist/headers-BRNMVpzu.js.map +1 -0
  65. package/dist/index-C5w9ripz.d.ts +204 -0
  66. package/dist/index.d.ts +6 -160
  67. package/dist/index.js +37 -5
  68. package/dist/index.js.map +1 -1
  69. package/dist/inline-BbS93GAT.js +682 -0
  70. package/dist/inline-BbS93GAT.js.map +1 -0
  71. package/dist/json-parse-C10znB7l.js +383 -0
  72. package/dist/json-parse-C10znB7l.js.map +1 -0
  73. package/dist/llms-Dhr_5u2O.js +19 -0
  74. package/dist/llms-Dhr_5u2O.js.map +1 -0
  75. package/dist/markdown-C6dRE9zD.js +168 -0
  76. package/dist/markdown-C6dRE9zD.js.map +1 -0
  77. package/dist/markdown-path-lJB9BAVZ.js +6 -0
  78. package/dist/markdown-path-lJB9BAVZ.js.map +1 -0
  79. package/dist/{message-DT_CjUdt.js → message-CuBjgZ74.js} +2 -2
  80. package/dist/{message-DT_CjUdt.js.map → message-CuBjgZ74.js.map} +1 -1
  81. package/dist/mistral-conversations-CvaqBWjR.js +690 -0
  82. package/dist/mistral-conversations-CvaqBWjR.js.map +1 -0
  83. package/dist/models-DcT5qOEL.js +1203 -0
  84. package/dist/models-DcT5qOEL.js.map +1 -0
  85. package/dist/node-Ccvru9GE.js +26 -0
  86. package/dist/node-Ccvru9GE.js.map +1 -0
  87. package/dist/node-MEosBOF2.js +2403 -0
  88. package/dist/node-MEosBOF2.js.map +1 -0
  89. package/dist/openai-BCBEd2eO.js +17350 -0
  90. package/dist/openai-BCBEd2eO.js.map +1 -0
  91. package/dist/openai-codex-responses-vJqxeeRC.js +1268 -0
  92. package/dist/openai-codex-responses-vJqxeeRC.js.map +1 -0
  93. package/dist/openai-completions-Cb_fRAbI.js +989 -0
  94. package/dist/openai-completions-Cb_fRAbI.js.map +1 -0
  95. package/dist/openai-prompt-cache-Bc6qNWt0.js +10 -0
  96. package/dist/openai-prompt-cache-Bc6qNWt0.js.map +1 -0
  97. package/dist/openai-responses-sDuh82G5.js +268 -0
  98. package/dist/openai-responses-sDuh82G5.js.map +1 -0
  99. package/dist/openai-responses-shared-mhuo1Jov.js +599 -0
  100. package/dist/openai-responses-shared-mhuo1Jov.js.map +1 -0
  101. package/dist/openrouter-images-CRmBkzpX.js +127 -0
  102. package/dist/openrouter-images-CRmBkzpX.js.map +1 -0
  103. package/dist/oxlint.d.ts +58 -0
  104. package/dist/oxlint.js +202 -0
  105. package/dist/oxlint.js.map +1 -0
  106. package/dist/page-heads-BfjWQvau.d.ts +108 -0
  107. package/dist/{page-heads-6y-CARRQ.js → page-heads-BgbaIjj9.js} +3 -3
  108. package/dist/page-heads-BgbaIjj9.js.map +1 -0
  109. package/dist/pi-Bvw6J0gh.js +56795 -0
  110. package/dist/pi-Bvw6J0gh.js.map +1 -0
  111. package/dist/pi-messages-CejiVYvO.js +308 -0
  112. package/dist/pi-messages-CejiVYvO.js.map +1 -0
  113. package/dist/{projections-DeEFe7XT.d.ts → projections-Bk-qOOsR.d.ts} +2 -2
  114. package/dist/provider-env-t38GK5FF.js +39 -0
  115. package/dist/provider-env-t38GK5FF.js.map +1 -0
  116. package/dist/provider-retry-DzKoh1X7.js +80 -0
  117. package/dist/provider-retry-DzKoh1X7.js.map +1 -0
  118. package/dist/react.d.ts +3 -2
  119. package/dist/react.js +2 -1
  120. package/dist/react.js.map +1 -1
  121. package/dist/rolldown-runtime-B-lAHAz2.js +37 -0
  122. package/dist/sanitize-unicode-Ds14l9Om.js +28 -0
  123. package/dist/sanitize-unicode-Ds14l9Om.js.map +1 -0
  124. package/dist/sdk-C9_wiO6w.js +12503 -0
  125. package/dist/sdk-C9_wiO6w.js.map +1 -0
  126. package/dist/state-BuJP_3Lr.js +28102 -0
  127. package/dist/state-BuJP_3Lr.js.map +1 -0
  128. package/dist/system-one-shared-Dl10ZF7Z.js +167 -0
  129. package/dist/system-one-shared-Dl10ZF7Z.js.map +1 -0
  130. package/dist/tanstack-start/index.d.ts +29 -13
  131. package/dist/tanstack-start/index.js +391 -42
  132. package/dist/tanstack-start/index.js.map +1 -1
  133. package/dist/tanstack-start/markdown.d.ts +12 -0
  134. package/dist/tanstack-start/markdown.js +149 -0
  135. package/dist/tanstack-start/markdown.js.map +1 -0
  136. package/dist/tanstack-start/prerender-worker.d.ts +2 -0
  137. package/dist/tanstack-start/prerender-worker.js +7 -0
  138. package/dist/tanstack-start/prerender-worker.js.map +1 -0
  139. package/dist/tanstack-start/react.d.ts +7 -0
  140. package/dist/tanstack-start/react.js +12 -0
  141. package/dist/tanstack-start/react.js.map +1 -0
  142. package/dist/tanstack-start/server.d.ts +9 -3
  143. package/dist/tanstack-start/server.js +26 -2
  144. package/dist/tanstack-start/server.js.map +1 -1
  145. package/dist/transform-messages-BLJ8EfK6.js +468 -0
  146. package/dist/transform-messages-BLJ8EfK6.js.map +1 -0
  147. package/dist/typesafe-system-one-CwEWMV8P.js +25 -0
  148. package/dist/typesafe-system-one-CwEWMV8P.js.map +1 -0
  149. package/dist/{vite-graph-loader-01p1WxEq.js → vite-graph-loader-CsGiYNWE.js} +6 -5
  150. package/dist/vite-graph-loader-CsGiYNWE.js.map +1 -0
  151. package/dist/vite-graph-loader-DZCwejuJ.d.ts +133 -0
  152. package/package.json +47 -10
  153. package/dist/checks-uZk5Em9A.js.map +0 -1
  154. package/dist/graph-Bcsourlv.js.map +0 -1
  155. package/dist/graph-BxCY90vq.d.ts +0 -104
  156. package/dist/graph-CBIY71w6.d.ts +0 -57
  157. package/dist/page-heads-6y-CARRQ.js.map +0 -1
  158. package/dist/page-heads-DNkjMUEN.d.ts +0 -21
  159. package/dist/vite-graph-loader-01p1WxEq.js.map +0 -1
  160. package/dist/vite-graph-loader-Btgjz5RH.d.ts +0 -56
@@ -0,0 +1,1067 @@
1
+ import { t as Anthropic } from "./sdk-C9_wiO6w.js";
2
+ import { t as getProviderEnvValue } from "./provider-env-t38GK5FF.js";
3
+ import { c as ANTHROPIC_WORKSPACE_ID_ENV, i as ANTHROPIC_IDENTITY_TOKEN_FILE_ENV, o as ANTHROPIC_ORGANIZATION_ID_ENV, r as ANTHROPIC_FEDERATION_RULE_ID_ENV, s as ANTHROPIC_SERVICE_ACCOUNT_ID_ENV } from "./env-api-keys-C-OA0yM-.js";
4
+ import { a as AssistantMessageEventStream, t as appendAssistantMessageDiagnostic } from "./diagnostics-Wt5faNDM.js";
5
+ import { C as renderSystemMessageUpdate, S as getSystemMessageText, d as getCurrentTools, f as getDeclaredTools, g as hasToolRedefinitions, p as getInitialSystemMessage, t as calculateCost, v as resolveTranscript } from "./models-DcT5qOEL.js";
6
+ import { t as headersToRecord } from "./headers-BRNMVpzu.js";
7
+ import { n as parseStreamingJson, t as parseJsonWithRepair } from "./json-parse-C10znB7l.js";
8
+ import { f as resolveJsonSchemaStrictSampling, i as clampMaxTokensToContext, n as adjustMaxTokensForThinking, p as getPiUserAgent, r as buildBaseOptions, t as transformMessages, u as getJsonSchemaToolParameters } from "./transform-messages-BLJ8EfK6.js";
9
+ import { t as retryProviderRequest } from "./provider-retry-DzKoh1X7.js";
10
+ import { t as sanitizeSurrogates } from "./sanitize-unicode-Ds14l9Om.js";
11
+ import { n as hasCopilotVisionInput, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-CEpMOpQF.js";
12
+ //#region node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.js
13
+ /**
14
+ * Resolve cache retention preference.
15
+ * Defaults to "short" and uses PI_CACHE_RETENTION for backward compatibility.
16
+ */
17
+ function resolveCacheRetention(cacheRetention, env) {
18
+ if (cacheRetention) return cacheRetention;
19
+ if (getProviderEnvValue("PI_CACHE_RETENTION", env) === "long") return "long";
20
+ return "short";
21
+ }
22
+ function getCacheControl(model, cacheRetention, env) {
23
+ const retention = resolveCacheRetention(cacheRetention, env);
24
+ if (retention === "none") return { retention };
25
+ const ttl = retention === "long" && getAnthropicCompat(model).supportsLongCacheRetention ? "1h" : void 0;
26
+ return {
27
+ retention,
28
+ cacheControl: {
29
+ type: "ephemeral",
30
+ ...ttl && { ttl }
31
+ }
32
+ };
33
+ }
34
+ const claudeCodeVersion = "2.1.280";
35
+ const ccToolLookup = new Map([
36
+ "Read",
37
+ "Write",
38
+ "Edit",
39
+ "Bash",
40
+ "Grep",
41
+ "Glob",
42
+ "AskUserQuestion",
43
+ "EnterPlanMode",
44
+ "ExitPlanMode",
45
+ "KillShell",
46
+ "NotebookEdit",
47
+ "Skill",
48
+ "Task",
49
+ "TaskOutput",
50
+ "TodoWrite",
51
+ "WebFetch",
52
+ "WebSearch"
53
+ ].map((t) => [t.toLowerCase(), t]));
54
+ const toClaudeCodeName = (name) => ccToolLookup.get(name.toLowerCase()) ?? name;
55
+ const fromClaudeCodeName = (name, tools) => {
56
+ if (tools && tools.length > 0) {
57
+ const lowerName = name.toLowerCase();
58
+ const matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);
59
+ if (matchedTool) return matchedTool.name;
60
+ }
61
+ return name;
62
+ };
63
+ /**
64
+ * Convert content blocks to Anthropic API format
65
+ */
66
+ function convertContentBlocks(content) {
67
+ if (!content.some((c) => c.type === "image")) return sanitizeSurrogates(content.map((c) => c.text).join("\n"));
68
+ const blocks = content.map((block) => {
69
+ if (block.type === "text") return {
70
+ type: "text",
71
+ text: sanitizeSurrogates(block.text)
72
+ };
73
+ return {
74
+ type: "image",
75
+ source: {
76
+ type: "base64",
77
+ media_type: block.mimeType,
78
+ data: block.data
79
+ }
80
+ };
81
+ });
82
+ if (!blocks.some((b) => b.type === "text")) blocks.unshift({
83
+ type: "text",
84
+ text: "(see attached image)"
85
+ });
86
+ return blocks;
87
+ }
88
+ const FINE_GRAINED_TOOL_STREAMING_BETA = "fine-grained-tool-streaming-2025-05-14";
89
+ const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
90
+ const SERVER_SIDE_FALLBACK_BETA = "server-side-fallback-2026-07-01";
91
+ const MID_CONVERSATION_OUTPUT_CONFIG_BETA = "mid-conversation-output-config-2026-07-01";
92
+ const THINKING_BINDING_CONTROLS_BETA = "thinking-binding-controls-2026-08-01";
93
+ const MID_CONVERSATION_TOOL_CHANGES_BETA = "mid-conversation-tool-changes-2026-07-01";
94
+ /**
95
+ * Stable deferred tool declared whenever native tool changes are in use. Anthropic adds
96
+ * hidden prompt scaffolding as soon as any tool has `defer_loading`; declaring this
97
+ * placeholder from the first request keeps that scaffolding in the cached prefix, so the
98
+ * first real late tool does not invalidate the cache (measured: full miss without it).
99
+ * It is never activated and the model cannot see it.
100
+ */
101
+ const DEFERRED_TOOL_PLACEHOLDER = {
102
+ name: "__pi_deferred_placeholder__",
103
+ description: "Reserved placeholder. Never available. Never call this.",
104
+ input_schema: {
105
+ type: "object",
106
+ properties: {},
107
+ required: []
108
+ },
109
+ defer_loading: true
110
+ };
111
+ function shouldUseServerSideFallbackBeta(model) {
112
+ return (model.compat?.allowedFallbackModels?.length ?? 0) > 0;
113
+ }
114
+ function getAnthropicCompat(model) {
115
+ const isOpenRouter = model.provider === "openrouter" || model.baseUrl.includes("openrouter.ai");
116
+ return {
117
+ supportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? true,
118
+ supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,
119
+ sendSessionAffinityHeaders: model.compat?.sendSessionAffinityHeaders ?? isOpenRouter,
120
+ sessionAffinityFormat: model.compat?.sessionAffinityFormat ?? (isOpenRouter ? "openrouter" : void 0),
121
+ supportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? true,
122
+ supportsTemperature: model.compat?.supportsTemperature ?? true,
123
+ allowEmptySignature: model.compat?.allowEmptySignature ?? false,
124
+ supportsStrictTools: model.compat?.supportsStrictTools ?? false,
125
+ supportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false,
126
+ supportsMidConvoToolChanges: model.compat?.supportsMidConvoToolChanges ?? false
127
+ };
128
+ }
129
+ function mergeHeaders(...headerSources) {
130
+ const merged = {};
131
+ for (const headers of headerSources) if (headers) Object.assign(merged, headers);
132
+ return merged;
133
+ }
134
+ function mergeClientHeaders(...headerSources) {
135
+ return mergeHeaders({ "User-Agent": getPiUserAgent() }, ...headerSources);
136
+ }
137
+ function hasHeader(headers, name) {
138
+ if (!headers) return false;
139
+ const expected = name.toLowerCase();
140
+ for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === expected && value !== null && value.trim().length > 0) return true;
141
+ return false;
142
+ }
143
+ function hasRequestAuth(apiKey, headers) {
144
+ return !!apiKey || hasHeader(headers, "authorization") || hasHeader(headers, "x-api-key") || hasHeader(headers, "cf-aig-authorization");
145
+ }
146
+ function assertRequestAuth(provider, apiKey, headers) {
147
+ if (!hasRequestAuth(apiKey, headers)) throw new Error(`No API key for provider: ${provider}`);
148
+ }
149
+ /**
150
+ * Anthropic SDK client that never runs the SDK's own credential chain
151
+ * (ANTHROPIC_PROFILE config files, federation env vars). Without this, every
152
+ * client built with `apiKey: null, authToken: null` for header-owned auth would
153
+ * also resolve and exchange SDK credentials behind pi's auth resolver.
154
+ */
155
+ var PiAnthropic = class extends Anthropic {
156
+ _shouldResolveDefaultCredentials() {
157
+ return false;
158
+ }
159
+ };
160
+ /**
161
+ * Workload identity federation config from the ANTHROPIC_* variables the
162
+ * Anthropic SDK documents; the SDK performs the token exchange and refresh.
163
+ * Only for the anthropic provider, since the exchange is an Anthropic API
164
+ * endpoint, and only when no key or auth header was resolved.
165
+ */
166
+ function getAnthropicFederation(model, apiKey, headers, env) {
167
+ if (model.provider !== "anthropic" || hasRequestAuth(apiKey, headers)) return void 0;
168
+ const federationRuleId = getProviderEnvValue(ANTHROPIC_FEDERATION_RULE_ID_ENV, env);
169
+ const organizationId = getProviderEnvValue(ANTHROPIC_ORGANIZATION_ID_ENV, env);
170
+ const identityTokenFile = getProviderEnvValue(ANTHROPIC_IDENTITY_TOKEN_FILE_ENV, env);
171
+ if (!federationRuleId || !organizationId || !identityTokenFile) return void 0;
172
+ return {
173
+ organization_id: organizationId,
174
+ workspace_id: getProviderEnvValue(ANTHROPIC_WORKSPACE_ID_ENV, env),
175
+ authentication: {
176
+ type: "oidc_federation",
177
+ federation_rule_id: federationRuleId,
178
+ service_account_id: getProviderEnvValue(ANTHROPIC_SERVICE_ACCOUNT_ID_ENV, env),
179
+ identity_token: {
180
+ source: "file",
181
+ path: identityTokenFile
182
+ }
183
+ }
184
+ };
185
+ }
186
+ /**
187
+ * The SDK caches the federated access token per client, but pi creates a client
188
+ * per request. Keep one client for the current federation config and fetch, and
189
+ * clone it per request with `withOptions()`, which shares the token cache.
190
+ */
191
+ let federationClient;
192
+ const ANTHROPIC_MESSAGE_EVENTS = /* @__PURE__ */ new Set([
193
+ "message_start",
194
+ "message_delta",
195
+ "message_stop",
196
+ "content_block_start",
197
+ "content_block_delta",
198
+ "content_block_stop"
199
+ ]);
200
+ function flushSseEvent(state) {
201
+ if (!state.event && state.data.length === 0) return null;
202
+ const event = {
203
+ event: state.event,
204
+ data: state.data.join("\n"),
205
+ raw: [...state.raw]
206
+ };
207
+ state.event = null;
208
+ state.data = [];
209
+ state.raw = [];
210
+ return event;
211
+ }
212
+ function decodeSseLine(line, state) {
213
+ if (line === "") return flushSseEvent(state);
214
+ state.raw.push(line);
215
+ if (line.startsWith(":")) return null;
216
+ const delimiterIndex = line.indexOf(":");
217
+ const fieldName = delimiterIndex === -1 ? line : line.slice(0, delimiterIndex);
218
+ let value = delimiterIndex === -1 ? "" : line.slice(delimiterIndex + 1);
219
+ if (value.startsWith(" ")) value = value.slice(1);
220
+ if (fieldName === "event") state.event = value;
221
+ else if (fieldName === "data") state.data.push(value);
222
+ return null;
223
+ }
224
+ function nextLineBreakIndex(text) {
225
+ const carriageReturnIndex = text.indexOf("\r");
226
+ const newlineIndex = text.indexOf("\n");
227
+ if (carriageReturnIndex === -1) return newlineIndex;
228
+ if (newlineIndex === -1) return carriageReturnIndex;
229
+ return Math.min(carriageReturnIndex, newlineIndex);
230
+ }
231
+ function consumeLine(text) {
232
+ const lineBreakIndex = nextLineBreakIndex(text);
233
+ if (lineBreakIndex === -1) return null;
234
+ let nextIndex = lineBreakIndex + 1;
235
+ if (text[lineBreakIndex] === "\r" && text[nextIndex] === "\n") nextIndex += 1;
236
+ return {
237
+ line: text.slice(0, lineBreakIndex),
238
+ rest: text.slice(nextIndex)
239
+ };
240
+ }
241
+ async function* iterateSseMessages(body, signal) {
242
+ const reader = body.getReader();
243
+ const decoder = new TextDecoder();
244
+ const state = {
245
+ event: null,
246
+ data: [],
247
+ raw: []
248
+ };
249
+ let buffer = "";
250
+ try {
251
+ while (true) {
252
+ if (signal?.aborted) throw new Error("Request was aborted");
253
+ const { value, done } = await reader.read();
254
+ if (done) break;
255
+ buffer += decoder.decode(value, { stream: true });
256
+ let consumed = consumeLine(buffer);
257
+ while (consumed) {
258
+ buffer = consumed.rest;
259
+ const event = decodeSseLine(consumed.line, state);
260
+ if (event) yield event;
261
+ consumed = consumeLine(buffer);
262
+ }
263
+ }
264
+ buffer += decoder.decode();
265
+ let consumed = consumeLine(buffer);
266
+ while (consumed) {
267
+ buffer = consumed.rest;
268
+ const event = decodeSseLine(consumed.line, state);
269
+ if (event) yield event;
270
+ consumed = consumeLine(buffer);
271
+ }
272
+ if (buffer.length > 0) {
273
+ const event = decodeSseLine(buffer, state);
274
+ if (event) yield event;
275
+ }
276
+ const trailingEvent = flushSseEvent(state);
277
+ if (trailingEvent) yield trailingEvent;
278
+ } finally {
279
+ reader.releaseLock();
280
+ }
281
+ }
282
+ async function* iterateAnthropicEvents(response, signal) {
283
+ if (!response.body) throw new Error("Attempted to iterate over an Anthropic response with no body");
284
+ let sawMessageStart = false;
285
+ let sawMessageEnd = false;
286
+ for await (const sse of iterateSseMessages(response.body, signal)) {
287
+ if (sse.event === "error") throw new Error(sse.data);
288
+ if (!ANTHROPIC_MESSAGE_EVENTS.has(sse.event ?? "")) continue;
289
+ try {
290
+ const event = parseJsonWithRepair(sse.data);
291
+ if (event.type === "message_start") sawMessageStart = true;
292
+ else if (event.type === "message_stop") sawMessageEnd = true;
293
+ yield event;
294
+ } catch (error) {
295
+ const message = error instanceof Error ? error.message : String(error);
296
+ throw new Error(`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join("\\n")}`);
297
+ }
298
+ }
299
+ if (sawMessageStart && !sawMessageEnd) throw new Error("Anthropic stream ended before message_stop");
300
+ }
301
+ const stream = (model, context, options) => {
302
+ const stream = new AssistantMessageEventStream();
303
+ const normalizedContext = resolveTranscript(context, getAnthropicCompat(model).supportsMidConvoSystemMessages);
304
+ const currentTools = getCurrentTools(normalizedContext.messages);
305
+ (async () => {
306
+ const providerThinkingLevel = model.compat?.supportsMidConvoEffort ? options?.effort ?? "high" : void 0;
307
+ const output = {
308
+ role: "assistant",
309
+ content: [],
310
+ api: model.api,
311
+ provider: model.provider,
312
+ model: model.id,
313
+ ...providerThinkingLevel === void 0 ? {} : { providerThinkingLevel },
314
+ usage: {
315
+ input: 0,
316
+ output: 0,
317
+ cacheRead: 0,
318
+ cacheWrite: 0,
319
+ totalTokens: 0,
320
+ cost: {
321
+ input: 0,
322
+ output: 0,
323
+ cacheRead: 0,
324
+ cacheWrite: 0,
325
+ total: 0
326
+ }
327
+ },
328
+ stopReason: "pending",
329
+ timestamp: Date.now()
330
+ };
331
+ try {
332
+ let client;
333
+ let isOAuth;
334
+ let usageModel = model;
335
+ let inputTransformations;
336
+ if (options?.client) {
337
+ client = options.client;
338
+ isOAuth = false;
339
+ } else {
340
+ const apiKey = options?.apiKey;
341
+ const federation = getAnthropicFederation(model, apiKey, options?.headers, options?.env);
342
+ if (!federation) assertRequestAuth(model.provider, apiKey, options?.headers);
343
+ let copilotDynamicHeaders;
344
+ if (model.provider === "github-copilot") {
345
+ const hasImages = hasCopilotVisionInput(normalizedContext.messages);
346
+ copilotDynamicHeaders = buildCopilotDynamicHeaders({
347
+ messages: normalizedContext.messages,
348
+ hasImages
349
+ });
350
+ }
351
+ const cacheSessionId = resolveCacheRetention(options?.cacheRetention, options?.env) === "none" ? void 0 : options?.sessionId;
352
+ const created = createClient(model, apiKey, options?.headers, options?.fetch, copilotDynamicHeaders, cacheSessionId, federation);
353
+ client = created.client;
354
+ isOAuth = created.isOAuthToken;
355
+ }
356
+ let params = buildParams(model, normalizedContext, isOAuth, options);
357
+ const nextParams = await options?.onPayload?.(params, model);
358
+ if (nextParams !== void 0) params = {
359
+ ...nextParams,
360
+ stream: true
361
+ };
362
+ const requestOptions = {
363
+ ...options?.signal ? { signal: options.signal } : {},
364
+ ...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
365
+ maxRetries: 0
366
+ };
367
+ const response = await retryProviderRequest(() => client.beta.messages.create(params, requestOptions).asResponse(), {
368
+ maxRetries: options?.maxRetries,
369
+ maxRetryDelayMs: options?.maxRetryDelayMs,
370
+ signal: options?.signal
371
+ });
372
+ await options?.onResponse?.({
373
+ status: response.status,
374
+ headers: headersToRecord(response.headers)
375
+ }, model);
376
+ stream.push({
377
+ type: "start",
378
+ partial: output
379
+ });
380
+ const blocks = output.content;
381
+ for await (const event of iterateAnthropicEvents(response, options?.signal)) {
382
+ await options?.onProviderStreamEvent?.(event, model);
383
+ if (event.type === "message_start") {
384
+ output.responseId = event.message.id;
385
+ const transformations = event.message.input_transformations;
386
+ if (Array.isArray(transformations)) inputTransformations = transformations;
387
+ const responseModel = event.message.model;
388
+ if (responseModel !== model.id) output.responseModel = responseModel;
389
+ const fallbackCost = responseModel === model.id ? void 0 : model.compat?.allowedFallbackModels?.find((fallback) => fallback.provider === model.provider && fallback.model === responseModel)?.cost;
390
+ usageModel = fallbackCost ? {
391
+ ...model,
392
+ id: responseModel,
393
+ cost: fallbackCost
394
+ } : model;
395
+ output.usage.input = event.message.usage.input_tokens || 0;
396
+ output.usage.output = event.message.usage.output_tokens || 0;
397
+ output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;
398
+ output.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;
399
+ output.usage.cacheWrite1h = event.message.usage.cache_creation?.ephemeral_1h_input_tokens || 0;
400
+ output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
401
+ calculateCost(usageModel, output.usage);
402
+ } else if (event.type === "content_block_start") {
403
+ if (event.content_block.type === "fallback") {
404
+ if (output.content.length > 0) throw new Error("Anthropic performed an unsupported mid-output model fallback");
405
+ continue;
406
+ }
407
+ if (event.content_block.type === "text") {
408
+ const block = {
409
+ type: "text",
410
+ text: event.content_block.text ?? "",
411
+ index: event.index
412
+ };
413
+ output.content.push(block);
414
+ stream.push({
415
+ type: "text_start",
416
+ contentIndex: output.content.length - 1,
417
+ partial: output
418
+ });
419
+ } else if (event.content_block.type === "thinking") {
420
+ const block = {
421
+ type: "thinking",
422
+ thinking: event.content_block.thinking ?? "",
423
+ thinkingSignature: event.content_block.signature ?? "",
424
+ index: event.index
425
+ };
426
+ output.content.push(block);
427
+ stream.push({
428
+ type: "thinking_start",
429
+ contentIndex: output.content.length - 1,
430
+ partial: output
431
+ });
432
+ } else if (event.content_block.type === "redacted_thinking") {
433
+ const block = {
434
+ type: "thinking",
435
+ thinking: "[Reasoning redacted]",
436
+ thinkingSignature: event.content_block.data,
437
+ redacted: true,
438
+ index: event.index
439
+ };
440
+ output.content.push(block);
441
+ stream.push({
442
+ type: "thinking_start",
443
+ contentIndex: output.content.length - 1,
444
+ partial: output
445
+ });
446
+ } else if (event.content_block.type === "tool_use") {
447
+ const block = {
448
+ type: "toolCall",
449
+ id: event.content_block.id,
450
+ name: isOAuth ? fromClaudeCodeName(event.content_block.name, currentTools) : event.content_block.name,
451
+ arguments: event.content_block.input ?? {},
452
+ partialJson: "",
453
+ index: event.index
454
+ };
455
+ output.content.push(block);
456
+ stream.push({
457
+ type: "toolcall_start",
458
+ contentIndex: output.content.length - 1,
459
+ partial: output
460
+ });
461
+ }
462
+ } else if (event.type === "content_block_delta") {
463
+ if (event.delta.type === "text_delta") {
464
+ const index = blocks.findIndex((b) => b.index === event.index);
465
+ const block = blocks[index];
466
+ if (block && block.type === "text") {
467
+ block.text += event.delta.text;
468
+ stream.push({
469
+ type: "text_delta",
470
+ contentIndex: index,
471
+ delta: event.delta.text,
472
+ partial: output
473
+ });
474
+ }
475
+ } else if (event.delta.type === "thinking_delta") {
476
+ const index = blocks.findIndex((b) => b.index === event.index);
477
+ const block = blocks[index];
478
+ if (block && block.type === "thinking") {
479
+ block.thinking += event.delta.thinking;
480
+ stream.push({
481
+ type: "thinking_delta",
482
+ contentIndex: index,
483
+ delta: event.delta.thinking,
484
+ partial: output
485
+ });
486
+ }
487
+ } else if (event.delta.type === "input_json_delta") {
488
+ const index = blocks.findIndex((b) => b.index === event.index);
489
+ const block = blocks[index];
490
+ if (block && block.type === "toolCall") {
491
+ block.partialJson += event.delta.partial_json;
492
+ block.arguments = parseStreamingJson(block.partialJson);
493
+ stream.push({
494
+ type: "toolcall_delta",
495
+ contentIndex: index,
496
+ delta: event.delta.partial_json,
497
+ partial: output
498
+ });
499
+ }
500
+ } else if (event.delta.type === "signature_delta") {
501
+ const block = blocks[blocks.findIndex((b) => b.index === event.index)];
502
+ if (block && block.type === "thinking") {
503
+ block.thinkingSignature = block.thinkingSignature || "";
504
+ block.thinkingSignature += event.delta.signature;
505
+ }
506
+ }
507
+ } else if (event.type === "content_block_stop") {
508
+ const index = blocks.findIndex((b) => b.index === event.index);
509
+ const block = blocks[index];
510
+ if (block) {
511
+ delete block.index;
512
+ if (block.type === "text") stream.push({
513
+ type: "text_end",
514
+ contentIndex: index,
515
+ content: block.text,
516
+ partial: output
517
+ });
518
+ else if (block.type === "thinking") stream.push({
519
+ type: "thinking_end",
520
+ contentIndex: index,
521
+ content: block.thinking,
522
+ partial: output
523
+ });
524
+ else if (block.type === "toolCall") {
525
+ block.arguments = parseStreamingJson(block.partialJson);
526
+ delete block.partialJson;
527
+ stream.push({
528
+ type: "toolcall_end",
529
+ contentIndex: index,
530
+ toolCall: block,
531
+ partial: output
532
+ });
533
+ }
534
+ }
535
+ } else if (event.type === "message_delta") {
536
+ const transformations = event.input_transformations;
537
+ if (Array.isArray(transformations)) inputTransformations = transformations;
538
+ if (event.delta.stop_reason) {
539
+ output.rawStopReason = event.delta.stop_reason;
540
+ const stopReasonResult = mapStopReason(event.delta.stop_reason, event.delta.stop_details);
541
+ output.stopReason = stopReasonResult.stopReason;
542
+ if (stopReasonResult.errorMessage) output.errorMessage = stopReasonResult.errorMessage;
543
+ }
544
+ if (event.usage) {
545
+ if (event.usage.input_tokens != null) output.usage.input = event.usage.input_tokens;
546
+ if (event.usage.output_tokens != null) output.usage.output = event.usage.output_tokens;
547
+ if (event.usage.cache_read_input_tokens != null) output.usage.cacheRead = event.usage.cache_read_input_tokens;
548
+ if (event.usage.cache_creation_input_tokens != null) output.usage.cacheWrite = event.usage.cache_creation_input_tokens;
549
+ const cacheCreation = event.usage.cache_creation;
550
+ if (cacheCreation?.ephemeral_1h_input_tokens != null) output.usage.cacheWrite1h = cacheCreation.ephemeral_1h_input_tokens;
551
+ const thinkingTokens = event.usage.output_tokens_details?.thinking_tokens;
552
+ if (thinkingTokens != null) output.usage.reasoning = thinkingTokens;
553
+ }
554
+ output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
555
+ calculateCost(usageModel, output.usage);
556
+ }
557
+ }
558
+ if (options?.signal?.aborted) throw new Error("Request was aborted");
559
+ if (output.stopReason === "pending") throw new Error("Anthropic stream ended without a stop reason");
560
+ if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage || "An unknown error occurred");
561
+ if (inputTransformations && inputTransformations.length > 0) appendAssistantMessageDiagnostic(output, {
562
+ type: "anthropic_input_transformations",
563
+ timestamp: Date.now(),
564
+ details: { transformations: inputTransformations.map((transformation) => ({
565
+ type: transformation.type ?? void 0,
566
+ path: transformation.path ?? void 0,
567
+ reason: transformation.reason ?? void 0
568
+ })) }
569
+ });
570
+ stream.push({
571
+ type: "done",
572
+ reason: output.stopReason,
573
+ message: output
574
+ });
575
+ stream.end();
576
+ } catch (error) {
577
+ for (const block of output.content) {
578
+ delete block.index;
579
+ delete block.partialJson;
580
+ }
581
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
582
+ output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
583
+ stream.push({
584
+ type: "error",
585
+ reason: output.stopReason,
586
+ error: output
587
+ });
588
+ stream.end();
589
+ }
590
+ })();
591
+ return stream;
592
+ };
593
+ /**
594
+ * Map ThinkingLevel to Anthropic effort levels for adaptive thinking.
595
+ * Note: effort "max" is available on all adaptive-thinking Claude models, while native
596
+ * "xhigh" is only available on Opus 4.7/4.8, Sonnet 5, and Fable 5.
597
+ */
598
+ function mapThinkingLevelToEffort(model, level) {
599
+ const mapped = level ? model.thinkingLevelMap?.[level] : void 0;
600
+ if (typeof mapped === "string") return mapped;
601
+ switch (level) {
602
+ case "minimal":
603
+ case "low": return "low";
604
+ case "medium": return "medium";
605
+ case "high": return "high";
606
+ default: return "high";
607
+ }
608
+ }
609
+ const streamSimple = (model, context, options) => {
610
+ if (!getAnthropicFederation(model, options?.apiKey, options?.headers, options?.env)) assertRequestAuth(model.provider, options?.apiKey, options?.headers);
611
+ const base = {
612
+ ...buildBaseOptions(model, context, options, options?.apiKey),
613
+ toolChoice: options?.toolChoice
614
+ };
615
+ if (!options?.reasoning) return stream(model, context, {
616
+ ...base,
617
+ thinkingEnabled: false
618
+ });
619
+ if (model.compat?.forceAdaptiveThinking === true) {
620
+ const effort = mapThinkingLevelToEffort(model, options.reasoning);
621
+ return stream(model, context, {
622
+ ...base,
623
+ thinkingEnabled: true,
624
+ effort
625
+ });
626
+ }
627
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens, options.reasoning, options.thinkingBudgets);
628
+ const maxTokens = clampMaxTokensToContext(model, context, adjusted.maxTokens);
629
+ return stream(model, context, {
630
+ ...base,
631
+ maxTokens,
632
+ thinkingEnabled: true,
633
+ thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024))
634
+ });
635
+ };
636
+ function isOAuthToken(apiKey) {
637
+ return apiKey.includes("sk-ant-oat");
638
+ }
639
+ function createClient(model, apiKey, optionsHeaders, fetch, dynamicHeaders, sessionId, federation) {
640
+ if (model.provider === "github-copilot") return {
641
+ client: new PiAnthropic({
642
+ apiKey: null,
643
+ authToken: apiKey ?? null,
644
+ baseURL: model.baseUrl,
645
+ dangerouslyAllowBrowser: true,
646
+ fetch,
647
+ defaultHeaders: mergeClientHeaders({
648
+ accept: "application/json",
649
+ "anthropic-dangerous-direct-browser-access": "true"
650
+ }, model.headers, dynamicHeaders, optionsHeaders)
651
+ }),
652
+ isOAuthToken: false
653
+ };
654
+ if (apiKey && isOAuthToken(apiKey)) return {
655
+ client: new PiAnthropic({
656
+ apiKey: null,
657
+ authToken: apiKey,
658
+ baseURL: model.baseUrl,
659
+ dangerouslyAllowBrowser: true,
660
+ fetch,
661
+ defaultHeaders: mergeClientHeaders({
662
+ accept: "application/json",
663
+ "anthropic-dangerous-direct-browser-access": "true",
664
+ "user-agent": `claude-cli/${claudeCodeVersion}`,
665
+ "x-app": "cli"
666
+ }, model.headers, optionsHeaders)
667
+ }),
668
+ isOAuthToken: true
669
+ };
670
+ const compat = getAnthropicCompat(model);
671
+ const sessionAffinityHeaders = {};
672
+ if (sessionId && compat.sendSessionAffinityHeaders) {
673
+ const header = compat.sessionAffinityFormat === "openrouter" ? "x-session-id" : "x-session-affinity";
674
+ sessionAffinityHeaders[header] = sessionId;
675
+ }
676
+ const defaultHeaders = mergeClientHeaders({
677
+ accept: "application/json",
678
+ "anthropic-dangerous-direct-browser-access": "true"
679
+ }, sessionAffinityHeaders, model.headers, optionsHeaders);
680
+ if (federation) {
681
+ const key = JSON.stringify([model.baseUrl, federation]);
682
+ if (federationClient?.key !== key || federationClient.fetch !== fetch) federationClient = {
683
+ key,
684
+ fetch,
685
+ client: new PiAnthropic({
686
+ apiKey: null,
687
+ authToken: null,
688
+ config: federation,
689
+ baseURL: model.baseUrl,
690
+ dangerouslyAllowBrowser: true,
691
+ fetch
692
+ })
693
+ };
694
+ return {
695
+ client: federationClient.client.withOptions({ defaultHeaders }),
696
+ isOAuthToken: false
697
+ };
698
+ }
699
+ return {
700
+ client: new PiAnthropic({
701
+ apiKey: apiKey ?? null,
702
+ authToken: null,
703
+ baseURL: model.baseUrl,
704
+ dangerouslyAllowBrowser: true,
705
+ fetch,
706
+ defaultHeaders
707
+ }),
708
+ isOAuthToken: false
709
+ };
710
+ }
711
+ function getBetaFeatures(model, context, isOAuthToken, nativeToolChanges, options) {
712
+ let configuredFeatures;
713
+ for (const headers of [model.headers, options?.headers]) for (const [name, value] of Object.entries(headers ?? {})) if (name.toLowerCase() === "anthropic-beta") configuredFeatures = value;
714
+ if (configuredFeatures === null) return [];
715
+ if (configuredFeatures !== void 0) return [...new Set(configuredFeatures.split(",").map((feature) => feature.trim()).filter((feature) => feature.length > 0))];
716
+ const features = [];
717
+ if (isOAuthToken) features.push("claude-code-20250219", "oauth-2025-04-20");
718
+ if (shouldUseFineGrainedToolStreamingBeta(model, context)) features.push(FINE_GRAINED_TOOL_STREAMING_BETA);
719
+ if (model.reasoning && options?.thinkingEnabled === true && (options.interleavedThinking ?? true) && model.compat?.forceAdaptiveThinking !== true) features.push(INTERLEAVED_THINKING_BETA);
720
+ if (shouldUseServerSideFallbackBeta(model)) features.push(SERVER_SIDE_FALLBACK_BETA);
721
+ if (model.compat?.supportsMidConvoEffort === true) features.push(MID_CONVERSATION_OUTPUT_CONFIG_BETA, THINKING_BINDING_CONTROLS_BETA);
722
+ if (nativeToolChanges) features.push(MID_CONVERSATION_TOOL_CHANGES_BETA);
723
+ return [...new Set(features)];
724
+ }
725
+ function buildParams(model, context, isOAuthToken, options) {
726
+ const { cacheControl } = getCacheControl(model, options?.cacheRetention, options?.env);
727
+ const compat = getAnthropicCompat(model);
728
+ const initialSystemMessage = getInitialSystemMessage(context.messages);
729
+ const initialSystemText = initialSystemMessage ? getSystemMessageText(initialSystemMessage) : "";
730
+ const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);
731
+ const conversationMessages = initialSystemMessage ? transformedMessages.slice(1) : transformedMessages;
732
+ const initialTools = initialSystemMessage?.toolsAdded ?? [];
733
+ const nativeToolChanges = compat.supportsMidConvoSystemMessages && compat.supportsMidConvoToolChanges && initialTools.length > 0 && !hasToolRedefinitions(context.messages);
734
+ const converted = convertMessages(conversationMessages, isOAuthToken, cacheControl, compat.allowEmptySignature, model.compat?.supportsMidConvoEffort === true ? model.provider : void 0, nativeToolChanges);
735
+ const activeEffort = options?.effort ?? "high";
736
+ const betaFeatures = getBetaFeatures(model, context, isOAuthToken, nativeToolChanges, options);
737
+ const params = {
738
+ model: model.id,
739
+ messages: model.compat?.supportsMidConvoEffort === true ? insertThinkingLevelMessages(converted, activeEffort) : converted.messages,
740
+ max_tokens: options?.maxTokens ?? model.maxTokens,
741
+ stream: true,
742
+ ...betaFeatures.length > 0 ? { betas: betaFeatures } : {}
743
+ };
744
+ if (isOAuthToken) {
745
+ params.system = [{
746
+ type: "text",
747
+ text: "You are Claude Code, Anthropic's official CLI for Claude.",
748
+ ...cacheControl ? { cache_control: cacheControl } : {}
749
+ }];
750
+ if (initialSystemText) params.system.push({
751
+ type: "text",
752
+ text: sanitizeSurrogates(initialSystemText),
753
+ ...cacheControl ? { cache_control: cacheControl } : {}
754
+ });
755
+ } else if (initialSystemText) params.system = [{
756
+ type: "text",
757
+ text: sanitizeSurrogates(initialSystemText),
758
+ ...cacheControl ? { cache_control: cacheControl } : {}
759
+ }];
760
+ if (options?.temperature !== void 0 && !options?.thinkingEnabled && model.compat?.supportsMidConvoEffort !== true && compat.supportsTemperature) params.temperature = options.temperature;
761
+ const toolCacheControl = compat.supportsCacheControlOnTools ? cacheControl : void 0;
762
+ if (nativeToolChanges) {
763
+ const initialNames = new Set(initialTools.map((tool) => tool.name));
764
+ const laterTools = getDeclaredTools(context.messages).filter((tool) => !initialNames.has(tool.name));
765
+ params.tools = [
766
+ ...convertTools(initialTools, isOAuthToken, compat.supportsEagerToolInputStreaming, compat.supportsStrictTools, toolCacheControl),
767
+ DEFERRED_TOOL_PLACEHOLDER,
768
+ ...convertTools(laterTools, isOAuthToken, compat.supportsEagerToolInputStreaming, compat.supportsStrictTools).map((tool) => ({
769
+ ...tool,
770
+ defer_loading: true
771
+ }))
772
+ ];
773
+ } else {
774
+ const tools = getCurrentTools(context.messages);
775
+ if (tools.length > 0) params.tools = convertTools(tools, isOAuthToken, compat.supportsEagerToolInputStreaming, compat.supportsStrictTools, toolCacheControl);
776
+ }
777
+ if (model.compat?.supportsMidConvoEffort === true) {
778
+ params.thinking = {
779
+ type: "adaptive",
780
+ display: options?.thinkingDisplay ?? "summarized",
781
+ block_binding: { prefix_mismatch_behavior: "drop_block" }
782
+ };
783
+ params.output_config = { effort: "high" };
784
+ } else if (model.reasoning) {
785
+ if (options?.thinkingEnabled) {
786
+ const display = options.thinkingDisplay ?? "summarized";
787
+ if (model.compat?.forceAdaptiveThinking === true) {
788
+ params.thinking = {
789
+ type: "adaptive",
790
+ display
791
+ };
792
+ if (options.effort) params.output_config = { effort: options.effort };
793
+ } else params.thinking = {
794
+ type: "enabled",
795
+ budget_tokens: options.thinkingBudgetTokens || 1024,
796
+ display
797
+ };
798
+ } else if (options?.thinkingEnabled === false && model.thinkingLevelMap?.off !== null) params.thinking = { type: "disabled" };
799
+ }
800
+ if (options?.metadata) {
801
+ const userId = options.metadata.user_id;
802
+ if (typeof userId === "string") params.metadata = { user_id: userId };
803
+ }
804
+ if (options?.toolChoice) if (typeof options.toolChoice === "string") params.tool_choice = { type: options.toolChoice };
805
+ else params.tool_choice = options.toolChoice;
806
+ const allowedFallbackModels = model.compat?.allowedFallbackModels;
807
+ if (allowedFallbackModels && allowedFallbackModels.length > 0) params.fallbacks = allowedFallbackModels.map((fallback) => ({ model: fallback.model }));
808
+ return params;
809
+ }
810
+ function normalizeToolCallId(id) {
811
+ return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
812
+ }
813
+ function convertToolResult(msg) {
814
+ return {
815
+ type: "tool_result",
816
+ tool_use_id: msg.toolCallId,
817
+ content: convertContentBlocks(msg.content),
818
+ is_error: msg.isError
819
+ };
820
+ }
821
+ function convertMessages(transformedMessages, isOAuthToken, cacheControl, allowEmptySignature = false, managedProvider, nativeToolChanges = false) {
822
+ const params = [];
823
+ const assistantLevels = /* @__PURE__ */ new Map();
824
+ const pendingSystemMessages = [];
825
+ const flushPendingSystemMessages = () => {
826
+ params.push(...pendingSystemMessages);
827
+ pendingSystemMessages.length = 0;
828
+ };
829
+ for (let i = 0; i < transformedMessages.length; i++) {
830
+ const msg = transformedMessages[i];
831
+ if (msg.role === "system") {
832
+ const text = renderSystemMessageUpdate(msg);
833
+ const blocks = [];
834
+ if (text.length > 0) blocks.push({
835
+ type: "text",
836
+ text: sanitizeSurrogates(text)
837
+ });
838
+ if (nativeToolChanges) {
839
+ for (const tool of msg.toolsRemoved ?? []) blocks.push({
840
+ type: "tool_removal",
841
+ tool: {
842
+ type: "tool_reference",
843
+ name: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name
844
+ }
845
+ });
846
+ for (const tool of msg.toolsAdded ?? []) blocks.push({
847
+ type: "tool_addition",
848
+ tool: {
849
+ type: "tool_reference",
850
+ name: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name
851
+ }
852
+ });
853
+ }
854
+ if (blocks.length > 0) pendingSystemMessages.push({
855
+ role: "system",
856
+ content: blocks
857
+ });
858
+ } else if (msg.role === "user") if (typeof msg.content === "string") {
859
+ if (msg.content.trim().length > 0) params.push({
860
+ role: "user",
861
+ content: sanitizeSurrogates(msg.content)
862
+ });
863
+ } else {
864
+ const filteredBlocks = msg.content.map((item) => {
865
+ if (item.type === "text") return {
866
+ type: "text",
867
+ text: sanitizeSurrogates(item.text)
868
+ };
869
+ else return {
870
+ type: "image",
871
+ source: {
872
+ type: "base64",
873
+ media_type: item.mimeType,
874
+ data: item.data
875
+ }
876
+ };
877
+ }).filter((b) => {
878
+ if (b.type === "text") return b.text.trim().length > 0;
879
+ return true;
880
+ });
881
+ if (filteredBlocks.length === 0) continue;
882
+ params.push({
883
+ role: "user",
884
+ content: filteredBlocks
885
+ });
886
+ }
887
+ else if (msg.role === "assistant") {
888
+ flushPendingSystemMessages();
889
+ const blocks = [];
890
+ for (const block of msg.content) if (block.type === "text") {
891
+ if (block.text.trim().length === 0) continue;
892
+ blocks.push({
893
+ type: "text",
894
+ text: sanitizeSurrogates(block.text)
895
+ });
896
+ } else if (block.type === "thinking") {
897
+ if (block.redacted) {
898
+ blocks.push({
899
+ type: "redacted_thinking",
900
+ data: block.thinkingSignature
901
+ });
902
+ continue;
903
+ }
904
+ const thinkingSignature = block.thinkingSignature;
905
+ const hasThinkingSignature = !!thinkingSignature && thinkingSignature.trim().length > 0;
906
+ if (block.thinking.trim().length === 0 && !hasThinkingSignature) continue;
907
+ if (!hasThinkingSignature) blocks.push(allowEmptySignature ? {
908
+ type: "thinking",
909
+ thinking: sanitizeSurrogates(block.thinking),
910
+ signature: ""
911
+ } : {
912
+ type: "text",
913
+ text: sanitizeSurrogates(block.thinking)
914
+ });
915
+ else blocks.push({
916
+ type: "thinking",
917
+ thinking: sanitizeSurrogates(block.thinking),
918
+ signature: thinkingSignature
919
+ });
920
+ } else if (block.type === "toolCall") blocks.push({
921
+ type: "tool_use",
922
+ id: block.id,
923
+ name: isOAuthToken ? toClaudeCodeName(block.name) : block.name,
924
+ input: block.arguments ?? {}
925
+ });
926
+ if (blocks.length === 0) continue;
927
+ const messageIndex = params.length;
928
+ params.push({
929
+ role: "assistant",
930
+ content: blocks
931
+ });
932
+ if (managedProvider !== void 0 && msg.api === "anthropic-messages" && msg.provider === managedProvider && isAnthropicEffort(msg.providerThinkingLevel)) assistantLevels.set(messageIndex, msg.providerThinkingLevel);
933
+ } else if (msg.role === "toolResult") {
934
+ const toolResults = [];
935
+ let j = i;
936
+ while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {
937
+ toolResults.push(convertToolResult(transformedMessages[j]));
938
+ j++;
939
+ }
940
+ i = j - 1;
941
+ params.push({
942
+ role: "user",
943
+ content: toolResults
944
+ });
945
+ }
946
+ }
947
+ flushPendingSystemMessages();
948
+ if (cacheControl && params.length > 0) {
949
+ const lastMessage = params[params.length - 1];
950
+ if (lastMessage.role === "user" || lastMessage.role === "system") {
951
+ if (Array.isArray(lastMessage.content)) {
952
+ const lastBlock = lastMessage.content[lastMessage.content.length - 1];
953
+ if (lastBlock && (lastBlock.type === "text" || lastBlock.type === "image" || lastBlock.type === "tool_result" || lastBlock.type === "tool_addition" || lastBlock.type === "tool_removal")) lastBlock.cache_control = cacheControl;
954
+ } else if (typeof lastMessage.content === "string") lastMessage.content = [{
955
+ type: "text",
956
+ text: lastMessage.content,
957
+ cache_control: cacheControl
958
+ }];
959
+ }
960
+ }
961
+ return {
962
+ messages: params,
963
+ assistantLevels
964
+ };
965
+ }
966
+ function isAnthropicEffort(value) {
967
+ return value === "low" || value === "medium" || value === "high" || value === "xhigh" || value === "max";
968
+ }
969
+ function insertThinkingLevelMessages(converted, activeEffort) {
970
+ const messages = [];
971
+ for (let index = 0; index < converted.messages.length; index++) {
972
+ const historicalEffort = converted.assistantLevels.get(index);
973
+ if (historicalEffort !== void 0) messages.push({
974
+ role: "system",
975
+ content: [],
976
+ output_config: { effort: historicalEffort }
977
+ });
978
+ messages.push(converted.messages[index]);
979
+ }
980
+ messages.push({
981
+ role: "system",
982
+ content: [],
983
+ output_config: { effort: activeEffort }
984
+ });
985
+ return messages;
986
+ }
987
+ function shouldUseFineGrainedToolStreamingBeta(model, context) {
988
+ return getCurrentTools(context.messages).length > 0 && !getAnthropicCompat(model).supportsEagerToolInputStreaming;
989
+ }
990
+ const ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS = /* @__PURE__ */ new Set([
991
+ "minimum",
992
+ "maximum",
993
+ "exclusiveMinimum",
994
+ "exclusiveMaximum",
995
+ "multipleOf",
996
+ "maxItems",
997
+ "uniqueItems",
998
+ "minContains",
999
+ "maxContains",
1000
+ "minProperties",
1001
+ "maxProperties"
1002
+ ]);
1003
+ const ANTHROPIC_STRICT_STRING_FORMATS = /* @__PURE__ */ new Set([
1004
+ "date-time",
1005
+ "time",
1006
+ "date",
1007
+ "duration",
1008
+ "email",
1009
+ "hostname",
1010
+ "uri",
1011
+ "ipv4",
1012
+ "ipv6",
1013
+ "uuid"
1014
+ ]);
1015
+ const isAnthropicStrictUnsupportedKeyword = (key, value) => {
1016
+ if (ANTHROPIC_STRICT_UNSUPPORTED_KEYWORDS.has(key)) return true;
1017
+ if (key === "minItems") return value !== 0 && value !== 1;
1018
+ if (key === "format") return typeof value !== "string" || !ANTHROPIC_STRICT_STRING_FORMATS.has(value);
1019
+ return false;
1020
+ };
1021
+ function convertTools(tools, isOAuthToken, supportsEagerToolInputStreaming, supportsStrictTools, cacheControl) {
1022
+ if (!tools) return [];
1023
+ return tools.map((tool, index) => {
1024
+ const strict = resolveJsonSchemaStrictSampling(tool, supportsStrictTools, isAnthropicStrictUnsupportedKeyword);
1025
+ const parameters = getJsonSchemaToolParameters(tool, strict);
1026
+ const schema = parameters;
1027
+ const legacyInputSchema = {
1028
+ type: "object",
1029
+ properties: schema.properties ?? {},
1030
+ required: schema.required ?? []
1031
+ };
1032
+ const inputSchema = strict === true ? {
1033
+ ...parameters,
1034
+ ...legacyInputSchema
1035
+ } : legacyInputSchema;
1036
+ return {
1037
+ name: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name,
1038
+ description: tool.description,
1039
+ ...supportsEagerToolInputStreaming ? { eager_input_streaming: true } : {},
1040
+ ...strict === true ? { strict: true } : {},
1041
+ input_schema: inputSchema,
1042
+ ...cacheControl && index === tools.length - 1 ? { cache_control: cacheControl } : {}
1043
+ };
1044
+ });
1045
+ }
1046
+ function mapStopReason(reason, stopDetails) {
1047
+ switch (reason) {
1048
+ case "end_turn": return { stopReason: "stop" };
1049
+ case "max_tokens": return { stopReason: "length" };
1050
+ case "tool_use": return { stopReason: "toolUse" };
1051
+ case "refusal": return {
1052
+ stopReason: "error",
1053
+ errorMessage: stopDetails?.explanation || `The model refused to complete the request`
1054
+ };
1055
+ case "pause_turn": return { stopReason: "stop" };
1056
+ case "stop_sequence": return { stopReason: "stop" };
1057
+ case "sensitive": return {
1058
+ stopReason: "error",
1059
+ errorMessage: "Provider stopped with: sensitive"
1060
+ };
1061
+ default: throw new Error(`Unhandled stop reason: ${reason}`);
1062
+ }
1063
+ }
1064
+ //#endregion
1065
+ export { stream, streamSimple };
1066
+
1067
+ //# sourceMappingURL=anthropic-messages-TqKpKmfW.js.map