@apholdings/jensen-ai 0.0.1

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