@lenylvt/pi-ai 0.64.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 (167) hide show
  1. package/README.md +203 -0
  2. package/dist/api-registry.d.ts +20 -0
  3. package/dist/api-registry.d.ts.map +1 -0
  4. package/dist/api-registry.js +44 -0
  5. package/dist/api-registry.js.map +1 -0
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +119 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/env-api-keys.d.ts +7 -0
  11. package/dist/env-api-keys.d.ts.map +1 -0
  12. package/dist/env-api-keys.js +13 -0
  13. package/dist/env-api-keys.js.map +1 -0
  14. package/dist/index.d.ts +20 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +14 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/models.d.ts +24 -0
  19. package/dist/models.d.ts.map +1 -0
  20. package/dist/models.generated.d.ts +2332 -0
  21. package/dist/models.generated.d.ts.map +1 -0
  22. package/dist/models.generated.js +2186 -0
  23. package/dist/models.generated.js.map +1 -0
  24. package/dist/models.js +60 -0
  25. package/dist/models.js.map +1 -0
  26. package/dist/oauth.d.ts +2 -0
  27. package/dist/oauth.d.ts.map +1 -0
  28. package/dist/oauth.js +2 -0
  29. package/dist/oauth.js.map +1 -0
  30. package/dist/providers/anthropic.d.ts +40 -0
  31. package/dist/providers/anthropic.d.ts.map +1 -0
  32. package/dist/providers/anthropic.js +749 -0
  33. package/dist/providers/anthropic.js.map +1 -0
  34. package/dist/providers/faux.d.ts +56 -0
  35. package/dist/providers/faux.d.ts.map +1 -0
  36. package/dist/providers/faux.js +367 -0
  37. package/dist/providers/faux.js.map +1 -0
  38. package/dist/providers/github-copilot-headers.d.ts +8 -0
  39. package/dist/providers/github-copilot-headers.d.ts.map +1 -0
  40. package/dist/providers/github-copilot-headers.js +29 -0
  41. package/dist/providers/github-copilot-headers.js.map +1 -0
  42. package/dist/providers/openai-codex-responses.d.ts +9 -0
  43. package/dist/providers/openai-codex-responses.d.ts.map +1 -0
  44. package/dist/providers/openai-codex-responses.js +741 -0
  45. package/dist/providers/openai-codex-responses.js.map +1 -0
  46. package/dist/providers/openai-completions.d.ts +15 -0
  47. package/dist/providers/openai-completions.d.ts.map +1 -0
  48. package/dist/providers/openai-completions.js +687 -0
  49. package/dist/providers/openai-completions.js.map +1 -0
  50. package/dist/providers/openai-responses-shared.d.ts +17 -0
  51. package/dist/providers/openai-responses-shared.d.ts.map +1 -0
  52. package/dist/providers/openai-responses-shared.js +458 -0
  53. package/dist/providers/openai-responses-shared.js.map +1 -0
  54. package/dist/providers/openai-responses.d.ts +13 -0
  55. package/dist/providers/openai-responses.d.ts.map +1 -0
  56. package/dist/providers/openai-responses.js +190 -0
  57. package/dist/providers/openai-responses.js.map +1 -0
  58. package/dist/providers/register-builtins.d.ts +16 -0
  59. package/dist/providers/register-builtins.d.ts.map +1 -0
  60. package/dist/providers/register-builtins.js +140 -0
  61. package/dist/providers/register-builtins.js.map +1 -0
  62. package/dist/providers/simple-options.d.ts +8 -0
  63. package/dist/providers/simple-options.d.ts.map +1 -0
  64. package/dist/providers/simple-options.js +35 -0
  65. package/dist/providers/simple-options.js.map +1 -0
  66. package/dist/providers/transform-messages.d.ts +8 -0
  67. package/dist/providers/transform-messages.d.ts.map +1 -0
  68. package/dist/providers/transform-messages.js +155 -0
  69. package/dist/providers/transform-messages.js.map +1 -0
  70. package/dist/stream.d.ts +8 -0
  71. package/dist/stream.d.ts.map +1 -0
  72. package/dist/stream.js +27 -0
  73. package/dist/stream.js.map +1 -0
  74. package/dist/types.d.ts +283 -0
  75. package/dist/types.d.ts.map +1 -0
  76. package/dist/types.js +2 -0
  77. package/dist/types.js.map +1 -0
  78. package/dist/utils/event-stream.d.ts +21 -0
  79. package/dist/utils/event-stream.d.ts.map +1 -0
  80. package/dist/utils/event-stream.js +81 -0
  81. package/dist/utils/event-stream.js.map +1 -0
  82. package/dist/utils/hash.d.ts +3 -0
  83. package/dist/utils/hash.d.ts.map +1 -0
  84. package/dist/utils/hash.js +14 -0
  85. package/dist/utils/hash.js.map +1 -0
  86. package/dist/utils/json-parse.d.ts +9 -0
  87. package/dist/utils/json-parse.d.ts.map +1 -0
  88. package/dist/utils/json-parse.js +29 -0
  89. package/dist/utils/json-parse.js.map +1 -0
  90. package/dist/utils/oauth/anthropic.d.ts +25 -0
  91. package/dist/utils/oauth/anthropic.d.ts.map +1 -0
  92. package/dist/utils/oauth/anthropic.js +335 -0
  93. package/dist/utils/oauth/anthropic.js.map +1 -0
  94. package/dist/utils/oauth/github-copilot.d.ts +30 -0
  95. package/dist/utils/oauth/github-copilot.d.ts.map +1 -0
  96. package/dist/utils/oauth/github-copilot.js +292 -0
  97. package/dist/utils/oauth/github-copilot.js.map +1 -0
  98. package/dist/utils/oauth/index.d.ts +36 -0
  99. package/dist/utils/oauth/index.d.ts.map +1 -0
  100. package/dist/utils/oauth/index.js +92 -0
  101. package/dist/utils/oauth/index.js.map +1 -0
  102. package/dist/utils/oauth/oauth-page.d.ts +3 -0
  103. package/dist/utils/oauth/oauth-page.d.ts.map +1 -0
  104. package/dist/utils/oauth/oauth-page.js +105 -0
  105. package/dist/utils/oauth/oauth-page.js.map +1 -0
  106. package/dist/utils/oauth/openai-codex.d.ts +34 -0
  107. package/dist/utils/oauth/openai-codex.d.ts.map +1 -0
  108. package/dist/utils/oauth/openai-codex.js +373 -0
  109. package/dist/utils/oauth/openai-codex.js.map +1 -0
  110. package/dist/utils/oauth/pkce.d.ts +13 -0
  111. package/dist/utils/oauth/pkce.d.ts.map +1 -0
  112. package/dist/utils/oauth/pkce.js +31 -0
  113. package/dist/utils/oauth/pkce.js.map +1 -0
  114. package/dist/utils/oauth/types.d.ts +47 -0
  115. package/dist/utils/oauth/types.d.ts.map +1 -0
  116. package/dist/utils/oauth/types.js +2 -0
  117. package/dist/utils/oauth/types.js.map +1 -0
  118. package/dist/utils/overflow.d.ts +53 -0
  119. package/dist/utils/overflow.d.ts.map +1 -0
  120. package/dist/utils/overflow.js +119 -0
  121. package/dist/utils/overflow.js.map +1 -0
  122. package/dist/utils/sanitize-unicode.d.ts +22 -0
  123. package/dist/utils/sanitize-unicode.d.ts.map +1 -0
  124. package/dist/utils/sanitize-unicode.js +26 -0
  125. package/dist/utils/sanitize-unicode.js.map +1 -0
  126. package/dist/utils/typebox-helpers.d.ts +17 -0
  127. package/dist/utils/typebox-helpers.d.ts.map +1 -0
  128. package/dist/utils/typebox-helpers.js +21 -0
  129. package/dist/utils/typebox-helpers.js.map +1 -0
  130. package/dist/utils/validation.d.ts +18 -0
  131. package/dist/utils/validation.d.ts.map +1 -0
  132. package/dist/utils/validation.js +80 -0
  133. package/dist/utils/validation.js.map +1 -0
  134. package/package.json +89 -0
  135. package/src/api-registry.ts +98 -0
  136. package/src/cli.ts +136 -0
  137. package/src/env-api-keys.ts +22 -0
  138. package/src/index.ts +29 -0
  139. package/src/models.generated.ts +2188 -0
  140. package/src/models.ts +82 -0
  141. package/src/oauth.ts +1 -0
  142. package/src/providers/anthropic.ts +905 -0
  143. package/src/providers/faux.ts +498 -0
  144. package/src/providers/github-copilot-headers.ts +37 -0
  145. package/src/providers/openai-codex-responses.ts +929 -0
  146. package/src/providers/openai-completions.ts +811 -0
  147. package/src/providers/openai-responses-shared.ts +513 -0
  148. package/src/providers/openai-responses.ts +251 -0
  149. package/src/providers/register-builtins.ts +232 -0
  150. package/src/providers/simple-options.ts +46 -0
  151. package/src/providers/transform-messages.ts +172 -0
  152. package/src/stream.ts +59 -0
  153. package/src/types.ts +294 -0
  154. package/src/utils/event-stream.ts +87 -0
  155. package/src/utils/hash.ts +13 -0
  156. package/src/utils/json-parse.ts +28 -0
  157. package/src/utils/oauth/anthropic.ts +402 -0
  158. package/src/utils/oauth/github-copilot.ts +396 -0
  159. package/src/utils/oauth/index.ts +123 -0
  160. package/src/utils/oauth/oauth-page.ts +109 -0
  161. package/src/utils/oauth/openai-codex.ts +450 -0
  162. package/src/utils/oauth/pkce.ts +34 -0
  163. package/src/utils/oauth/types.ts +59 -0
  164. package/src/utils/overflow.ts +125 -0
  165. package/src/utils/sanitize-unicode.ts +25 -0
  166. package/src/utils/typebox-helpers.ts +24 -0
  167. package/src/utils/validation.ts +93 -0
