@leanandmean/ai 0.74.1-scramjet.4

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 (209) hide show
  1. package/dist/api-registry.d.ts +28 -0
  2. package/dist/api-registry.d.ts.map +1 -0
  3. package/dist/api-registry.js +52 -0
  4. package/dist/api-registry.js.map +1 -0
  5. package/dist/bedrock-provider.d.ts +5 -0
  6. package/dist/bedrock-provider.d.ts.map +1 -0
  7. package/dist/bedrock-provider.js +6 -0
  8. package/dist/bedrock-provider.js.map +1 -0
  9. package/dist/cli.d.ts +3 -0
  10. package/dist/cli.d.ts.map +1 -0
  11. package/dist/cli.js +116 -0
  12. package/dist/cli.js.map +1 -0
  13. package/dist/env-api-keys.d.ts +18 -0
  14. package/dist/env-api-keys.d.ts.map +1 -0
  15. package/dist/env-api-keys.js +170 -0
  16. package/dist/env-api-keys.js.map +1 -0
  17. package/dist/image-models.d.ts +10 -0
  18. package/dist/image-models.d.ts.map +1 -0
  19. package/dist/image-models.generated.d.ts +515 -0
  20. package/dist/image-models.generated.d.ts.map +1 -0
  21. package/dist/image-models.generated.js +517 -0
  22. package/dist/image-models.generated.js.map +1 -0
  23. package/dist/image-models.js +23 -0
  24. package/dist/image-models.js.map +1 -0
  25. package/dist/images-api-registry.d.ts +14 -0
  26. package/dist/images-api-registry.d.ts.map +1 -0
  27. package/dist/images-api-registry.js +22 -0
  28. package/dist/images-api-registry.js.map +1 -0
  29. package/dist/images.d.ts +4 -0
  30. package/dist/images.d.ts.map +1 -0
  31. package/dist/images.js +14 -0
  32. package/dist/images.js.map +1 -0
  33. package/dist/index.d.ts +33 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +21 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/models.d.ts +18 -0
  38. package/dist/models.d.ts.map +1 -0
  39. package/dist/models.generated.d.ts +18234 -0
  40. package/dist/models.generated.d.ts.map +1 -0
  41. package/dist/models.generated.js +17070 -0
  42. package/dist/models.generated.js.map +1 -0
  43. package/dist/models.js +71 -0
  44. package/dist/models.js.map +1 -0
  45. package/dist/oauth.d.ts +2 -0
  46. package/dist/oauth.d.ts.map +1 -0
  47. package/dist/oauth.js +2 -0
  48. package/dist/oauth.js.map +1 -0
  49. package/dist/providers/amazon-bedrock.d.ts +38 -0
  50. package/dist/providers/amazon-bedrock.d.ts.map +1 -0
  51. package/dist/providers/amazon-bedrock.js +752 -0
  52. package/dist/providers/amazon-bedrock.js.map +1 -0
  53. package/dist/providers/anthropic.d.ts +54 -0
  54. package/dist/providers/anthropic.d.ts.map +1 -0
  55. package/dist/providers/anthropic.js +1023 -0
  56. package/dist/providers/anthropic.js.map +1 -0
  57. package/dist/providers/azure-openai-responses.d.ts +15 -0
  58. package/dist/providers/azure-openai-responses.d.ts.map +1 -0
  59. package/dist/providers/azure-openai-responses.js +208 -0
  60. package/dist/providers/azure-openai-responses.js.map +1 -0
  61. package/dist/providers/cloudflare.d.ts +13 -0
  62. package/dist/providers/cloudflare.d.ts.map +1 -0
  63. package/dist/providers/cloudflare.js +26 -0
  64. package/dist/providers/cloudflare.js.map +1 -0
  65. package/dist/providers/faux.d.ts +56 -0
  66. package/dist/providers/faux.d.ts.map +1 -0
  67. package/dist/providers/faux.js +372 -0
  68. package/dist/providers/faux.js.map +1 -0
  69. package/dist/providers/github-copilot-headers.d.ts +8 -0
  70. package/dist/providers/github-copilot-headers.d.ts.map +1 -0
  71. package/dist/providers/github-copilot-headers.js +29 -0
  72. package/dist/providers/github-copilot-headers.js.map +1 -0
  73. package/dist/providers/google-shared.d.ts +70 -0
  74. package/dist/providers/google-shared.d.ts.map +1 -0
  75. package/dist/providers/google-shared.js +329 -0
  76. package/dist/providers/google-shared.js.map +1 -0
  77. package/dist/providers/google-vertex.d.ts +15 -0
  78. package/dist/providers/google-vertex.d.ts.map +1 -0
  79. package/dist/providers/google-vertex.js +444 -0
  80. package/dist/providers/google-vertex.js.map +1 -0
  81. package/dist/providers/google.d.ts +13 -0
  82. package/dist/providers/google.d.ts.map +1 -0
  83. package/dist/providers/google.js +402 -0
  84. package/dist/providers/google.js.map +1 -0
  85. package/dist/providers/images/openrouter.d.ts +3 -0
  86. package/dist/providers/images/openrouter.d.ts.map +1 -0
  87. package/dist/providers/images/openrouter.js +129 -0
  88. package/dist/providers/images/openrouter.js.map +1 -0
  89. package/dist/providers/images/register-builtins.d.ts +4 -0
  90. package/dist/providers/images/register-builtins.d.ts.map +1 -0
  91. package/dist/providers/images/register-builtins.js +34 -0
  92. package/dist/providers/images/register-builtins.js.map +1 -0
  93. package/dist/providers/mistral.d.ts +25 -0
  94. package/dist/providers/mistral.d.ts.map +1 -0
  95. package/dist/providers/mistral.js +537 -0
  96. package/dist/providers/mistral.js.map +1 -0
  97. package/dist/providers/openai-codex-responses.d.ts +30 -0
  98. package/dist/providers/openai-codex-responses.d.ts.map +1 -0
  99. package/dist/providers/openai-codex-responses.js +1081 -0
  100. package/dist/providers/openai-codex-responses.js.map +1 -0
  101. package/dist/providers/openai-completions.d.ts +19 -0
  102. package/dist/providers/openai-completions.d.ts.map +1 -0
  103. package/dist/providers/openai-completions.js +945 -0
  104. package/dist/providers/openai-completions.js.map +1 -0
  105. package/dist/providers/openai-responses-shared.d.ts +18 -0
  106. package/dist/providers/openai-responses-shared.d.ts.map +1 -0
  107. package/dist/providers/openai-responses-shared.js +494 -0
  108. package/dist/providers/openai-responses-shared.js.map +1 -0
  109. package/dist/providers/openai-responses.d.ts +13 -0
  110. package/dist/providers/openai-responses.d.ts.map +1 -0
  111. package/dist/providers/openai-responses.js +220 -0
  112. package/dist/providers/openai-responses.js.map +1 -0
  113. package/dist/providers/register-builtins.d.ts +35 -0
  114. package/dist/providers/register-builtins.d.ts.map +1 -0
  115. package/dist/providers/register-builtins.js +254 -0
  116. package/dist/providers/register-builtins.js.map +1 -0
  117. package/dist/providers/simple-options.d.ts +8 -0
  118. package/dist/providers/simple-options.d.ts.map +1 -0
  119. package/dist/providers/simple-options.js +39 -0
  120. package/dist/providers/simple-options.js.map +1 -0
  121. package/dist/providers/transform-messages.d.ts +8 -0
  122. package/dist/providers/transform-messages.d.ts.map +1 -0
  123. package/dist/providers/transform-messages.js +184 -0
  124. package/dist/providers/transform-messages.js.map +1 -0
  125. package/dist/session-resources.d.ts +4 -0
  126. package/dist/session-resources.d.ts.map +1 -0
  127. package/dist/session-resources.js +22 -0
  128. package/dist/session-resources.js.map +1 -0
  129. package/dist/stream.d.ts +8 -0
  130. package/dist/stream.d.ts.map +1 -0
  131. package/dist/stream.js +27 -0
  132. package/dist/stream.js.map +1 -0
  133. package/dist/types.d.ts +508 -0
  134. package/dist/types.d.ts.map +1 -0
  135. package/dist/types.js +2 -0
  136. package/dist/types.js.map +1 -0
  137. package/dist/utils/diagnostics.d.ts +19 -0
  138. package/dist/utils/diagnostics.d.ts.map +1 -0
  139. package/dist/utils/diagnostics.js +25 -0
  140. package/dist/utils/diagnostics.js.map +1 -0
  141. package/dist/utils/event-stream.d.ts +21 -0
  142. package/dist/utils/event-stream.d.ts.map +1 -0
  143. package/dist/utils/event-stream.js +81 -0
  144. package/dist/utils/event-stream.js.map +1 -0
  145. package/dist/utils/hash.d.ts +3 -0
  146. package/dist/utils/hash.d.ts.map +1 -0
  147. package/dist/utils/hash.js +14 -0
  148. package/dist/utils/hash.js.map +1 -0
  149. package/dist/utils/headers.d.ts +2 -0
  150. package/dist/utils/headers.d.ts.map +1 -0
  151. package/dist/utils/headers.js +8 -0
  152. package/dist/utils/headers.js.map +1 -0
  153. package/dist/utils/json-parse.d.ts +16 -0
  154. package/dist/utils/json-parse.d.ts.map +1 -0
  155. package/dist/utils/json-parse.js +113 -0
  156. package/dist/utils/json-parse.js.map +1 -0
  157. package/dist/utils/node-http-proxy.d.ts +10 -0
  158. package/dist/utils/node-http-proxy.d.ts.map +1 -0
  159. package/dist/utils/node-http-proxy.js +97 -0
  160. package/dist/utils/node-http-proxy.js.map +1 -0
  161. package/dist/utils/oauth/anthropic.d.ts +25 -0
  162. package/dist/utils/oauth/anthropic.d.ts.map +1 -0
  163. package/dist/utils/oauth/anthropic.js +335 -0
  164. package/dist/utils/oauth/anthropic.js.map +1 -0
  165. package/dist/utils/oauth/github-copilot.d.ts +30 -0
  166. package/dist/utils/oauth/github-copilot.d.ts.map +1 -0
  167. package/dist/utils/oauth/github-copilot.js +292 -0
  168. package/dist/utils/oauth/github-copilot.js.map +1 -0
  169. package/dist/utils/oauth/index.d.ts +57 -0
  170. package/dist/utils/oauth/index.d.ts.map +1 -0
  171. package/dist/utils/oauth/index.js +121 -0
  172. package/dist/utils/oauth/index.js.map +1 -0
  173. package/dist/utils/oauth/oauth-page.d.ts +3 -0
  174. package/dist/utils/oauth/oauth-page.d.ts.map +1 -0
  175. package/dist/utils/oauth/oauth-page.js +105 -0
  176. package/dist/utils/oauth/oauth-page.js.map +1 -0
  177. package/dist/utils/oauth/openai-codex.d.ts +34 -0
  178. package/dist/utils/oauth/openai-codex.d.ts.map +1 -0
  179. package/dist/utils/oauth/openai-codex.js +385 -0
  180. package/dist/utils/oauth/openai-codex.js.map +1 -0
  181. package/dist/utils/oauth/pkce.d.ts +13 -0
  182. package/dist/utils/oauth/pkce.d.ts.map +1 -0
  183. package/dist/utils/oauth/pkce.js +31 -0
  184. package/dist/utils/oauth/pkce.js.map +1 -0
  185. package/dist/utils/oauth/types.d.ts +57 -0
  186. package/dist/utils/oauth/types.d.ts.map +1 -0
  187. package/dist/utils/oauth/types.js +2 -0
  188. package/dist/utils/oauth/types.js.map +1 -0
  189. package/dist/utils/overflow.d.ts +56 -0
  190. package/dist/utils/overflow.d.ts.map +1 -0
  191. package/dist/utils/overflow.js +151 -0
  192. package/dist/utils/overflow.js.map +1 -0
  193. package/dist/utils/sanitize-unicode.d.ts +22 -0
  194. package/dist/utils/sanitize-unicode.d.ts.map +1 -0
  195. package/dist/utils/sanitize-unicode.js +26 -0
  196. package/dist/utils/sanitize-unicode.js.map +1 -0
  197. package/dist/utils/system-prompt.d.ts +12 -0
  198. package/dist/utils/system-prompt.d.ts.map +1 -0
  199. package/dist/utils/system-prompt.js +8 -0
  200. package/dist/utils/system-prompt.js.map +1 -0
  201. package/dist/utils/typebox-helpers.d.ts +17 -0
  202. package/dist/utils/typebox-helpers.d.ts.map +1 -0
  203. package/dist/utils/typebox-helpers.js +21 -0
  204. package/dist/utils/typebox-helpers.js.map +1 -0
  205. package/dist/utils/validation.d.ts +18 -0
  206. package/dist/utils/validation.d.ts.map +1 -0
  207. package/dist/utils/validation.js +281 -0
  208. package/dist/utils/validation.js.map +1 -0
  209. package/package.json +84 -0
