solid-translate 0.2.0 → 1.0.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.
@@ -0,0 +1,1165 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ NoSuchModelError,
4
+ UnsupportedFunctionalityError,
5
+ combineHeaders,
6
+ convertUint8ArrayToBase64,
7
+ createEventSourceResponseHandler,
8
+ createJsonErrorResponseHandler,
9
+ createJsonResponseHandler,
10
+ loadApiKey,
11
+ parseProviderOptions,
12
+ postJsonToApi,
13
+ resolve,
14
+ withoutTrailingSlash
15
+ } from "./chunk-CIKZ6PF7.js";
16
+ import "./chunk-FYS2JH42.js";
17
+
18
+ // node_modules/@ai-sdk/anthropic/dist/index.mjs
19
+ import { z as z2 } from "zod";
20
+ import { z } from "zod";
21
+ import { z as z3 } from "zod";
22
+ var anthropicErrorDataSchema = z.object({
23
+ type: z.literal("error"),
24
+ error: z.object({
25
+ type: z.string(),
26
+ message: z.string()
27
+ })
28
+ });
29
+ var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
30
+ errorSchema: anthropicErrorDataSchema,
31
+ errorToMessage: (data) => data.error.message
32
+ });
33
+ function prepareTools(mode) {
34
+ var _a;
35
+ const tools = ((_a = mode.tools) == null ? void 0 : _a.length) ? mode.tools : void 0;
36
+ const toolWarnings = [];
37
+ const betas = /* @__PURE__ */ new Set();
38
+ if (tools == null) {
39
+ return { tools: void 0, tool_choice: void 0, toolWarnings, betas };
40
+ }
41
+ const anthropicTools2 = [];
42
+ for (const tool of tools) {
43
+ switch (tool.type) {
44
+ case "function":
45
+ anthropicTools2.push({
46
+ name: tool.name,
47
+ description: tool.description,
48
+ input_schema: tool.parameters
49
+ });
50
+ break;
51
+ case "provider-defined":
52
+ switch (tool.id) {
53
+ case "anthropic.computer_20250124":
54
+ betas.add("computer-use-2025-01-24");
55
+ anthropicTools2.push({
56
+ name: tool.name,
57
+ type: "computer_20250124",
58
+ display_width_px: tool.args.displayWidthPx,
59
+ display_height_px: tool.args.displayHeightPx,
60
+ display_number: tool.args.displayNumber
61
+ });
62
+ break;
63
+ case "anthropic.computer_20241022":
64
+ betas.add("computer-use-2024-10-22");
65
+ anthropicTools2.push({
66
+ name: tool.name,
67
+ type: "computer_20241022",
68
+ display_width_px: tool.args.displayWidthPx,
69
+ display_height_px: tool.args.displayHeightPx,
70
+ display_number: tool.args.displayNumber
71
+ });
72
+ break;
73
+ case "anthropic.text_editor_20250124":
74
+ betas.add("computer-use-2025-01-24");
75
+ anthropicTools2.push({
76
+ name: tool.name,
77
+ type: "text_editor_20250124"
78
+ });
79
+ break;
80
+ case "anthropic.text_editor_20241022":
81
+ betas.add("computer-use-2024-10-22");
82
+ anthropicTools2.push({
83
+ name: tool.name,
84
+ type: "text_editor_20241022"
85
+ });
86
+ break;
87
+ case "anthropic.bash_20250124":
88
+ betas.add("computer-use-2025-01-24");
89
+ anthropicTools2.push({
90
+ name: tool.name,
91
+ type: "bash_20250124"
92
+ });
93
+ break;
94
+ case "anthropic.bash_20241022":
95
+ betas.add("computer-use-2024-10-22");
96
+ anthropicTools2.push({
97
+ name: tool.name,
98
+ type: "bash_20241022"
99
+ });
100
+ break;
101
+ default:
102
+ toolWarnings.push({ type: "unsupported-tool", tool });
103
+ break;
104
+ }
105
+ break;
106
+ default:
107
+ toolWarnings.push({ type: "unsupported-tool", tool });
108
+ break;
109
+ }
110
+ }
111
+ const toolChoice = mode.toolChoice;
112
+ if (toolChoice == null) {
113
+ return {
114
+ tools: anthropicTools2,
115
+ tool_choice: void 0,
116
+ toolWarnings,
117
+ betas
118
+ };
119
+ }
120
+ const type = toolChoice.type;
121
+ switch (type) {
122
+ case "auto":
123
+ return {
124
+ tools: anthropicTools2,
125
+ tool_choice: { type: "auto" },
126
+ toolWarnings,
127
+ betas
128
+ };
129
+ case "required":
130
+ return {
131
+ tools: anthropicTools2,
132
+ tool_choice: { type: "any" },
133
+ toolWarnings,
134
+ betas
135
+ };
136
+ case "none":
137
+ return { tools: void 0, tool_choice: void 0, toolWarnings, betas };
138
+ case "tool":
139
+ return {
140
+ tools: anthropicTools2,
141
+ tool_choice: { type: "tool", name: toolChoice.toolName },
142
+ toolWarnings,
143
+ betas
144
+ };
145
+ default: {
146
+ const _exhaustiveCheck = type;
147
+ throw new UnsupportedFunctionalityError({
148
+ functionality: `Unsupported tool choice type: ${_exhaustiveCheck}`
149
+ });
150
+ }
151
+ }
152
+ }
153
+ function convertToAnthropicMessagesPrompt({
154
+ prompt,
155
+ sendReasoning,
156
+ warnings
157
+ }) {
158
+ var _a, _b, _c, _d;
159
+ const betas = /* @__PURE__ */ new Set();
160
+ const blocks = groupIntoBlocks(prompt);
161
+ let system = void 0;
162
+ const messages = [];
163
+ function getCacheControl(providerMetadata) {
164
+ var _a2;
165
+ const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic;
166
+ const cacheControlValue = (_a2 = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a2 : anthropic2 == null ? void 0 : anthropic2.cache_control;
167
+ return cacheControlValue;
168
+ }
169
+ for (let i = 0; i < blocks.length; i++) {
170
+ const block = blocks[i];
171
+ const isLastBlock = i === blocks.length - 1;
172
+ const type = block.type;
173
+ switch (type) {
174
+ case "system": {
175
+ if (system != null) {
176
+ throw new UnsupportedFunctionalityError({
177
+ functionality: "Multiple system messages that are separated by user/assistant messages"
178
+ });
179
+ }
180
+ system = block.messages.map(({ content, providerMetadata }) => ({
181
+ type: "text",
182
+ text: content,
183
+ cache_control: getCacheControl(providerMetadata)
184
+ }));
185
+ break;
186
+ }
187
+ case "user": {
188
+ const anthropicContent = [];
189
+ for (const message of block.messages) {
190
+ const { role, content } = message;
191
+ switch (role) {
192
+ case "user": {
193
+ for (let j = 0; j < content.length; j++) {
194
+ const part = content[j];
195
+ const isLastPart = j === content.length - 1;
196
+ const cacheControl = (_a = getCacheControl(part.providerMetadata)) != null ? _a : isLastPart ? getCacheControl(message.providerMetadata) : void 0;
197
+ switch (part.type) {
198
+ case "text": {
199
+ anthropicContent.push({
200
+ type: "text",
201
+ text: part.text,
202
+ cache_control: cacheControl
203
+ });
204
+ break;
205
+ }
206
+ case "image": {
207
+ anthropicContent.push({
208
+ type: "image",
209
+ source: part.image instanceof URL ? {
210
+ type: "url",
211
+ url: part.image.toString()
212
+ } : {
213
+ type: "base64",
214
+ media_type: (_b = part.mimeType) != null ? _b : "image/jpeg",
215
+ data: convertUint8ArrayToBase64(part.image)
216
+ },
217
+ cache_control: cacheControl
218
+ });
219
+ break;
220
+ }
221
+ case "file": {
222
+ if (part.mimeType !== "application/pdf") {
223
+ throw new UnsupportedFunctionalityError({
224
+ functionality: "Non-PDF files in user messages"
225
+ });
226
+ }
227
+ betas.add("pdfs-2024-09-25");
228
+ anthropicContent.push({
229
+ type: "document",
230
+ source: part.data instanceof URL ? {
231
+ type: "url",
232
+ url: part.data.toString()
233
+ } : {
234
+ type: "base64",
235
+ media_type: "application/pdf",
236
+ data: part.data
237
+ },
238
+ cache_control: cacheControl
239
+ });
240
+ break;
241
+ }
242
+ }
243
+ }
244
+ break;
245
+ }
246
+ case "tool": {
247
+ for (let i2 = 0; i2 < content.length; i2++) {
248
+ const part = content[i2];
249
+ const isLastPart = i2 === content.length - 1;
250
+ const cacheControl = (_c = getCacheControl(part.providerMetadata)) != null ? _c : isLastPart ? getCacheControl(message.providerMetadata) : void 0;
251
+ const toolResultContent = part.content != null ? part.content.map((part2) => {
252
+ var _a2;
253
+ switch (part2.type) {
254
+ case "text":
255
+ return {
256
+ type: "text",
257
+ text: part2.text,
258
+ cache_control: void 0
259
+ };
260
+ case "image":
261
+ return {
262
+ type: "image",
263
+ source: {
264
+ type: "base64",
265
+ media_type: (_a2 = part2.mimeType) != null ? _a2 : "image/jpeg",
266
+ data: part2.data
267
+ },
268
+ cache_control: void 0
269
+ };
270
+ }
271
+ }) : JSON.stringify(part.result);
272
+ anthropicContent.push({
273
+ type: "tool_result",
274
+ tool_use_id: part.toolCallId,
275
+ content: toolResultContent,
276
+ is_error: part.isError,
277
+ cache_control: cacheControl
278
+ });
279
+ }
280
+ break;
281
+ }
282
+ default: {
283
+ const _exhaustiveCheck = role;
284
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
285
+ }
286
+ }
287
+ }
288
+ messages.push({ role: "user", content: anthropicContent });
289
+ break;
290
+ }
291
+ case "assistant": {
292
+ const anthropicContent = [];
293
+ for (let j = 0; j < block.messages.length; j++) {
294
+ const message = block.messages[j];
295
+ const isLastMessage = j === block.messages.length - 1;
296
+ const { content } = message;
297
+ for (let k = 0; k < content.length; k++) {
298
+ const part = content[k];
299
+ const isLastContentPart = k === content.length - 1;
300
+ const cacheControl = (_d = getCacheControl(part.providerMetadata)) != null ? _d : isLastContentPart ? getCacheControl(message.providerMetadata) : void 0;
301
+ switch (part.type) {
302
+ case "text": {
303
+ anthropicContent.push({
304
+ type: "text",
305
+ text: (
306
+ // trim the last text part if it's the last message in the block
307
+ // because Anthropic does not allow trailing whitespace
308
+ // in pre-filled assistant responses
309
+ isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text
310
+ ),
311
+ cache_control: cacheControl
312
+ });
313
+ break;
314
+ }
315
+ case "reasoning": {
316
+ if (sendReasoning) {
317
+ anthropicContent.push({
318
+ type: "thinking",
319
+ thinking: part.text,
320
+ signature: part.signature,
321
+ cache_control: cacheControl
322
+ });
323
+ } else {
324
+ warnings.push({
325
+ type: "other",
326
+ message: "sending reasoning content is disabled for this model"
327
+ });
328
+ }
329
+ break;
330
+ }
331
+ case "redacted-reasoning": {
332
+ anthropicContent.push({
333
+ type: "redacted_thinking",
334
+ data: part.data,
335
+ cache_control: cacheControl
336
+ });
337
+ break;
338
+ }
339
+ case "tool-call": {
340
+ anthropicContent.push({
341
+ type: "tool_use",
342
+ id: part.toolCallId,
343
+ name: part.toolName,
344
+ input: part.args,
345
+ cache_control: cacheControl
346
+ });
347
+ break;
348
+ }
349
+ }
350
+ }
351
+ }
352
+ messages.push({ role: "assistant", content: anthropicContent });
353
+ break;
354
+ }
355
+ default: {
356
+ const _exhaustiveCheck = type;
357
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
358
+ }
359
+ }
360
+ }
361
+ return {
362
+ prompt: { system, messages },
363
+ betas
364
+ };
365
+ }
366
+ function groupIntoBlocks(prompt) {
367
+ const blocks = [];
368
+ let currentBlock = void 0;
369
+ for (const message of prompt) {
370
+ const { role } = message;
371
+ switch (role) {
372
+ case "system": {
373
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "system") {
374
+ currentBlock = { type: "system", messages: [] };
375
+ blocks.push(currentBlock);
376
+ }
377
+ currentBlock.messages.push(message);
378
+ break;
379
+ }
380
+ case "assistant": {
381
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "assistant") {
382
+ currentBlock = { type: "assistant", messages: [] };
383
+ blocks.push(currentBlock);
384
+ }
385
+ currentBlock.messages.push(message);
386
+ break;
387
+ }
388
+ case "user": {
389
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
390
+ currentBlock = { type: "user", messages: [] };
391
+ blocks.push(currentBlock);
392
+ }
393
+ currentBlock.messages.push(message);
394
+ break;
395
+ }
396
+ case "tool": {
397
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
398
+ currentBlock = { type: "user", messages: [] };
399
+ blocks.push(currentBlock);
400
+ }
401
+ currentBlock.messages.push(message);
402
+ break;
403
+ }
404
+ default: {
405
+ const _exhaustiveCheck = role;
406
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
407
+ }
408
+ }
409
+ }
410
+ return blocks;
411
+ }
412
+ function mapAnthropicStopReason(finishReason) {
413
+ switch (finishReason) {
414
+ case "end_turn":
415
+ case "stop_sequence":
416
+ return "stop";
417
+ case "tool_use":
418
+ return "tool-calls";
419
+ case "max_tokens":
420
+ return "length";
421
+ default:
422
+ return "unknown";
423
+ }
424
+ }
425
+ var AnthropicMessagesLanguageModel = class {
426
+ constructor(modelId, settings, config) {
427
+ this.specificationVersion = "v1";
428
+ this.defaultObjectGenerationMode = "tool";
429
+ this.modelId = modelId;
430
+ this.settings = settings;
431
+ this.config = config;
432
+ }
433
+ supportsUrl(url) {
434
+ return url.protocol === "https:";
435
+ }
436
+ get provider() {
437
+ return this.config.provider;
438
+ }
439
+ get supportsImageUrls() {
440
+ return this.config.supportsImageUrls;
441
+ }
442
+ async getArgs({
443
+ mode,
444
+ prompt,
445
+ maxTokens = 4096,
446
+ // 4096: max model output tokens TODO update default in v5
447
+ temperature,
448
+ topP,
449
+ topK,
450
+ frequencyPenalty,
451
+ presencePenalty,
452
+ stopSequences,
453
+ responseFormat,
454
+ seed,
455
+ providerMetadata: providerOptions
456
+ }) {
457
+ var _a, _b, _c;
458
+ const type = mode.type;
459
+ const warnings = [];
460
+ if (frequencyPenalty != null) {
461
+ warnings.push({
462
+ type: "unsupported-setting",
463
+ setting: "frequencyPenalty"
464
+ });
465
+ }
466
+ if (presencePenalty != null) {
467
+ warnings.push({
468
+ type: "unsupported-setting",
469
+ setting: "presencePenalty"
470
+ });
471
+ }
472
+ if (seed != null) {
473
+ warnings.push({
474
+ type: "unsupported-setting",
475
+ setting: "seed"
476
+ });
477
+ }
478
+ if (responseFormat != null && responseFormat.type !== "text") {
479
+ warnings.push({
480
+ type: "unsupported-setting",
481
+ setting: "responseFormat",
482
+ details: "JSON response format is not supported."
483
+ });
484
+ }
485
+ const { prompt: messagesPrompt, betas: messagesBetas } = convertToAnthropicMessagesPrompt({
486
+ prompt,
487
+ sendReasoning: (_a = this.settings.sendReasoning) != null ? _a : true,
488
+ warnings
489
+ });
490
+ const anthropicOptions = parseProviderOptions({
491
+ provider: "anthropic",
492
+ providerOptions,
493
+ schema: anthropicProviderOptionsSchema
494
+ });
495
+ const isThinking = ((_b = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _b.type) === "enabled";
496
+ const thinkingBudget = (_c = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _c.budgetTokens;
497
+ const baseArgs = {
498
+ // model id:
499
+ model: this.modelId,
500
+ // standardized settings:
501
+ max_tokens: maxTokens,
502
+ temperature,
503
+ top_k: topK,
504
+ top_p: topP,
505
+ stop_sequences: stopSequences,
506
+ // provider specific settings:
507
+ ...isThinking && {
508
+ thinking: { type: "enabled", budget_tokens: thinkingBudget }
509
+ },
510
+ // prompt:
511
+ system: messagesPrompt.system,
512
+ messages: messagesPrompt.messages
513
+ };
514
+ if (isThinking) {
515
+ if (thinkingBudget == null) {
516
+ throw new UnsupportedFunctionalityError({
517
+ functionality: "thinking requires a budget"
518
+ });
519
+ }
520
+ if (baseArgs.temperature != null) {
521
+ baseArgs.temperature = void 0;
522
+ warnings.push({
523
+ type: "unsupported-setting",
524
+ setting: "temperature",
525
+ details: "temperature is not supported when thinking is enabled"
526
+ });
527
+ }
528
+ if (topK != null) {
529
+ baseArgs.top_k = void 0;
530
+ warnings.push({
531
+ type: "unsupported-setting",
532
+ setting: "topK",
533
+ details: "topK is not supported when thinking is enabled"
534
+ });
535
+ }
536
+ if (topP != null) {
537
+ baseArgs.top_p = void 0;
538
+ warnings.push({
539
+ type: "unsupported-setting",
540
+ setting: "topP",
541
+ details: "topP is not supported when thinking is enabled"
542
+ });
543
+ }
544
+ baseArgs.max_tokens = maxTokens + thinkingBudget;
545
+ }
546
+ switch (type) {
547
+ case "regular": {
548
+ const {
549
+ tools,
550
+ tool_choice,
551
+ toolWarnings,
552
+ betas: toolsBetas
553
+ } = prepareTools(mode);
554
+ return {
555
+ args: { ...baseArgs, tools, tool_choice },
556
+ warnings: [...warnings, ...toolWarnings],
557
+ betas: /* @__PURE__ */ new Set([...messagesBetas, ...toolsBetas])
558
+ };
559
+ }
560
+ case "object-json": {
561
+ throw new UnsupportedFunctionalityError({
562
+ functionality: "json-mode object generation"
563
+ });
564
+ }
565
+ case "object-tool": {
566
+ const { name, description, parameters } = mode.tool;
567
+ return {
568
+ args: {
569
+ ...baseArgs,
570
+ tools: [{ name, description, input_schema: parameters }],
571
+ tool_choice: { type: "tool", name }
572
+ },
573
+ warnings,
574
+ betas: messagesBetas
575
+ };
576
+ }
577
+ default: {
578
+ const _exhaustiveCheck = type;
579
+ throw new Error(`Unsupported type: ${_exhaustiveCheck}`);
580
+ }
581
+ }
582
+ }
583
+ async getHeaders({
584
+ betas,
585
+ headers
586
+ }) {
587
+ return combineHeaders(
588
+ await resolve(this.config.headers),
589
+ betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {},
590
+ headers
591
+ );
592
+ }
593
+ buildRequestUrl(isStreaming) {
594
+ var _a, _b, _c;
595
+ return (_c = (_b = (_a = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;
596
+ }
597
+ transformRequestBody(args) {
598
+ var _a, _b, _c;
599
+ return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;
600
+ }
601
+ async doGenerate(options) {
602
+ var _a, _b, _c, _d;
603
+ const { args, warnings, betas } = await this.getArgs(options);
604
+ const {
605
+ responseHeaders,
606
+ value: response,
607
+ rawValue: rawResponse
608
+ } = await postJsonToApi({
609
+ url: this.buildRequestUrl(false),
610
+ headers: await this.getHeaders({ betas, headers: options.headers }),
611
+ body: this.transformRequestBody(args),
612
+ failedResponseHandler: anthropicFailedResponseHandler,
613
+ successfulResponseHandler: createJsonResponseHandler(
614
+ anthropicMessagesResponseSchema
615
+ ),
616
+ abortSignal: options.abortSignal,
617
+ fetch: this.config.fetch
618
+ });
619
+ const { messages: rawPrompt, ...rawSettings } = args;
620
+ let text = "";
621
+ for (const content of response.content) {
622
+ if (content.type === "text") {
623
+ text += content.text;
624
+ }
625
+ }
626
+ let toolCalls = void 0;
627
+ if (response.content.some((content) => content.type === "tool_use")) {
628
+ toolCalls = [];
629
+ for (const content of response.content) {
630
+ if (content.type === "tool_use") {
631
+ toolCalls.push({
632
+ toolCallType: "function",
633
+ toolCallId: content.id,
634
+ toolName: content.name,
635
+ args: JSON.stringify(content.input)
636
+ });
637
+ }
638
+ }
639
+ }
640
+ const reasoning = response.content.filter(
641
+ (content) => content.type === "redacted_thinking" || content.type === "thinking"
642
+ ).map(
643
+ (content) => content.type === "thinking" ? {
644
+ type: "text",
645
+ text: content.thinking,
646
+ signature: content.signature
647
+ } : {
648
+ type: "redacted",
649
+ data: content.data
650
+ }
651
+ );
652
+ return {
653
+ text,
654
+ reasoning: reasoning.length > 0 ? reasoning : void 0,
655
+ toolCalls,
656
+ finishReason: mapAnthropicStopReason(response.stop_reason),
657
+ usage: {
658
+ promptTokens: response.usage.input_tokens,
659
+ completionTokens: response.usage.output_tokens
660
+ },
661
+ rawCall: { rawPrompt, rawSettings },
662
+ rawResponse: {
663
+ headers: responseHeaders,
664
+ body: rawResponse
665
+ },
666
+ response: {
667
+ id: (_a = response.id) != null ? _a : void 0,
668
+ modelId: (_b = response.model) != null ? _b : void 0
669
+ },
670
+ warnings,
671
+ providerMetadata: {
672
+ anthropic: {
673
+ cacheCreationInputTokens: (_c = response.usage.cache_creation_input_tokens) != null ? _c : null,
674
+ cacheReadInputTokens: (_d = response.usage.cache_read_input_tokens) != null ? _d : null
675
+ }
676
+ },
677
+ request: { body: JSON.stringify(args) }
678
+ };
679
+ }
680
+ async doStream(options) {
681
+ const { args, warnings, betas } = await this.getArgs(options);
682
+ const body = { ...args, stream: true };
683
+ const { responseHeaders, value: response } = await postJsonToApi({
684
+ url: this.buildRequestUrl(true),
685
+ headers: await this.getHeaders({ betas, headers: options.headers }),
686
+ body: this.transformRequestBody(body),
687
+ failedResponseHandler: anthropicFailedResponseHandler,
688
+ successfulResponseHandler: createEventSourceResponseHandler(
689
+ anthropicMessagesChunkSchema
690
+ ),
691
+ abortSignal: options.abortSignal,
692
+ fetch: this.config.fetch
693
+ });
694
+ const { messages: rawPrompt, ...rawSettings } = args;
695
+ let finishReason = "unknown";
696
+ const usage = {
697
+ promptTokens: Number.NaN,
698
+ completionTokens: Number.NaN
699
+ };
700
+ const toolCallContentBlocks = {};
701
+ let providerMetadata = void 0;
702
+ let blockType = void 0;
703
+ return {
704
+ stream: response.pipeThrough(
705
+ new TransformStream({
706
+ transform(chunk, controller) {
707
+ var _a, _b, _c, _d;
708
+ if (!chunk.success) {
709
+ controller.enqueue({ type: "error", error: chunk.error });
710
+ return;
711
+ }
712
+ const value = chunk.value;
713
+ switch (value.type) {
714
+ case "ping": {
715
+ return;
716
+ }
717
+ case "content_block_start": {
718
+ const contentBlockType = value.content_block.type;
719
+ blockType = contentBlockType;
720
+ switch (contentBlockType) {
721
+ case "text":
722
+ case "thinking": {
723
+ return;
724
+ }
725
+ case "redacted_thinking": {
726
+ controller.enqueue({
727
+ type: "redacted-reasoning",
728
+ data: value.content_block.data
729
+ });
730
+ return;
731
+ }
732
+ case "tool_use": {
733
+ toolCallContentBlocks[value.index] = {
734
+ toolCallId: value.content_block.id,
735
+ toolName: value.content_block.name,
736
+ jsonText: ""
737
+ };
738
+ return;
739
+ }
740
+ default: {
741
+ const _exhaustiveCheck = contentBlockType;
742
+ throw new Error(
743
+ `Unsupported content block type: ${_exhaustiveCheck}`
744
+ );
745
+ }
746
+ }
747
+ }
748
+ case "content_block_stop": {
749
+ if (toolCallContentBlocks[value.index] != null) {
750
+ const contentBlock = toolCallContentBlocks[value.index];
751
+ controller.enqueue({
752
+ type: "tool-call",
753
+ toolCallType: "function",
754
+ toolCallId: contentBlock.toolCallId,
755
+ toolName: contentBlock.toolName,
756
+ args: contentBlock.jsonText
757
+ });
758
+ delete toolCallContentBlocks[value.index];
759
+ }
760
+ blockType = void 0;
761
+ return;
762
+ }
763
+ case "content_block_delta": {
764
+ const deltaType = value.delta.type;
765
+ switch (deltaType) {
766
+ case "text_delta": {
767
+ controller.enqueue({
768
+ type: "text-delta",
769
+ textDelta: value.delta.text
770
+ });
771
+ return;
772
+ }
773
+ case "thinking_delta": {
774
+ controller.enqueue({
775
+ type: "reasoning",
776
+ textDelta: value.delta.thinking
777
+ });
778
+ return;
779
+ }
780
+ case "signature_delta": {
781
+ if (blockType === "thinking") {
782
+ controller.enqueue({
783
+ type: "reasoning-signature",
784
+ signature: value.delta.signature
785
+ });
786
+ }
787
+ return;
788
+ }
789
+ case "input_json_delta": {
790
+ const contentBlock = toolCallContentBlocks[value.index];
791
+ controller.enqueue({
792
+ type: "tool-call-delta",
793
+ toolCallType: "function",
794
+ toolCallId: contentBlock.toolCallId,
795
+ toolName: contentBlock.toolName,
796
+ argsTextDelta: value.delta.partial_json
797
+ });
798
+ contentBlock.jsonText += value.delta.partial_json;
799
+ return;
800
+ }
801
+ default: {
802
+ const _exhaustiveCheck = deltaType;
803
+ throw new Error(
804
+ `Unsupported delta type: ${_exhaustiveCheck}`
805
+ );
806
+ }
807
+ }
808
+ }
809
+ case "message_start": {
810
+ usage.promptTokens = value.message.usage.input_tokens;
811
+ usage.completionTokens = value.message.usage.output_tokens;
812
+ providerMetadata = {
813
+ anthropic: {
814
+ cacheCreationInputTokens: (_a = value.message.usage.cache_creation_input_tokens) != null ? _a : null,
815
+ cacheReadInputTokens: (_b = value.message.usage.cache_read_input_tokens) != null ? _b : null
816
+ }
817
+ };
818
+ controller.enqueue({
819
+ type: "response-metadata",
820
+ id: (_c = value.message.id) != null ? _c : void 0,
821
+ modelId: (_d = value.message.model) != null ? _d : void 0
822
+ });
823
+ return;
824
+ }
825
+ case "message_delta": {
826
+ usage.completionTokens = value.usage.output_tokens;
827
+ finishReason = mapAnthropicStopReason(value.delta.stop_reason);
828
+ return;
829
+ }
830
+ case "message_stop": {
831
+ controller.enqueue({
832
+ type: "finish",
833
+ finishReason,
834
+ usage,
835
+ providerMetadata
836
+ });
837
+ return;
838
+ }
839
+ case "error": {
840
+ controller.enqueue({ type: "error", error: value.error });
841
+ return;
842
+ }
843
+ default: {
844
+ const _exhaustiveCheck = value;
845
+ throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);
846
+ }
847
+ }
848
+ }
849
+ })
850
+ ),
851
+ rawCall: { rawPrompt, rawSettings },
852
+ rawResponse: { headers: responseHeaders },
853
+ warnings,
854
+ request: { body: JSON.stringify(body) }
855
+ };
856
+ }
857
+ };
858
+ var anthropicMessagesResponseSchema = z2.object({
859
+ type: z2.literal("message"),
860
+ id: z2.string().nullish(),
861
+ model: z2.string().nullish(),
862
+ content: z2.array(
863
+ z2.discriminatedUnion("type", [
864
+ z2.object({
865
+ type: z2.literal("text"),
866
+ text: z2.string()
867
+ }),
868
+ z2.object({
869
+ type: z2.literal("thinking"),
870
+ thinking: z2.string(),
871
+ signature: z2.string()
872
+ }),
873
+ z2.object({
874
+ type: z2.literal("redacted_thinking"),
875
+ data: z2.string()
876
+ }),
877
+ z2.object({
878
+ type: z2.literal("tool_use"),
879
+ id: z2.string(),
880
+ name: z2.string(),
881
+ input: z2.unknown()
882
+ })
883
+ ])
884
+ ),
885
+ stop_reason: z2.string().nullish(),
886
+ usage: z2.object({
887
+ input_tokens: z2.number(),
888
+ output_tokens: z2.number(),
889
+ cache_creation_input_tokens: z2.number().nullish(),
890
+ cache_read_input_tokens: z2.number().nullish()
891
+ })
892
+ });
893
+ var anthropicMessagesChunkSchema = z2.discriminatedUnion("type", [
894
+ z2.object({
895
+ type: z2.literal("message_start"),
896
+ message: z2.object({
897
+ id: z2.string().nullish(),
898
+ model: z2.string().nullish(),
899
+ usage: z2.object({
900
+ input_tokens: z2.number(),
901
+ output_tokens: z2.number(),
902
+ cache_creation_input_tokens: z2.number().nullish(),
903
+ cache_read_input_tokens: z2.number().nullish()
904
+ })
905
+ })
906
+ }),
907
+ z2.object({
908
+ type: z2.literal("content_block_start"),
909
+ index: z2.number(),
910
+ content_block: z2.discriminatedUnion("type", [
911
+ z2.object({
912
+ type: z2.literal("text"),
913
+ text: z2.string()
914
+ }),
915
+ z2.object({
916
+ type: z2.literal("thinking"),
917
+ thinking: z2.string()
918
+ }),
919
+ z2.object({
920
+ type: z2.literal("tool_use"),
921
+ id: z2.string(),
922
+ name: z2.string()
923
+ }),
924
+ z2.object({
925
+ type: z2.literal("redacted_thinking"),
926
+ data: z2.string()
927
+ })
928
+ ])
929
+ }),
930
+ z2.object({
931
+ type: z2.literal("content_block_delta"),
932
+ index: z2.number(),
933
+ delta: z2.discriminatedUnion("type", [
934
+ z2.object({
935
+ type: z2.literal("input_json_delta"),
936
+ partial_json: z2.string()
937
+ }),
938
+ z2.object({
939
+ type: z2.literal("text_delta"),
940
+ text: z2.string()
941
+ }),
942
+ z2.object({
943
+ type: z2.literal("thinking_delta"),
944
+ thinking: z2.string()
945
+ }),
946
+ z2.object({
947
+ type: z2.literal("signature_delta"),
948
+ signature: z2.string()
949
+ })
950
+ ])
951
+ }),
952
+ z2.object({
953
+ type: z2.literal("content_block_stop"),
954
+ index: z2.number()
955
+ }),
956
+ z2.object({
957
+ type: z2.literal("error"),
958
+ error: z2.object({
959
+ type: z2.string(),
960
+ message: z2.string()
961
+ })
962
+ }),
963
+ z2.object({
964
+ type: z2.literal("message_delta"),
965
+ delta: z2.object({ stop_reason: z2.string().nullish() }),
966
+ usage: z2.object({ output_tokens: z2.number() })
967
+ }),
968
+ z2.object({
969
+ type: z2.literal("message_stop")
970
+ }),
971
+ z2.object({
972
+ type: z2.literal("ping")
973
+ })
974
+ ]);
975
+ var anthropicProviderOptionsSchema = z2.object({
976
+ thinking: z2.object({
977
+ type: z2.union([z2.literal("enabled"), z2.literal("disabled")]),
978
+ budgetTokens: z2.number().optional()
979
+ }).optional()
980
+ });
981
+ var Bash20241022Parameters = z3.object({
982
+ command: z3.string(),
983
+ restart: z3.boolean().optional()
984
+ });
985
+ function bashTool_20241022(options = {}) {
986
+ return {
987
+ type: "provider-defined",
988
+ id: "anthropic.bash_20241022",
989
+ args: {},
990
+ parameters: Bash20241022Parameters,
991
+ execute: options.execute,
992
+ experimental_toToolResultContent: options.experimental_toToolResultContent
993
+ };
994
+ }
995
+ var Bash20250124Parameters = z3.object({
996
+ command: z3.string(),
997
+ restart: z3.boolean().optional()
998
+ });
999
+ function bashTool_20250124(options = {}) {
1000
+ return {
1001
+ type: "provider-defined",
1002
+ id: "anthropic.bash_20250124",
1003
+ args: {},
1004
+ parameters: Bash20250124Parameters,
1005
+ execute: options.execute,
1006
+ experimental_toToolResultContent: options.experimental_toToolResultContent
1007
+ };
1008
+ }
1009
+ var TextEditor20241022Parameters = z3.object({
1010
+ command: z3.enum(["view", "create", "str_replace", "insert", "undo_edit"]),
1011
+ path: z3.string(),
1012
+ file_text: z3.string().optional(),
1013
+ insert_line: z3.number().int().optional(),
1014
+ new_str: z3.string().optional(),
1015
+ old_str: z3.string().optional(),
1016
+ view_range: z3.array(z3.number().int()).optional()
1017
+ });
1018
+ function textEditorTool_20241022(options = {}) {
1019
+ return {
1020
+ type: "provider-defined",
1021
+ id: "anthropic.text_editor_20241022",
1022
+ args: {},
1023
+ parameters: TextEditor20241022Parameters,
1024
+ execute: options.execute,
1025
+ experimental_toToolResultContent: options.experimental_toToolResultContent
1026
+ };
1027
+ }
1028
+ var TextEditor20250124Parameters = z3.object({
1029
+ command: z3.enum(["view", "create", "str_replace", "insert", "undo_edit"]),
1030
+ path: z3.string(),
1031
+ file_text: z3.string().optional(),
1032
+ insert_line: z3.number().int().optional(),
1033
+ new_str: z3.string().optional(),
1034
+ old_str: z3.string().optional(),
1035
+ view_range: z3.array(z3.number().int()).optional()
1036
+ });
1037
+ function textEditorTool_20250124(options = {}) {
1038
+ return {
1039
+ type: "provider-defined",
1040
+ id: "anthropic.text_editor_20250124",
1041
+ args: {},
1042
+ parameters: TextEditor20250124Parameters,
1043
+ execute: options.execute,
1044
+ experimental_toToolResultContent: options.experimental_toToolResultContent
1045
+ };
1046
+ }
1047
+ var Computer20241022Parameters = z3.object({
1048
+ action: z3.enum([
1049
+ "key",
1050
+ "type",
1051
+ "mouse_move",
1052
+ "left_click",
1053
+ "left_click_drag",
1054
+ "right_click",
1055
+ "middle_click",
1056
+ "double_click",
1057
+ "screenshot",
1058
+ "cursor_position"
1059
+ ]),
1060
+ coordinate: z3.array(z3.number().int()).optional(),
1061
+ text: z3.string().optional()
1062
+ });
1063
+ function computerTool_20241022(options) {
1064
+ return {
1065
+ type: "provider-defined",
1066
+ id: "anthropic.computer_20241022",
1067
+ args: {
1068
+ displayWidthPx: options.displayWidthPx,
1069
+ displayHeightPx: options.displayHeightPx,
1070
+ displayNumber: options.displayNumber
1071
+ },
1072
+ parameters: Computer20241022Parameters,
1073
+ execute: options.execute,
1074
+ experimental_toToolResultContent: options.experimental_toToolResultContent
1075
+ };
1076
+ }
1077
+ var Computer20250124Parameters = z3.object({
1078
+ action: z3.enum([
1079
+ "key",
1080
+ "hold_key",
1081
+ "type",
1082
+ "cursor_position",
1083
+ "mouse_move",
1084
+ "left_mouse_down",
1085
+ "left_mouse_up",
1086
+ "left_click",
1087
+ "left_click_drag",
1088
+ "right_click",
1089
+ "middle_click",
1090
+ "double_click",
1091
+ "triple_click",
1092
+ "scroll",
1093
+ "wait",
1094
+ "screenshot"
1095
+ ]),
1096
+ coordinate: z3.tuple([z3.number().int(), z3.number().int()]).optional(),
1097
+ duration: z3.number().optional(),
1098
+ scroll_amount: z3.number().optional(),
1099
+ scroll_direction: z3.enum(["up", "down", "left", "right"]).optional(),
1100
+ start_coordinate: z3.tuple([z3.number().int(), z3.number().int()]).optional(),
1101
+ text: z3.string().optional()
1102
+ });
1103
+ function computerTool_20250124(options) {
1104
+ return {
1105
+ type: "provider-defined",
1106
+ id: "anthropic.computer_20250124",
1107
+ args: {
1108
+ displayWidthPx: options.displayWidthPx,
1109
+ displayHeightPx: options.displayHeightPx,
1110
+ displayNumber: options.displayNumber
1111
+ },
1112
+ parameters: Computer20250124Parameters,
1113
+ execute: options.execute,
1114
+ experimental_toToolResultContent: options.experimental_toToolResultContent
1115
+ };
1116
+ }
1117
+ var anthropicTools = {
1118
+ bash_20241022: bashTool_20241022,
1119
+ bash_20250124: bashTool_20250124,
1120
+ textEditor_20241022: textEditorTool_20241022,
1121
+ textEditor_20250124: textEditorTool_20250124,
1122
+ computer_20241022: computerTool_20241022,
1123
+ computer_20250124: computerTool_20250124
1124
+ };
1125
+ function createAnthropic(options = {}) {
1126
+ var _a;
1127
+ const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
1128
+ const getHeaders = () => ({
1129
+ "anthropic-version": "2023-06-01",
1130
+ "x-api-key": loadApiKey({
1131
+ apiKey: options.apiKey,
1132
+ environmentVariableName: "ANTHROPIC_API_KEY",
1133
+ description: "Anthropic"
1134
+ }),
1135
+ ...options.headers
1136
+ });
1137
+ const createChatModel = (modelId, settings = {}) => new AnthropicMessagesLanguageModel(modelId, settings, {
1138
+ provider: "anthropic.messages",
1139
+ baseURL,
1140
+ headers: getHeaders,
1141
+ fetch: options.fetch,
1142
+ supportsImageUrls: true
1143
+ });
1144
+ const provider = function(modelId, settings) {
1145
+ if (new.target) {
1146
+ throw new Error(
1147
+ "The Anthropic model function cannot be called with the new keyword."
1148
+ );
1149
+ }
1150
+ return createChatModel(modelId, settings);
1151
+ };
1152
+ provider.languageModel = createChatModel;
1153
+ provider.chat = createChatModel;
1154
+ provider.messages = createChatModel;
1155
+ provider.textEmbeddingModel = (modelId) => {
1156
+ throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
1157
+ };
1158
+ provider.tools = anthropicTools;
1159
+ return provider;
1160
+ }
1161
+ var anthropic = createAnthropic();
1162
+ export {
1163
+ anthropic,
1164
+ createAnthropic
1165
+ };