@@ -0,0 +1,749 @@
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 { parseStreamingJson } from "../utils/json-parse.js";
6
+ import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
7
+ import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "./github-copilot-headers.js";
8
+ import { adjustMaxTokensForThinking, buildBaseOptions } from "./simple-options.js";
9
+ import { transformMessages } from "./transform-messages.js";
10
+ /**
11
+ * Resolve cache retention preference.
12
+ * Defaults to "short" and uses PI_CACHE_RETENTION for backward compatibility.
13
+ */
14
+ function resolveCacheRetention(cacheRetention) {
15
+ if (cacheRetention) {
16
+ return cacheRetention;
17
+ }
18
+ if (typeof process !== "undefined" && process.env.PI_CACHE_RETENTION === "long") {
19
+ return "long";
20
+ }
21
+ return "short";
22
+ }
23
+ function getCacheControl(baseUrl, cacheRetention) {
24
+ const retention = resolveCacheRetention(cacheRetention);
25
+ if (retention === "none") {
26
+ return { retention };
27
+ }
28
+ const ttl = retention === "long" && baseUrl.includes("api.anthropic.com") ? "1h" : undefined;
29
+ return {
30
+ retention,
31
+ cacheControl: { type: "ephemeral", ...(ttl && { ttl }) },
32
+ };
33
+ }
34
+ // Stealth mode: Mimic Claude Code's tool naming exactly
35
+ const claudeCodeVersion = "2.1.75";
36
+ // Claude Code 2.x tool names (canonical casing)
37
+ // Source: https://cchistory.mariozechner.at/data/prompts-2.1.11.md
38
+ // To update: https://github.com/badlogic/cchistory
39
+ const claudeCodeTools = [
40
+ "Read",
41
+ "Write",
42
+ "Edit",
43
+ "Bash",
44
+ "Grep",
45
+ "Glob",
46
+ "AskUserQuestion",
47
+ "EnterPlanMode",
48
+ "ExitPlanMode",
49
+ "KillShell",
50
+ "NotebookEdit",
51
+ "Skill",
52
+ "Task",
53
+ "TaskOutput",
54
+ "TodoWrite",
55
+ "WebFetch",
56
+ "WebSearch",
57
+ ];
58
+ const ccToolLookup = new Map(claudeCodeTools.map((t) => [t.toLowerCase(), t]));
59
+ // Convert tool name to CC canonical casing if it matches (case-insensitive)
60
+ const toClaudeCodeName = (name) => ccToolLookup.get(name.toLowerCase()) ?? name;
61
+ const fromClaudeCodeName = (name, tools) => {
62
+ if (tools && tools.length > 0) {
63
+ const lowerName = name.toLowerCase();
64
+ const matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);
65
+ if (matchedTool)
66
+ return matchedTool.name;
67
+ }
68
+ return name;
69
+ };
70
+ /**
71
+ * Convert content blocks to Anthropic API format
72
+ */
73
+ function convertContentBlocks(content) {
74
+ // If only text blocks, return as concatenated string for simplicity
75
+ const hasImages = content.some((c) => c.type === "image");
76
+ if (!hasImages) {
77
+ return sanitizeSurrogates(content.map((c) => c.text).join("\n"));
78
+ }
79
+ // If we have images, convert to content block array
80
+ const blocks = content.map((block) => {
81
+ if (block.type === "text") {
82
+ return {
83
+ type: "text",
84
+ text: sanitizeSurrogates(block.text),
85
+ };
86
+ }
87
+ return {
88
+ type: "image",
89
+ source: {
90
+ type: "base64",
91
+ media_type: block.mimeType,
92
+ data: block.data,
93
+ },
94
+ };
95
+ });
96
+ // If only images (no text), add placeholder text block
97
+ const hasText = blocks.some((b) => b.type === "text");
98
+ if (!hasText) {
99
+ blocks.unshift({
100
+ type: "text",
101
+ text: "(see attached image)",
102
+ });
103
+ }
104
+ return blocks;
105
+ }
106
+ function mergeHeaders(...headerSources) {
107
+ const merged = {};
108
+ for (const headers of headerSources) {
109
+ if (headers) {
110
+ Object.assign(merged, headers);
111
+ }
112
+ }
113
+ return merged;
114
+ }
115
+ export const streamAnthropic = (model, context, options) => {
116
+ const stream = new AssistantMessageEventStream();
117
+ (async () => {
118
+ const output = {
119
+ role: "assistant",
120
+ content: [],
121
+ api: model.api,
122
+ provider: model.provider,
123
+ model: model.id,
124
+ usage: {
125
+ input: 0,
126
+ output: 0,
127
+ cacheRead: 0,
128
+ cacheWrite: 0,
129
+ totalTokens: 0,
130
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
131
+ },
132
+ stopReason: "stop",
133
+ timestamp: Date.now(),
134
+ };
135
+ try {
136
+ let client;
137
+ let isOAuth;
138
+ if (options?.client) {
139
+ client = options.client;
140
+ isOAuth = false;
141
+ }
142
+ else {
143
+ const apiKey = options?.apiKey ?? getEnvApiKey(model.provider) ?? "";
144
+ let copilotDynamicHeaders;
145
+ if (model.provider === "github-copilot") {
146
+ const hasImages = hasCopilotVisionInput(context.messages);
147
+ copilotDynamicHeaders = buildCopilotDynamicHeaders({
148
+ messages: context.messages,
149
+ hasImages,
150
+ });
151
+ }
152
+ const created = createClient(model, apiKey, options?.interleavedThinking ?? true, options?.headers, copilotDynamicHeaders);
153
+ client = created.client;
154
+ isOAuth = created.isOAuthToken;
155
+ }
156
+ let params = buildParams(model, context, isOAuth, options);
157
+ const nextParams = await options?.onPayload?.(params, model);
158
+ if (nextParams !== undefined) {
159
+ params = nextParams;
160
+ }
161
+ const anthropicStream = client.messages.stream({ ...params, stream: true }, { signal: options?.signal });
162
+ stream.push({ type: "start", partial: output });
163
+ const blocks = output.content;
164
+ for await (const event of anthropicStream) {
165
+ if (event.type === "message_start") {
166
+ output.responseId = event.message.id;
167
+ // Capture initial token usage from message_start event
168
+ // This ensures we have input token counts even if the stream is aborted early
169
+ output.usage.input = event.message.usage.input_tokens || 0;
170
+ output.usage.output = event.message.usage.output_tokens || 0;
171
+ output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;
172
+ output.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;
173
+ // Anthropic doesn't provide total_tokens, compute from components
174
+ output.usage.totalTokens =
175
+ output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
176
+ calculateCost(model, output.usage);
177
+ }
178
+ else if (event.type === "content_block_start") {
179
+ if (event.content_block.type === "text") {
180
+ const block = {
181
+ type: "text",
182
+ text: "",
183
+ index: event.index,
184
+ };
185
+ output.content.push(block);
186
+ stream.push({ type: "text_start", contentIndex: output.content.length - 1, partial: output });
187
+ }
188
+ else if (event.content_block.type === "thinking") {
189
+ const block = {
190
+ type: "thinking",
191
+ thinking: "",
192
+ thinkingSignature: "",
193
+ index: event.index,
194
+ };
195
+ output.content.push(block);
196
+ stream.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
197
+ }
198
+ else if (event.content_block.type === "redacted_thinking") {
199
+ const block = {
200
+ type: "thinking",
201
+ thinking: "[Reasoning redacted]",
202
+ thinkingSignature: event.content_block.data,
203
+ redacted: true,
204
+ index: event.index,
205
+ };
206
+ output.content.push(block);
207
+ stream.push({ type: "thinking_start", contentIndex: output.content.length - 1, partial: output });
208
+ }
209
+ else if (event.content_block.type === "tool_use") {
210
+ const block = {
211
+ type: "toolCall",
212
+ id: event.content_block.id,
213
+ name: isOAuth
214
+ ? fromClaudeCodeName(event.content_block.name, context.tools)
215
+ : event.content_block.name,
216
+ arguments: event.content_block.input ?? {},
217
+ partialJson: "",
218
+ index: event.index,
219
+ };
220
+ output.content.push(block);
221
+ stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });
222
+ }
223
+ }
224
+ else if (event.type === "content_block_delta") {
225
+ if (event.delta.type === "text_delta") {
226
+ const index = blocks.findIndex((b) => b.index === event.index);
227
+ const block = blocks[index];
228
+ if (block && block.type === "text") {
229
+ block.text += event.delta.text;
230
+ stream.push({
231
+ type: "text_delta",
232
+ contentIndex: index,
233
+ delta: event.delta.text,
234
+ partial: output,
235
+ });
236
+ }
237
+ }
238
+ else if (event.delta.type === "thinking_delta") {
239
+ const index = blocks.findIndex((b) => b.index === event.index);
240
+ const block = blocks[index];
241
+ if (block && block.type === "thinking") {
242
+ block.thinking += event.delta.thinking;
243
+ stream.push({
244
+ type: "thinking_delta",
245
+ contentIndex: index,
246
+ delta: event.delta.thinking,
247
+ partial: output,
248
+ });
249
+ }
250
+ }
251
+ else if (event.delta.type === "input_json_delta") {
252
+ const index = blocks.findIndex((b) => b.index === event.index);
253
+ const block = blocks[index];
254
+ if (block && block.type === "toolCall") {
255
+ block.partialJson += event.delta.partial_json;
256
+ block.arguments = parseStreamingJson(block.partialJson);
257
+ stream.push({
258
+ type: "toolcall_delta",
259
+ contentIndex: index,
260
+ delta: event.delta.partial_json,
261
+ partial: output,
262
+ });
263
+ }
264
+ }
265
+ else if (event.delta.type === "signature_delta") {
266
+ const index = blocks.findIndex((b) => b.index === event.index);
267
+ const block = blocks[index];
268
+ if (block && block.type === "thinking") {
269
+ block.thinkingSignature = block.thinkingSignature || "";
270
+ block.thinkingSignature += event.delta.signature;
271
+ }
272
+ }
273
+ }
274
+ else if (event.type === "content_block_stop") {
275
+ const index = blocks.findIndex((b) => b.index === event.index);
276
+ const block = blocks[index];
277
+ if (block) {
278
+ delete block.index;
279
+ if (block.type === "text") {
280
+ stream.push({
281
+ type: "text_end",
282
+ contentIndex: index,
283
+ content: block.text,
284
+ partial: output,
285
+ });
286
+ }
287
+ else if (block.type === "thinking") {
288
+ stream.push({
289
+ type: "thinking_end",
290
+ contentIndex: index,
291
+ content: block.thinking,
292
+ partial: output,
293
+ });
294
+ }
295
+ else if (block.type === "toolCall") {
296
+ block.arguments = parseStreamingJson(block.partialJson);
297
+ delete block.partialJson;
298
+ stream.push({
299
+ type: "toolcall_end",
300
+ contentIndex: index,
301
+ toolCall: block,
302
+ partial: output,
303
+ });
304
+ }
305
+ }
306
+ }
307
+ else if (event.type === "message_delta") {
308
+ if (event.delta.stop_reason) {
309
+ output.stopReason = mapStopReason(event.delta.stop_reason);
310
+ }
311
+ // Only update usage fields if present (not null).
312
+ // Preserves input_tokens from message_start when proxies omit it in message_delta.
313
+ if (event.usage.input_tokens != null) {
314
+ output.usage.input = event.usage.input_tokens;
315
+ }
316
+ if (event.usage.output_tokens != null) {
317
+ output.usage.output = event.usage.output_tokens;
318
+ }
319
+ if (event.usage.cache_read_input_tokens != null) {
320
+ output.usage.cacheRead = event.usage.cache_read_input_tokens;
321
+ }
322
+ if (event.usage.cache_creation_input_tokens != null) {
323
+ output.usage.cacheWrite = event.usage.cache_creation_input_tokens;
324
+ }
325
+ // Anthropic doesn't provide total_tokens, compute from components
326
+ output.usage.totalTokens =
327
+ output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
328
+ calculateCost(model, output.usage);
329
+ }
330
+ }
331
+ if (options?.signal?.aborted) {
332
+ throw new Error("Request was aborted");
333
+ }
334
+ if (output.stopReason === "aborted" || output.stopReason === "error") {
335
+ throw new Error("An unknown error occurred");
336
+ }
337
+ stream.push({ type: "done", reason: output.stopReason, message: output });
338
+ stream.end();
339
+ }
340
+ catch (error) {
341
+ for (const block of output.content)
342
+ delete block.index;
343
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
344
+ output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
345
+ stream.push({ type: "error", reason: output.stopReason, error: output });
346
+ stream.end();
347
+ }
348
+ })();
349
+ return stream;
350
+ };
351
+ /**
352
+ * Check if a model supports adaptive thinking (Opus 4.6 and Sonnet 4.6)
353
+ */
354
+ function supportsAdaptiveThinking(modelId) {
355
+ // Opus 4.6 and Sonnet 4.6 model IDs (with or without date suffix)
356
+ return (modelId.includes("opus-4-6") ||
357
+ modelId.includes("opus-4.6") ||
358
+ modelId.includes("sonnet-4-6") ||
359
+ modelId.includes("sonnet-4.6"));
360
+ }
361
+ /**
362
+ * Map ThinkingLevel to Anthropic effort levels for adaptive thinking.
363
+ * Note: effort "max" is only valid on Opus 4.6.
364
+ */
365
+ function mapThinkingLevelToEffort(level, modelId) {
366
+ switch (level) {
367
+ case "minimal":
368
+ return "low";
369
+ case "low":
370
+ return "low";
371
+ case "medium":
372
+ return "medium";
373
+ case "high":
374
+ return "high";
375
+ case "xhigh":
376
+ return modelId.includes("opus-4-6") || modelId.includes("opus-4.6") ? "max" : "high";
377
+ default:
378
+ return "high";
379
+ }
380
+ }
381
+ export const streamSimpleAnthropic = (model, context, options) => {
382
+ const apiKey = options?.apiKey || getEnvApiKey(model.provider);
383
+ if (!apiKey) {
384
+ throw new Error(`No API key for provider: ${model.provider}`);
385
+ }
386
+ const base = buildBaseOptions(model, options, apiKey);
387
+ if (!options?.reasoning) {
388
+ return streamAnthropic(model, context, { ...base, thinkingEnabled: false });
389
+ }
390
+ // For Opus 4.6 and Sonnet 4.6: use adaptive thinking with effort level
391
+ // For older models: use budget-based thinking
392
+ if (supportsAdaptiveThinking(model.id)) {
393
+ const effort = mapThinkingLevelToEffort(options.reasoning, model.id);
394
+ return streamAnthropic(model, context, {
395
+ ...base,
396
+ thinkingEnabled: true,
397
+ effort,
398
+ });
399
+ }
400
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens || 0, model.maxTokens, options.reasoning, options.thinkingBudgets);
401
+ return streamAnthropic(model, context, {
402
+ ...base,
403
+ maxTokens: adjusted.maxTokens,
404
+ thinkingEnabled: true,
405
+ thinkingBudgetTokens: adjusted.thinkingBudget,
406
+ });
407
+ };
408
+ function isOAuthToken(apiKey) {
409
+ return apiKey.includes("sk-ant-oat");
410
+ }
411
+ function createClient(model, apiKey, interleavedThinking, optionsHeaders, dynamicHeaders) {
412
+ // Adaptive thinking models (Opus 4.6, Sonnet 4.6) have interleaved thinking built-in.
413
+ // The beta header is deprecated on Opus 4.6 and redundant on Sonnet 4.6, so skip it.
414
+ const needsInterleavedBeta = interleavedThinking && !supportsAdaptiveThinking(model.id);
415
+ // Copilot: Bearer auth, selective betas (no fine-grained-tool-streaming)
416
+ if (model.provider === "github-copilot") {
417
+ const betaFeatures = [];
418
+ if (needsInterleavedBeta) {
419
+ betaFeatures.push("interleaved-thinking-2025-05-14");
420
+ }
421
+ const client = new Anthropic({
422
+ apiKey: null,
423
+ authToken: apiKey,
424
+ baseURL: model.baseUrl,
425
+ dangerouslyAllowBrowser: true,
426
+ defaultHeaders: mergeHeaders({
427
+ accept: "application/json",
428
+ "anthropic-dangerous-direct-browser-access": "true",
429
+ ...(betaFeatures.length > 0 ? { "anthropic-beta": betaFeatures.join(",") } : {}),
430
+ }, model.headers, dynamicHeaders, optionsHeaders),
431
+ });
432
+ return { client, isOAuthToken: false };
433
+ }
434
+ const betaFeatures = ["fine-grained-tool-streaming-2025-05-14"];
435
+ if (needsInterleavedBeta) {
436
+ betaFeatures.push("interleaved-thinking-2025-05-14");
437
+ }
438
+ // OAuth: Bearer auth, Claude Code identity headers
439
+ if (isOAuthToken(apiKey)) {
440
+ const client = new Anthropic({
441
+ apiKey: null,
442
+ authToken: apiKey,
443
+ baseURL: model.baseUrl,
444
+ dangerouslyAllowBrowser: true,
445
+ defaultHeaders: mergeHeaders({
446
+ accept: "application/json",
447
+ "anthropic-dangerous-direct-browser-access": "true",
448
+ "anthropic-beta": `claude-code-20250219,oauth-2025-04-20,${betaFeatures.join(",")}`,
449
+ "user-agent": `claude-cli/${claudeCodeVersion}`,
450
+ "x-app": "cli",
451
+ }, model.headers, optionsHeaders),
452
+ });
453
+ return { client, isOAuthToken: true };
454
+ }
455
+ // API key auth
456
+ const client = new Anthropic({
457
+ apiKey,
458
+ baseURL: model.baseUrl,
459
+ dangerouslyAllowBrowser: true,
460
+ defaultHeaders: mergeHeaders({
461
+ accept: "application/json",
462
+ "anthropic-dangerous-direct-browser-access": "true",
463
+ "anthropic-beta": betaFeatures.join(","),
464
+ }, model.headers, optionsHeaders),
465
+ });
466
+ return { client, isOAuthToken: false };
467
+ }
468
+ function buildParams(model, context, isOAuthToken, options) {
469
+ const { cacheControl } = getCacheControl(model.baseUrl, options?.cacheRetention);
470
+ const params = {
471
+ model: model.id,
472
+ messages: convertMessages(context.messages, model, isOAuthToken, cacheControl),
473
+ max_tokens: options?.maxTokens || (model.maxTokens / 3) | 0,
474
+ stream: true,
475
+ };
476
+ // For OAuth tokens, we MUST include Claude Code identity
477
+ if (isOAuthToken) {
478
+ params.system = [
479
+ {
480
+ type: "text",
481
+ text: "You are Claude Code, Anthropic's official CLI for Claude.",
482
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
483
+ },
484
+ ];
485
+ if (context.systemPrompt) {
486
+ params.system.push({
487
+ type: "text",
488
+ text: sanitizeSurrogates(context.systemPrompt),
489
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
490
+ });
491
+ }
492
+ }
493
+ else if (context.systemPrompt) {
494
+ // Add cache control to system prompt for non-OAuth tokens
495
+ params.system = [
496
+ {
497
+ type: "text",
498
+ text: sanitizeSurrogates(context.systemPrompt),
499
+ ...(cacheControl ? { cache_control: cacheControl } : {}),
500
+ },
501
+ ];
502
+ }
503
+ // Temperature is incompatible with extended thinking (adaptive or budget-based).
504
+ if (options?.temperature !== undefined && !options?.thinkingEnabled) {
505
+ params.temperature = options.temperature;
506
+ }
507
+ if (context.tools) {
508
+ params.tools = convertTools(context.tools, isOAuthToken);
509
+ }
510
+ // Configure thinking mode: adaptive (Opus 4.6 and Sonnet 4.6),
511
+ // budget-based (older models), or explicitly disabled.
512
+ if (model.reasoning) {
513
+ if (options?.thinkingEnabled) {
514
+ if (supportsAdaptiveThinking(model.id)) {
515
+ // Adaptive thinking: Claude decides when and how much to think
516
+ params.thinking = { type: "adaptive" };
517
+ if (options.effort) {
518
+ params.output_config = { effort: options.effort };
519
+ }
520
+ }
521
+ else {
522
+ // Budget-based thinking for older models
523
+ params.thinking = {
524
+ type: "enabled",
525
+ budget_tokens: options.thinkingBudgetTokens || 1024,
526
+ };
527
+ }
528
+ }
529
+ else if (options?.thinkingEnabled === false) {
530
+ params.thinking = { type: "disabled" };
531
+ }
532
+ }
533
+ if (options?.metadata) {
534
+ const userId = options.metadata.user_id;
535
+ if (typeof userId === "string") {
536
+ params.metadata = { user_id: userId };
537
+ }
538
+ }
539
+ if (options?.toolChoice) {
540
+ if (typeof options.toolChoice === "string") {
541
+ params.tool_choice = { type: options.toolChoice };
542
+ }
543
+ else {
544
+ params.tool_choice = options.toolChoice;
545
+ }
546
+ }
547
+ return params;
548
+ }
549
+ // Normalize tool call IDs to match Anthropic's required pattern and length
550
+ function normalizeToolCallId(id) {
551
+ return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
552
+ }
553
+ function convertMessages(messages, model, isOAuthToken, cacheControl) {
554
+ const params = [];
555
+ // Transform messages for cross-provider compatibility
556
+ const transformedMessages = transformMessages(messages, model, normalizeToolCallId);
557
+ for (let i = 0; i < transformedMessages.length; i++) {
558
+ const msg = transformedMessages[i];
559
+ if (msg.role === "user") {
560
+ if (typeof msg.content === "string") {
561
+ if (msg.content.trim().length > 0) {
562
+ params.push({
563
+ role: "user",
564
+ content: sanitizeSurrogates(msg.content),
565
+ });
566
+ }
567
+ }
568
+ else {
569
+ const blocks = msg.content.map((item) => {
570
+ if (item.type === "text") {
571
+ return {
572
+ type: "text",
573
+ text: sanitizeSurrogates(item.text),
574
+ };
575
+ }
576
+ else {
577
+ return {
578
+ type: "image",
579
+ source: {
580
+ type: "base64",
581
+ media_type: item.mimeType,
582
+ data: item.data,
583
+ },
584
+ };
585
+ }
586
+ });
587
+ let filteredBlocks = !model?.input.includes("image") ? blocks.filter((b) => b.type !== "image") : blocks;
588
+ filteredBlocks = filteredBlocks.filter((b) => {
589
+ if (b.type === "text") {
590
+ return b.text.trim().length > 0;
591
+ }
592
+ return true;
593
+ });
594
+ if (filteredBlocks.length === 0)
595
+ continue;
596
+ params.push({
597
+ role: "user",
598
+ content: filteredBlocks,
599
+ });
600
+ }
601
+ }
602
+ else if (msg.role === "assistant") {
603
+ const blocks = [];
604
+ for (const block of msg.content) {
605
+ if (block.type === "text") {
606
+ if (block.text.trim().length === 0)
607
+ continue;
608
+ blocks.push({
609
+ type: "text",
610
+ text: sanitizeSurrogates(block.text),
611
+ });
612
+ }
613
+ else if (block.type === "thinking") {
614
+ // Redacted thinking: pass the opaque payload back as redacted_thinking
615
+ if (block.redacted) {
616
+ blocks.push({
617
+ type: "redacted_thinking",
618
+ data: block.thinkingSignature,
619
+ });
620
+ continue;
621
+ }
622
+ if (block.thinking.trim().length === 0)
623
+ continue;
624
+ // If thinking signature is missing/empty (e.g., from aborted stream),
625
+ // convert to plain text block without <thinking> tags to avoid API rejection
626
+ // and prevent Claude from mimicking the tags in responses
627
+ if (!block.thinkingSignature || block.thinkingSignature.trim().length === 0) {
628
+ blocks.push({
629
+ type: "text",
630
+ text: sanitizeSurrogates(block.thinking),
631
+ });
632
+ }
633
+ else {
634
+ blocks.push({
635
+ type: "thinking",
636
+ thinking: sanitizeSurrogates(block.thinking),
637
+ signature: block.thinkingSignature,
638
+ });
639
+ }
640
+ }
641
+ else if (block.type === "toolCall") {
642
+ blocks.push({
643
+ type: "tool_use",
644
+ id: block.id,
645
+ name: isOAuthToken ? toClaudeCodeName(block.name) : block.name,
646
+ input: block.arguments ?? {},
647
+ });
648
+ }
649
+ }
650
+ if (blocks.length === 0)
651
+ continue;
652
+ params.push({
653
+ role: "assistant",
654
+ content: blocks,
655
+ });
656
+ }
657
+ else if (msg.role === "toolResult") {
658
+ // Collect all consecutive toolResult messages, needed for z.ai Anthropic endpoint
659
+ const toolResults = [];
660
+ // Add the current tool result
661
+ toolResults.push({
662
+ type: "tool_result",
663
+ tool_use_id: msg.toolCallId,
664
+ content: convertContentBlocks(msg.content),
665
+ is_error: msg.isError,
666
+ });
667
+ // Look ahead for consecutive toolResult messages
668
+ let j = i + 1;
669
+ while (j < transformedMessages.length && transformedMessages[j].role === "toolResult") {
670
+ const nextMsg = transformedMessages[j]; // We know it's a toolResult
671
+ toolResults.push({
672
+ type: "tool_result",
673
+ tool_use_id: nextMsg.toolCallId,
674
+ content: convertContentBlocks(nextMsg.content),
675
+ is_error: nextMsg.isError,
676
+ });
677
+ j++;
678
+ }
679
+ // Skip the messages we've already processed
680
+ i = j - 1;
681
+ // Add a single user message with all tool results
682
+ params.push({
683
+ role: "user",
684
+ content: toolResults,
685
+ });
686
+ }
687
+ }
688
+ // Add cache_control to the last user message to cache conversation history
689
+ if (cacheControl && params.length > 0) {
690
+ const lastMessage = params[params.length - 1];
691
+ if (lastMessage.role === "user") {
692
+ if (Array.isArray(lastMessage.content)) {
693
+ const lastBlock = lastMessage.content[lastMessage.content.length - 1];
694
+ if (lastBlock &&
695
+ (lastBlock.type === "text" || lastBlock.type === "image" || lastBlock.type === "tool_result")) {
696
+ lastBlock.cache_control = cacheControl;
697
+ }
698
+ }
699
+ else if (typeof lastMessage.content === "string") {
700
+ lastMessage.content = [
701
+ {
702
+ type: "text",
703
+ text: lastMessage.content,
704
+ cache_control: cacheControl,
705
+ },
706
+ ];
707
+ }
708
+ }
709
+ }
710
+ return params;
711
+ }
712
+ function convertTools(tools, isOAuthToken) {
713
+ if (!tools)
714
+ return [];
715
+ return tools.map((tool) => {
716
+ const jsonSchema = tool.parameters; // TypeBox already generates JSON Schema
717
+ return {
718
+ name: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name,
719
+ description: tool.description,
720
+ input_schema: {
721
+ type: "object",
722
+ properties: jsonSchema.properties || {},
723
+ required: jsonSchema.required || [],
724
+ },
725
+ };
726
+ });
727
+ }
728
+ function mapStopReason(reason) {
729
+ switch (reason) {
730
+ case "end_turn":
731
+ return "stop";
732
+ case "max_tokens":
733
+ return "length";
734
+ case "tool_use":
735
+ return "toolUse";
736
+ case "refusal":
737
+ return "error";
738
+ case "pause_turn": // Stop is good enough -> resubmit
739
+ return "stop";
740
+ case "stop_sequence":
741
+ return "stop"; // We don't supply stop sequences, so this should never happen
742
+ case "sensitive": // Content flagged by safety filters (not yet in SDK types)
743
+ return "error";
744
+ default:
745
+ // Handle unknown stop reasons gracefully (API may add new values)
746
+ throw new Error(`Unhandled stop reason: ${reason}`);
747
+ }
748
+ }
749
+ //# sourceMappingURL=anthropic.js.map