@@ -0,0 +1,1023 @@
1
+ import Anthropic from "@anthropic-ai/sdk";
2
+ import { getEnvApiKey } from "../env-api-keys.js";
3
+ import { calculateCost } from "../models.js";
4
+ import { AssistantMessageEventStream } from "../utils/event-stream.js";
5
+ import { headersToRecord } from "../utils/headers.js";
6
+ import { parseJsonWithRepair, parseStreamingJson } from "../utils/json-parse.js";
7
+ import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
8
+ import { resolveCloudflareBaseUrl } from "./cloudflare.js";
9
+ import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "./github-copilot-headers.js";
10
+ import { adjustMaxTokensForThinking, buildBaseOptions } from "./simple-options.js";
11
+ import { transformMessages } from "./transform-messages.js";
12
+ /**
13
+ * Resolve cache retention preference.
14
+ *
15
+ * Defaults to "short" and only honors PI_CACHE_RETENTION === "long" — this is
16
+ * the low-level provider fallback for callers that hit the adapter directly.
17
+ * In the coding-agent path this default rarely fires: the SDK's own
18
+ * resolveCacheRetention (packages/coding-agent/src/core/sdk.ts, which defaults
19
+ * to "long") resolves first and passes a concrete value down, so `cacheRetention`
20
+ * is normally already set when it reaches here. Keep the two defaults in sync
21
+ * intentionally — they differ on purpose (backward-compat vs. SDK default).
22
+ */
23
+ function resolveCacheRetention(cacheRetention) {
24
+ if (cacheRetention) {
25
+ return cacheRetention;
26
+ }
27
+ if (typeof process !== "undefined" && process.env.PI_CACHE_RETENTION === "long") {
28
+ return "long";
29
+ }
30
+ return "short";
31
+ }
32
+ function getCacheControl(model, cacheRetention) {
33
+ const retention = resolveCacheRetention(cacheRetention);
34
+ if (retention === "none") {
35
+ return { retention };
36
+ }
37
+ const ttl = retention === "long" && getAnthropicCompat(model).supportsLongCacheRetention ? "1h" : undefined;
38
+ return {
39
+ retention,
40
+ cacheControl: { type: "ephemeral", ...(ttl && { ttl }) },
41
+ };
42
+ }
43
+ // Stealth mode: Mimic Claude Code's tool naming exactly
44
+ const claudeCodeVersion = "2.1.75";
45
+ // Claude Code 2.x tool names (canonical casing)
46
+ // Source: https://cchistory.mariozechner.at/data/prompts-2.1.11.md
47
+ // To update: https://github.com/badlogic/cchistory
48
+ const claudeCodeTools = [
49
+ "Read",
50
+ "Write",
51
+ "Edit",
52
+ "Bash",
53
+ "Grep",
54
+ "Glob",
55
+ "AskUserQuestion",
56
+ "EnterPlanMode",
57
+ "ExitPlanMode",
58
+ "KillShell",
59
+ "NotebookEdit",
60
+ "Skill",
61
+ "Task",
62
+ "TaskOutput",
63
+ "TodoWrite",
64
+ "WebFetch",
65
+ "WebSearch",
66
+ ];
67
+ const ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));
68
+ // Convert tool name to CC canonical casing if it matches (case-insensitive)
69
+ const toClaudeCodeName = (name) => ccToolLookup.get(name.toLowerCase()) ?? name;
70
+ const fromClaudeCodeName = (name, tools) => {
71
+ if (tools && tools.length > 0) {
72
+ const lowerName = name.toLowerCase();
73
+ const matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);
74
+ if (matchedTool)
75
+ return matchedTool.name;
76
+ }
77
+ return name;
78
+ };
79
+ /**
80
+ * Convert content blocks to Anthropic API format
81
+ */
82
+ function convertContentBlocks(content) {
83
+ // If only text blocks, return as concatenated string for simplicity
84
+ const hasImages = content.some((c) => c.type === "image");
85
+ if (!hasImages) {
86
+ return sanitizeSurrogates(content.map((c) => c.text).join("\n"));
87
+ }
88
+ // If we have images, convert to content block array
89
+ const blocks = content.map((block) => {
90
+ if (block.type === "text") {
91
+ return {
92
+ type: "text",
93
+ text: sanitizeSurrogates(block.text),
94
+ };
95
+ }
96
+ return {
97
+ type: "image",
98
+ source: {
99
+ type: "base64",
100
+ media_type: block.mimeType,
101
+ data: block.data,
102
+ },
103
+ };
104
+ });
105
+ // If only images (no text), add placeholder text block
106
+ const hasText = blocks.some((b) => b.type === "text");
107
+ if (!hasText) {
108
+ blocks.unshift({
109
+ type: "text",
110
+ text: "(see attached image)",
111
+ });
112
+ }
113
+ return blocks;
114
+ }
115
+ const FINE_GRAINED_TOOL_STREAMING_BETA = "fine-grained-tool-streaming-2025-05-14";
116
+ const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
117
+ function getAnthropicCompat(model) {
118
+ // Auto-detect session affinity and cache control support from provider
119
+ const isFireworks = model.provider === "fireworks";
120
+ const isCloudflareAiGatewayAnthropic = model.provider === "cloudflare-ai-gateway" && model.baseUrl.includes("anthropic");
121
+ return {
122
+ supportsEagerToolInputStreaming: model.compat?.supportsEagerToolInputStreaming ?? !isFireworks,
123
+ supportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? !isFireworks,
124
+ sendSessionAffinityHeaders: model.compat?.sendSessionAffinityHeaders ?? !!(isFireworks || isCloudflareAiGatewayAnthropic),
125
+ supportsCacheControlOnTools: model.compat?.supportsCacheControlOnTools ?? !isFireworks,
126
+ };
127
+ }
128
+ function mergeHeaders(...headerSources) {
129
+ const merged = {};
130
+ for (const headers of headerSources) {
131
+ if (headers) {
132
+ Object.assign(merged, headers);
133
+ }
134
+ }
135
+ return merged;
136
+ }
137
+ const ANTHROPIC_MESSAGE_EVENTS = new Set([
138
+ "message_start",
139
+ "message_delta",
140
+ "message_stop",
141
+ "content_block_start",
142
+ "content_block_delta",
143
+ "content_block_stop",
144
+ ]);
145
+ function flushSseEvent(state) {
146
+ if (!state.event && state.data.length === 0) {
147
+ return null;
148
+ }
149
+ const event = {
150
+ event: state.event,
151
+ data: state.data.join("\n"),
152
+ raw: [...state.raw],
153
+ };
154
+ state.event = null;
155
+ state.data = [];
156
+ state.raw = [];
157
+ return event;
158
+ }
159
+ function decodeSseLine(line, state) {
160
+ if (line === "") {
161
+ return flushSseEvent(state);
162
+ }
163
+ state.raw.push(line);
164
+ if (line.startsWith(":")) {
165
+ return null;
166
+ }
167
+ const delimiterIndex = line.indexOf(":");
168
+ const fieldName = delimiterIndex === -1 ? line : line.slice(0, delimiterIndex);
169
+ let value = delimiterIndex === -1 ? "" : line.slice(delimiterIndex + 1);
170
+ if (value.startsWith(" ")) {
171
+ value = value.slice(1);
172
+ }
173
+ if (fieldName === "event") {
174
+ state.event = value;
175
+ }
176
+ else if (fieldName === "data") {
177
+ state.data.push(value);
178
+ }
179
+ return null;
180
+ }
181
+ function nextLineBreakIndex(text) {
182
+ const carriageReturnIndex = text.indexOf("\r");
183
+ const newlineIndex = text.indexOf("\n");
184
+ if (carriageReturnIndex === -1) {
185
+ return newlineIndex;
186
+ }
187
+ if (newlineIndex === -1) {
188
+ return carriageReturnIndex;
189
+ }
190
+ return Math.min(carriageReturnIndex, newlineIndex);
191
+ }
192
+ function consumeLine(text) {
193
+ const lineBreakIndex = nextLineBreakIndex(text);
194
+ if (lineBreakIndex === -1) {
195
+ return null;
196
+ }
197
+ let nextIndex = lineBreakIndex + 1;
198
+ if (text[lineBreakIndex] === "\r" && text[nextIndex] === "\n") {
199
+ nextIndex += 1;
200
+ }
201
+ return {
202
+ line: text.slice(0, lineBreakIndex),
203
+ rest: text.slice(nextIndex),
204
+ };
205
+ }
206
+ async function* iterateSseMessages(body, signal) {
207
+ const reader = body.getReader();
208
+ const decoder = new TextDecoder();
209
+ const state = { event: null, data: [], raw: [] };
210
+ let buffer = "";
211
+ try {
212
+ while (true) {
213
+ if (signal?.aborted) {
214
+ throw new Error("Request was aborted");
215
+ }
216
+ const { value, done } = await reader.read();
217
+ if (done) {
218
+ break;
219
+ }
220
+ buffer += decoder.decode(value, { stream: true });
221
+ let consumed = consumeLine(buffer);
222
+ while (consumed) {
223
+ buffer = consumed.rest;
224
+ const event = decodeSseLine(consumed.line, state);
225
+ if (event) {
226
+ yield event;
227
+ }
228
+ consumed = consumeLine(buffer);
229
+ }
230
+ }
231
+ buffer += decoder.decode();
232
+ let consumed = consumeLine(buffer);
233
+ while (consumed) {
234
+ buffer = consumed.rest;
235
+ const event = decodeSseLine(consumed.line, state);
236
+ if (event) {
237
+ yield event;
238
+ }
239
+ consumed = consumeLine(buffer);
240
+ }
241
+ if (buffer.length > 0) {
242
+ const event = decodeSseLine(buffer, state);
243
+ if (event) {
244
+ yield event;
245
+ }
246
+ }
247
+ const trailingEvent = flushSseEvent(state);
248
+ if (trailingEvent) {
249
+ yield trailingEvent;
250
+ }
251
+ }
252
+ finally {
253
+ reader.releaseLock();
254
+ }
255
+ }
256
+ async function* iterateAnthropicEvents(response, signal) {
257
+ if (!response.body) {
258
+ throw new Error("Attempted to iterate over an Anthropic response with no body");
259
+ }
260
+ let sawMessageStart = false;
261
+ let sawMessageEnd = false;
262
+ for await (const sse of iterateSseMessages(response.body, signal)) {
263
+ if (sse.event === "error") {
264
+ throw new Error(sse.data);
265
+ }
266
+ if (!ANTHROPIC_MESSAGE_EVENTS.has(sse.event ?? "")) {
267
+ continue;
268
+ }
269
+ try {
270
+ const event = parseJsonWithRepair(sse.data);
271
+ if (event.type === "message_start") {
272
+ sawMessageStart = true;
273
+ }
274
+ else if (event.type === "message_stop") {
275
+ sawMessageEnd = true;
276
+ }
277
+ yield event;
278
+ }
279
+ catch (error) {
280
+ const message = error instanceof Error ? error.message : String(error);
281
+ throw new Error(`Could not parse Anthropic SSE event ${sse.event}: ${message}; data=${sse.data}; raw=${sse.raw.join("\\n")}`);
282
+ }
283
+ }
284
+ if (sawMessageStart && !sawMessageEnd) {
285
+ throw new Error("Anthropic stream ended before message_stop");
286
+ }
287
+ }
288
+ export const streamAnthropic = (model, context, options) => {
289
+ const stream = new AssistantMessageEventStream();
290
+ (async () => {
291
+ const output = {
292
+ role: "assistant",
293
+ content: [],
294
+ api: model.api,
295
+ provider: model.provider,
296
+ model: model.id,
297
+ usage: {
298
+ input: 0,
299
+ output: 0,
300
+ cacheRead: 0,
301
+ cacheWrite: 0,
302
+ totalTokens: 0,
303
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
304
+ },
305
+ stopReason: "stop",
306
+ timestamp: Date.now(),
307
+ };
308
+ try {
309
+ let client;
310
+ let isOAuth;
311
+ if (options?.client) {
312
+ client = options.client;
313
+ isOAuth = false;
314
+ }
315
+ else {
316
+ const apiKey = options?.apiKey ?? getEnvApiKey(model.provider) ?? "";
317
+ let copilotDynamicHeaders;
318
+ if (model.provider === "github-copilot") {
319
+ const hasImages = hasCopilotVisionInput(context.messages);
320
+ copilotDynamicHeaders = buildCopilotDynamicHeaders({
321
+ messages: context.messages,
322
+ hasImages,
323
+ });
324
+ }
325
+ const cacheRetention = options?.cacheRetention ?? resolveCacheRetention();
326
+ const cacheSessionId = cacheRetention === "none" ? undefined : options?.sessionId;
327
+ const created = createClient(model, apiKey, options?.interleavedThinking ?? true, shouldUseFineGrainedToolStreamingBeta(model, context), options?.headers, copilotDynamicHeaders, cacheSessionId);
328
+ client = created.client;
329
+ isOAuth = created.isOAuthToken;
330
+ }
331
+ let params = buildParams(model, context, isOAuth, options);
332
+ const nextParams = await options?.onPayload?.(params, model);
333
+ if (nextParams !== undefined) {
334
+ params = nextParams;
335
+ }
336
+ const requestOptions = {
337
+ ...(options?.signal ? { signal: options.signal } : {}),
338
+ ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),
339
+ ...(options?.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),
340
+ };
341
+ const response = await client.messages.create({ ...params, stream: true }, requestOptions).asResponse();
342
+ await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
343
+ stream.push({ type: "start", partial: output });
344
+ const blocks = output.content;
345
+ for await (const event of iterateAnthropicEvents(response, options?.signal)) {
346
+ if (event.type === "message_start") {
347
+ output.responseId = event.message.id;
348
+ // Capture initial token usage from message_start event
349
+ // This ensures we have input token counts even if the stream is aborted early
350
+ output.usage.input = event.message.usage.input_tokens || 0;
351
+ output.usage.output = event.message.usage.output_tokens || 0;
352
+ output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;
353
+ output.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;
354
+ // Anthropic doesn't provide total_tokens, compute from components
355
+ output.usage.totalTokens =
356
+ output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
357
+ calculateCost(model, output.usage);
358
+ }
359
+ else if (event.type === "content_block_start") {
360
+ if (event.content_block.type === "text") {
361
+ const block = {
362
+ type: "text",
363
+ text: "",
364
+ index: event.index,
365
+ };
366
+ output.content.push(block);
367
+ stream.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output });
368
+ }
369
+ else if (event.content_block.type === "thinking") {
370
+ const block = {
371
+ type: "thinking",
372
+ thinking: "",
373
+ thinkingSignature: "",
374
+ index: event.index,
375
+ };
376
+ output.content.push(block);
377
+ stream.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
378
+ }
379
+ else if (event.content_block.type === "redacted_thinking") {
380
+ const block = {
381
+ type: "thinking",
382
+ thinking: "[Reasoning redacted]",
383
+ thinkingSignature: event.content_block.data,
384
+ redacted: true,
385
+ index: event.index,
386
+ };
387
+ output.content.push(block);
388
+ stream.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
389
+ }
390
+ else if (event.content_block.type === "tool_use") {
391
+ const block = {
392
+ type: "toolCall",
393
+ id: event.content_block.id,
394
+ name: isOAuth
395
+ ? fromClaudeCodeName(event.content_block.name, context.tools)
396
+ : event.content_block.name,
397
+ arguments: event.content_block.input ?? {},
398
+ partialJson: "",
399
+ index: event.index,
400
+ };
401
+ output.content.push(block);
402
+ stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
403
+ }
404
+ }
405
+ else if (event.type === "content_block_delta") {
406
+ if (event.delta.type === "text_delta") {
407
+ const index = blocks.findIndex((b) => b.index === event.index);
408
+ const block = blocks[index];
409
+ if (block && block.type === "text") {
410
+ block.text += event.delta.text;
411
+ stream.push({
412
+ type: "text_delta",
413
+ contentIndex: index,
414
+ delta: event.delta.text,
415
+ partial: output,
416
+ });
417
+ }
418
+ }
419
+ else if (event.delta.type === "thinking_delta") {
420
+ const index = blocks.findIndex((b) => b.index === event.index);
421
+ const block = blocks[index];
422
+ if (block && block.type === "thinking") {
423
+ block.thinking += event.delta.thinking;
424
+ stream.push({
425
+ type: "thinking_delta",
426
+ contentIndex: index,
427
+ delta: event.delta.thinking,
428
+ partial: output,
429
+ });
430
+ }
431
+ }
432
+ else if (event.delta.type === "input_json_delta") {
433
+ const index = blocks.findIndex((b) => b.index === event.index);
434
+ const block = blocks[index];
435
+ if (block && block.type === "toolCall") {
436
+ block.partialJson += event.delta.partial_json;
437
+ block.arguments = parseStreamingJson(block.partialJson);
438
+ stream.push({
439
+ type: "toolcall_delta",
440
+ contentIndex: index,
441
+ delta: event.delta.partial_json,
442
+ partial: output,
443
+ });
444
+ }
445
+ }
446
+ else if (event.delta.type === "signature_delta") {
447
+ const index = blocks.findIndex((b) => b.index === event.index);
448
+ const block = blocks[index];
449
+ if (block && block.type === "thinking") {
450
+ block.thinkingSignature = block.thinkingSignature || "";
451
+ block.thinkingSignature += event.delta.signature;
452
+ }
453
+ }
454
+ }
455
+ else if (event.type === "content_block_stop") {
456
+ const index = blocks.findIndex((b) => b.index === event.index);
457
+ const block = blocks[index];
458
+ if (block) {
459
+ delete block.index;
460
+ if (block.type === "text") {
461
+ stream.push({
462
+ type: "text_end",
463
+ contentIndex: index,
464
+ content: block.text,
465
+ partial: output,
466
+ });
467
+ }
468
+ else if (block.type === "thinking") {
469
+ stream.push({
470
+ type: "thinking_end",
471
+ contentIndex: index,
472
+ content: block.thinking,
473
+ partial: output,
474
+ });
475
+ }
476
+ else if (block.type === "toolCall") {
477
+ block.arguments = parseStreamingJson(block.partialJson);
478
+ // Finalize in-place and strip the scratch buffer so replay only
479
+ // carries parsed arguments.
480
+ delete block.partialJson;
481
+ stream.push({
482
+ type: "toolcall_end",
483
+ contentIndex: index,
484
+ toolCall: block,
485
+ partial: output,
486
+ });
487
+ }
488
+ }
489
+ }
490
+ else if (event.type === "message_delta") {
491
+ if (event.delta.stop_reason) {
492
+ output.stopReason = mapStopReason(event.delta.stop_reason);
493
+ }
494
+ // Only update usage fields if present (not null).
495
+ // Preserves input_tokens from message_start when proxies omit it in message_delta.
496
+ if (event.usage.input_tokens != null) {
497
+ output.usage.input = event.usage.input_tokens;
498
+ }
499
+ if (event.usage.output_tokens != null) {
500
+ output.usage.output = event.usage.output_tokens;
501
+ }
502
+ if (event.usage.cache_read_input_tokens != null) {
503
+ output.usage.cacheRead = event.usage.cache_read_input_tokens;
504
+ }
505
+ if (event.usage.cache_creation_input_tokens != null) {
506
+ output.usage.cacheWrite = event.usage.cache_creation_input_tokens;
507
+ }
508
+ // Anthropic doesn't provide total_tokens, compute from components
509
+ output.usage.totalTokens =
510
+ output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
511
+ calculateCost(model, output.usage);
512
+ }
513
+ }
514
+ if (options?.signal?.aborted) {
515
+ throw new Error("Request was aborted");
516
+ }
517
+ if (output.stopReason === "aborted" || output.stopReason === "error") {
518
+ throw new Error("An unknown error occurred");
519
+ }
520
+ stream.push({ type: "done", reason: output.stopReason, message: output });
521
+ stream.end();
522
+ }
523
+ catch (error) {
524
+ for (const block of output.content) {
525
+ delete block.index;
526
+ // partialJson is only a streaming scratch buffer; never persist it.
527
+ delete block.partialJson;
528
+ }
529
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
530
+ output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
531
+ stream.push({ type: "error", reason: output.stopReason, error: output });
532
+ stream.end();
533
+ }
534
+ })();
535
+ return stream;
536
+ };
537
+ /**
538
+ * Check if a model supports adaptive thinking (Opus 4.6+, Sonnet 4.6)
539
+ */
540
+ function supportsAdaptiveThinking(modelId) {
541
+ // Adaptive-thinking model IDs (with or without date suffix)
542
+ return (modelId.includes("opus-4-6") ||
543
+ modelId.includes("opus-4.6") ||
544
+ modelId.includes("opus-4-7") ||
545
+ modelId.includes("opus-4.7") ||
546
+ modelId.includes("sonnet-4-6") ||
547
+ modelId.includes("sonnet-4.6"));
548
+ }
549
+ /**
550
+ * Map ThinkingLevel to Anthropic effort levels for adaptive thinking.
551
+ * Note: effort "max" is only valid on Opus 4.6, while Opus 4.7 supports "xhigh".
552
+ */
553
+ function mapThinkingLevelToEffort(model, level) {
554
+ const mapped = level ? model.thinkingLevelMap?.[level] : undefined;
555
+ if (typeof mapped === "string")
556
+ return mapped;
557
+ switch (level) {
558
+ case "minimal":
559
+ case "low":
560
+ return "low";
561
+ case "medium":
562
+ return "medium";
563
+ case "high":
564
+ return "high";
565
+ default:
566
+ return "high";
567
+ }
568
+ }
569
+ export const streamSimpleAnthropic = (model, context, options) => {
570
+ const apiKey = options?.apiKey || getEnvApiKey(model.provider);
571
+ if (!apiKey) {
572
+ throw new Error(`No API key for provider: ${model.provider}`);
573
+ }
574
+ const base = buildBaseOptions(model, options, apiKey);
575
+ if (!options?.reasoning) {
576
+ return streamAnthropic(model, context, { ...base, thinkingEnabled: false });
577
+ }
578
+ // For Opus 4.6 and Sonnet 4.6: use adaptive thinking with effort level
579
+ // For older models: use budget-based thinking
580
+ if (supportsAdaptiveThinking(model.id)) {
581
+ const effort = mapThinkingLevelToEffort(model, options.reasoning);
582
+ return streamAnthropic(model, context, {
583
+ ...base,
584
+ thinkingEnabled: true,
585
+ effort,
586
+ });
587
+ }
588
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens || 0, model.maxTokens, options.reasoning, options.thinkingBudgets);
589
+ return streamAnthropic(model, context, {
590
+ ...base,
591
+ maxTokens: adjusted.maxTokens,
592
+ thinkingEnabled: true,
593
+ thinkingBudgetTokens: adjusted.thinkingBudget,
594
+ });
595
+ };
596
+ function isOAuthToken(apiKey) {
597
+ return apiKey.includes("sk-ant-oat");
598
+ }
599
+ function createClient(model, apiKey, interleavedThinking, useFineGrainedToolStreamingBeta, optionsHeaders, dynamicHeaders, sessionId) {
600
+ // Adaptive thinking models (Opus 4.6, Sonnet 4.6) have interleaved thinking built-in.
601
+ // The beta header is deprecated on Opus 4.6 and redundant on Sonnet 4.6, so skip it.
602
+ const needsInterleavedBeta = interleavedThinking && !supportsAdaptiveThinking(model.id);
603
+ const betaFeatures = [];
604
+ if (useFineGrainedToolStreamingBeta) {
605
+ betaFeatures.push(FINE_GRAINED_TOOL_STREAMING_BETA);
606
+ }
607
+ if (needsInterleavedBeta) {
608
+ betaFeatures.push(INTERLEAVED_THINKING_BETA);
609
+ }
610
+ if (model.provider === "cloudflare-ai-gateway") {
611
+ const client = new Anthropic({
612
+ apiKey: null,
613
+ authToken: null,
614
+ baseURL: resolveCloudflareBaseUrl(model),
615
+ dangerouslyAllowBrowser: true,
616
+ defaultHeaders: mergeHeaders({
617
+ accept: "application/json",
618
+ "anthropic-dangerous-direct-browser-access": "true",
619
+ "cf-aig-authorization": `Bearer ${apiKey}`,
620
+ "x-api-key": null,
621
+ Authorization: null,
622
+ ...(betaFeatures.length > 0 ? { "anthropic-beta": betaFeatures.join(",") } : {}),
623
+ }, model.headers, optionsHeaders),
624
+ });
625
+ return { client, isOAuthToken: false };
626
+ }
627
+ // Copilot: Bearer auth, selective betas.
628
+ if (model.provider === "github-copilot") {
629
+ const client = new Anthropic({
630
+ apiKey: null,
631
+ authToken: apiKey,
632
+ baseURL: model.baseUrl,
633
+ dangerouslyAllowBrowser: true,
634
+ defaultHeaders: mergeHeaders({
635
+ accept: "application/json",
636
+ "anthropic-dangerous-direct-browser-access": "true",
637
+ ...(betaFeatures.length > 0 ? { "anthropic-beta": betaFeatures.join(",") } : {}),
638
+ }, model.headers, dynamicHeaders, optionsHeaders),
639
+ });
640
+ return { client, isOAuthToken: false };
641
+ }
642
+ // OAuth: Bearer auth, Claude Code identity headers
643
+ if (isOAuthToken(apiKey)) {
644
+ const client = new Anthropic({
645
+ apiKey: null,
646
+ authToken: apiKey,
647
+ baseURL: model.baseUrl,
648
+ dangerouslyAllowBrowser: true,
649
+ defaultHeaders: mergeHeaders({
650
+ accept: "application/json",
651
+ "anthropic-dangerous-direct-browser-access": "true",
652
+ "anthropic-beta": ["claude-code-20250219", "oauth-2025-04-20", ...betaFeatures].join(","),
653
+ "user-agent": `claude-cli/${claudeCodeVersion}`,
654
+ "x-app": "cli",
655
+ }, model.headers, optionsHeaders),
656
+ });
657
+ return { client, isOAuthToken: true };
658
+ }
659
+ // API key auth
660
+ const sessionAffinityHeaders = sessionId && getAnthropicCompat(model).sendSessionAffinityHeaders ? { "x-session-affinity": sessionId } : {};
661
+ const client = new Anthropic({
662
+ apiKey,
663
+ baseURL: model.baseUrl,
664
+ dangerouslyAllowBrowser: true,
665
+ defaultHeaders: mergeHeaders({
666
+ accept: "application/json",
667
+ "anthropic-dangerous-direct-browser-access": "true",
668
+ ...(betaFeatures.length > 0 ? { "anthropic-beta": betaFeatures.join(",") } : {}),
669
+ }, sessionAffinityHeaders, model.headers, optionsHeaders),
670
+ });
671
+ return { client, isOAuthToken: false };
672
+ }
673
+ const claudeCodeIdentity = "You are Claude Code, Anthropic's official CLI for Claude.";
674
+ /**
675
+ * Builds the system block array for a sectioned system prompt.
676
+ *
677
+ * Anthropic allows at most 4 `cache_control` breakpoints per request, and the
678
+ * last tool and last user message already consume two, so the system prompt
679
+ * spends at most one: it lands on a single stable block folding the leading
680
+ * run of sections up to the first `cacheRetention: "none"` section (zero
681
+ * breakpoints when retention is "none"; when the first section is volatile
682
+ * the breakpoint moves to the OAuth identity block, or is omitted entirely
683
+ * on API-key auth).
684
+ * Everything from the first volatile section onward trails as uncached blocks
685
+ * in array order — anything after the breakpoint is excluded from the cached
686
+ * prefix, and preserving array order keeps the concatenated block text
687
+ * byte-identical (for well-formed text; `sanitizeSurrogates` runs per block)
688
+ * to the flattened prompt other providers send. On OAuth the
689
+ * Claude Code identity block stays first; caching is prefix-based, so the
690
+ * stable block's breakpoint covers it without a second one (unlike the legacy
691
+ * string path, which marks both for back-compat).
692
+ */
693
+ function buildSystemBlocks(sections, isOAuthToken, cacheControl) {
694
+ const blocks = [];
695
+ const nonEmpty = sections.filter((s) => s.text);
696
+ const firstVolatile = nonEmpty.findIndex((s) => s.cacheRetention === "none");
697
+ const stable = firstVolatile === -1 ? nonEmpty : nonEmpty.slice(0, firstVolatile);
698
+ const tail = firstVolatile === -1 ? [] : nonEmpty.slice(firstVolatile);
699
+ if (isOAuthToken) {
700
+ blocks.push({
701
+ type: "text",
702
+ text: claudeCodeIdentity,
703
+ // Without stable sections the identity block is the whole stable
704
+ // prefix, so the breakpoint lands here (as on the string path).
705
+ ...(stable.length === 0 && cacheControl ? { cache_control: cacheControl } : {}),
706
+ });
707
+ }
708
+ if (stable.length > 0) {
709
+ blocks.push({
710
+ type: "text",
711
+ text: sanitizeSurrogates(stable.map((s) => s.text).join("")),
712
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
713
+ });
714
+ }
715
+ for (const section of tail) {
716
+ blocks.push({ type: "text", text: sanitizeSurrogates(section.text) });
717
+ }
718
+ return blocks;
719
+ }
720
+ function buildParams(model, context, isOAuthToken, options) {
721
+ const { cacheControl } = getCacheControl(model, options?.cacheRetention);
722
+ const params = {
723
+ model: model.id,
724
+ messages: convertMessages(context.messages, model, isOAuthToken, cacheControl),
725
+ max_tokens: options?.maxTokens || (model.maxTokens / 3) | 0,
726
+ stream: true,
727
+ };
728
+ if (Array.isArray(context.systemPrompt)) {
729
+ const blocks = buildSystemBlocks(context.systemPrompt, isOAuthToken, cacheControl);
730
+ if (blocks.length > 0) {
731
+ params.system = blocks;
732
+ }
733
+ }
734
+ else {
735
+ const systemPrompt = context.systemPrompt;
736
+ // For OAuth tokens, we MUST include Claude Code identity
737
+ if (isOAuthToken) {
738
+ params.system = [
739
+ {
740
+ type: "text",
741
+ text: claudeCodeIdentity,
742
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
743
+ },
744
+ ];
745
+ if (systemPrompt) {
746
+ params.system.push({
747
+ type: "text",
748
+ text: sanitizeSurrogates(systemPrompt),
749
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
750
+ });
751
+ }
752
+ }
753
+ else if (systemPrompt) {
754
+ // Add cache control to system prompt for non-OAuth tokens
755
+ params.system = [
756
+ {
757
+ type: "text",
758
+ text: sanitizeSurrogates(systemPrompt),
759
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
760
+ },
761
+ ];
762
+ }
763
+ }
764
+ // Temperature is incompatible with extended thinking (adaptive or budget-based).
765
+ if (options?.temperature !== undefined && !options?.thinkingEnabled) {
766
+ params.temperature = options.temperature;
767
+ }
768
+ if (context.tools && context.tools.length > 0) {
769
+ const compat = getAnthropicCompat(model);
770
+ params.tools = convertTools(context.tools, isOAuthToken, compat.supportsEagerToolInputStreaming, compat.supportsCacheControlOnTools ? cacheControl : undefined);
771
+ }
772
+ // Configure thinking mode: adaptive (Opus 4.6+ and Sonnet 4.6),
773
+ // budget-based (older models), or explicitly disabled.
774
+ if (model.reasoning) {
775
+ if (options?.thinkingEnabled) {
776
+ // Default to "summarized" so Opus 4.7 and Mythos Preview behave like
777
+ // older Claude 4 models (whose API default is also "summarized").
778
+ const display = options.thinkingDisplay ?? "summarized";
779
+ if (supportsAdaptiveThinking(model.id)) {
780
+ // Adaptive thinking: Claude decides when and how much to think.
781
+ params.thinking = { type: "adaptive", display };
782
+ if (options.effort) {
783
+ // The Anthropic SDK types can lag newly supported effort values such as "xhigh".
784
+ params.output_config =
785
+ options.effort === "xhigh"
786
+ ? { effort: options.effort }
787
+ : { effort: options.effort };
788
+ }
789
+ }
790
+ else {
791
+ // Budget-based thinking for older models
792
+ params.thinking = {
793
+ type: "enabled",
794
+ budget_tokens: options.thinkingBudgetTokens || 1024,
795
+ display,
796
+ };
797
+ }
798
+ }
799
+ else if (options?.thinkingEnabled === false) {
800
+ params.thinking = { type: "disabled" };
801
+ }
802
+ }
803
+ if (options?.metadata) {
804
+ const userId = options.metadata.user_id;
805
+ if (typeof userId === "string") {
806
+ params.metadata = { user_id: userId };
807
+ }
808
+ }
809
+ if (options?.toolChoice) {
810
+ if (typeof options.toolChoice === "string") {
811
+ params.tool_choice = { type: options.toolChoice };
812
+ }
813
+ else {
814
+ params.tool_choice = options.toolChoice;
815
+ }
816
+ }
817
+ return params;
818
+ }
819
+ // Normalize tool call IDs to match Anthropic's required pattern and length
820
+ function normalizeToolCallId(id) {
821
+ return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
822
+ }
823
+ function convertMessages(messages, model, isOAuthToken, cacheControl) {
824
+ const params = [];
825
+ // Transform messages for cross-provider compatibility
826
+ const transformedMessages = transformMessages(messages, model, normalizeToolCallId);
827
+ for (let i = 0; i < transformedMessages.length; i++) {
828
+ const msg = transformedMessages[i];
829
+ if (msg.role === "user") {
830
+ if (typeof msg.content === "string") {
831
+ if (msg.content.trim().length > 0) {
832
+ params.push({
833
+ role: "user",
834
+ content: sanitizeSurrogates(msg.content),
835
+ });
836
+ }
837
+ }
838
+ else {
839
+ const blocks = msg.content.map((item) => {
840
+ if (item.type === "text") {
841
+ return {
842
+ type: "text",
843
+ text: sanitizeSurrogates(item.text),
844
+ };
845
+ }
846
+ else {
847
+ return {
848
+ type: "image",
849
+ source: {
850
+ type: "base64",
851
+ media_type: item.mimeType,
852
+ data: item.data,
853
+ },
854
+ };
855
+ }
856
+ });
857
+ const filteredBlocks = blocks.filter((b) => {
858
+ if (b.type === "text") {
859
+ return b.text.trim().length > 0;
860
+ }
861
+ return true;
862
+ });
863
+ if (filteredBlocks.length === 0)
864
+ continue;
865
+ params.push({
866
+ role: "user",
867
+ content: filteredBlocks,
868
+ });
869
+ }
870
+ }
871
+ else if (msg.role === "assistant") {
872
+ const blocks = [];
873
+ for (const block of msg.content) {
874
+ if (block.type === "text") {
875
+ if (block.text.trim().length === 0)
876
+ continue;
877
+ blocks.push({
878
+ type: "text",
879
+ text: sanitizeSurrogates(block.text),
880
+ });
881
+ }
882
+ else if (block.type === "thinking") {
883
+ // Redacted thinking: pass the opaque payload back as redacted_thinking
884
+ if (block.redacted) {
885
+ blocks.push({
886
+ type: "redacted_thinking",
887
+ data: block.thinkingSignature,
888
+ });
889
+ continue;
890
+ }
891
+ if (block.thinking.trim().length === 0)
892
+ continue;
893
+ // If thinking signature is missing/empty (e.g., from aborted stream),
894
+ // convert to plain text block without <thinking> tags to avoid API rejection
895
+ // and prevent Claude from mimicking the tags in responses
896
+ if (!block.thinkingSignature || block.thinkingSignature.trim().length === 0) {
897
+ blocks.push({
898
+ type: "text",
899
+ text: sanitizeSurrogates(block.thinking),
900
+ });
901
+ }
902
+ else {
903
+ blocks.push({
904
+ type: "thinking",
905
+ thinking: sanitizeSurrogates(block.thinking),
906
+ signature: block.thinkingSignature,
907
+ });
908
+ }
909
+ }
910
+ else if (block.type === "toolCall") {
911
+ blocks.push({
912
+ type: "tool_use",
913
+ id: block.id,
914
+ name: isOAuthToken ? toClaudeCodeName(block.name) : block.name,
915
+ input: block.arguments ?? {},
916
+ });
917
+ }
918
+ }
919
+ if (blocks.length === 0)
920
+ continue;
921
+ params.push({
922
+ role: "assistant",
923
+ content: blocks,
924
+ });
925
+ }
926
+ else if (msg.role === "toolResult") {
927
+ // Collect all consecutive toolResult messages, needed for z.ai Anthropic endpoint
928
+ const toolResults = [];
929
+ // Add the current tool result
930
+ toolResults.push({
931
+ type: "tool_result",
932
+ tool_use_id: msg.toolCallId,
933
+ content: convertContentBlocks(msg.content),
934
+ is_error: msg.isError,
935
+ });
936
+ // Look ahead for consecutive toolResult messages
937
+ let j = i + 1;
938
+ while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {
939
+ const nextMsg = transformedMessages[j]; // We know it's a toolResult
940
+ toolResults.push({
941
+ type: "tool_result",
942
+ tool_use_id: nextMsg.toolCallId,
943
+ content: convertContentBlocks(nextMsg.content),
944
+ is_error: nextMsg.isError,
945
+ });
946
+ j++;
947
+ }
948
+ // Skip the messages we've already processed
949
+ i = j - 1;
950
+ // Add a single user message with all tool results
951
+ params.push({
952
+ role: "user",
953
+ content: toolResults,
954
+ });
955
+ }
956
+ }
957
+ // Add cache_control to the last user message to cache conversation history
958
+ if (cacheControl && params.length > 0) {
959
+ const lastMessage = params[params.length - 1];
960
+ if (lastMessage.role === "user") {
961
+ if (Array.isArray(lastMessage.content)) {
962
+ const lastBlock = lastMessage.content[lastMessage.content.length - 1];
963
+ if (lastBlock &&
964
+ (lastBlock.type === "text" || lastBlock.type === "image" || lastBlock.type === "tool_result")) {
965
+ lastBlock.cache_control = cacheControl;
966
+ }
967
+ }
968
+ else if (typeof lastMessage.content === "string") {
969
+ lastMessage.content = [
970
+ {
971
+ type: "text",
972
+ text: lastMessage.content,
973
+ cache_control: cacheControl,
974
+ },
975
+ ];
976
+ }
977
+ }
978
+ }
979
+ return params;
980
+ }
981
+ function shouldUseFineGrainedToolStreamingBeta(model, context) {
982
+ return !!context.tools?.length && !getAnthropicCompat(model).supportsEagerToolInputStreaming;
983
+ }
984
+ function convertTools(tools, isOAuthToken, supportsEagerToolInputStreaming, cacheControl) {
985
+ if (!tools)
986
+ return [];
987
+ return tools.map((tool, index) => {
988
+ const schema = tool.parameters;
989
+ return {
990
+ name: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name,
991
+ description: tool.description,
992
+ ...(supportsEagerToolInputStreaming ? { eager_input_streaming: true } : {}),
993
+ input_schema: {
994
+ type: "object",
995
+ properties: schema.properties ?? {},
996
+ required: schema.required ?? [],
997
+ },
998
+ ...(cacheControl && index === tools.length - 1 ? { cache_control: cacheControl } : {}),
999
+ };
1000
+ });
1001
+ }
1002
+ function mapStopReason(reason) {
1003
+ switch (reason) {
1004
+ case "end_turn":
1005
+ return "stop";
1006
+ case "max_tokens":
1007
+ return "length";
1008
+ case "tool_use":
1009
+ return "toolUse";
1010
+ case "refusal":
1011
+ return "error";
1012
+ case "pause_turn": // Stop is good enough -> resubmit
1013
+ return "stop";
1014
+ case "stop_sequence":
1015
+ return "stop"; // We don't supply stop sequences, so this should never happen
1016
+ case "sensitive": // Content flagged by safety filters (not yet in SDK types)
1017
+ return "error";
1018
+ default:
1019
+ // Handle unknown stop reasons gracefully (API may add new values)
1020
+ throw new Error(`Unhandled stop reason: ${reason}`);
1021
+ }
1022
+ }
1023
+ //# sourceMappingURL=anthropic.js.map