@snap-agent/core 0.1.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,3216 @@
1
+ import {
2
+ APICallError,
3
+ NoSuchModelError,
4
+ UnsupportedFunctionalityError,
5
+ combineHeaders,
6
+ convertToBase64,
7
+ createEventSourceResponseHandler,
8
+ createJsonErrorResponseHandler,
9
+ createJsonResponseHandler,
10
+ createProviderDefinedToolFactory,
11
+ createProviderDefinedToolFactoryWithOutputSchema,
12
+ generateId,
13
+ lazySchema,
14
+ loadApiKey,
15
+ loadOptionalSetting,
16
+ parseProviderOptions,
17
+ postJsonToApi,
18
+ resolve,
19
+ validateTypes,
20
+ withUserAgentSuffix,
21
+ withoutTrailingSlash,
22
+ zodSchema
23
+ } from "./chunk-V4TPAVOY.mjs";
24
+
25
+ // node_modules/.pnpm/@ai-sdk+anthropic@2.0.56_zod@3.25.76/node_modules/@ai-sdk/anthropic/dist/index.mjs
26
+ import { z } from "zod/v4";
27
+ import { z as z2 } from "zod/v4";
28
+ import { z as z3 } from "zod/v4";
29
+ import { z as z4 } from "zod/v4";
30
+ import { z as z5 } from "zod/v4";
31
+ import { z as z6 } from "zod/v4";
32
+ import { z as z7 } from "zod/v4";
33
+ import { z as z8 } from "zod/v4";
34
+ import { z as z9 } from "zod/v4";
35
+ import { z as z10 } from "zod/v4";
36
+ import { z as z11 } from "zod/v4";
37
+ import { z as z12 } from "zod/v4";
38
+ import { z as z13 } from "zod/v4";
39
+ import { z as z14 } from "zod/v4";
40
+ import { z as z15 } from "zod/v4";
41
+ import { z as z16 } from "zod/v4";
42
+ var VERSION = true ? "2.0.56" : "0.0.0-test";
43
+ var anthropicErrorDataSchema = lazySchema(
44
+ () => zodSchema(
45
+ z.object({
46
+ type: z.literal("error"),
47
+ error: z.object({
48
+ type: z.string(),
49
+ message: z.string()
50
+ })
51
+ })
52
+ )
53
+ );
54
+ var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
55
+ errorSchema: anthropicErrorDataSchema,
56
+ errorToMessage: (data) => data.error.message
57
+ });
58
+ var anthropicMessagesResponseSchema = lazySchema(
59
+ () => zodSchema(
60
+ z2.object({
61
+ type: z2.literal("message"),
62
+ id: z2.string().nullish(),
63
+ model: z2.string().nullish(),
64
+ content: z2.array(
65
+ z2.discriminatedUnion("type", [
66
+ z2.object({
67
+ type: z2.literal("text"),
68
+ text: z2.string(),
69
+ citations: z2.array(
70
+ z2.discriminatedUnion("type", [
71
+ z2.object({
72
+ type: z2.literal("web_search_result_location"),
73
+ cited_text: z2.string(),
74
+ url: z2.string(),
75
+ title: z2.string(),
76
+ encrypted_index: z2.string()
77
+ }),
78
+ z2.object({
79
+ type: z2.literal("page_location"),
80
+ cited_text: z2.string(),
81
+ document_index: z2.number(),
82
+ document_title: z2.string().nullable(),
83
+ start_page_number: z2.number(),
84
+ end_page_number: z2.number()
85
+ }),
86
+ z2.object({
87
+ type: z2.literal("char_location"),
88
+ cited_text: z2.string(),
89
+ document_index: z2.number(),
90
+ document_title: z2.string().nullable(),
91
+ start_char_index: z2.number(),
92
+ end_char_index: z2.number()
93
+ })
94
+ ])
95
+ ).optional()
96
+ }),
97
+ z2.object({
98
+ type: z2.literal("thinking"),
99
+ thinking: z2.string(),
100
+ signature: z2.string()
101
+ }),
102
+ z2.object({
103
+ type: z2.literal("redacted_thinking"),
104
+ data: z2.string()
105
+ }),
106
+ z2.object({
107
+ type: z2.literal("tool_use"),
108
+ id: z2.string(),
109
+ name: z2.string(),
110
+ input: z2.unknown()
111
+ }),
112
+ z2.object({
113
+ type: z2.literal("server_tool_use"),
114
+ id: z2.string(),
115
+ name: z2.string(),
116
+ input: z2.record(z2.string(), z2.unknown()).nullish()
117
+ }),
118
+ z2.object({
119
+ type: z2.literal("web_fetch_tool_result"),
120
+ tool_use_id: z2.string(),
121
+ content: z2.union([
122
+ z2.object({
123
+ type: z2.literal("web_fetch_result"),
124
+ url: z2.string(),
125
+ retrieved_at: z2.string(),
126
+ content: z2.object({
127
+ type: z2.literal("document"),
128
+ title: z2.string().nullable(),
129
+ citations: z2.object({ enabled: z2.boolean() }).optional(),
130
+ source: z2.union([
131
+ z2.object({
132
+ type: z2.literal("base64"),
133
+ media_type: z2.literal("application/pdf"),
134
+ data: z2.string()
135
+ }),
136
+ z2.object({
137
+ type: z2.literal("text"),
138
+ media_type: z2.literal("text/plain"),
139
+ data: z2.string()
140
+ })
141
+ ])
142
+ })
143
+ }),
144
+ z2.object({
145
+ type: z2.literal("web_fetch_tool_result_error"),
146
+ error_code: z2.string()
147
+ })
148
+ ])
149
+ }),
150
+ z2.object({
151
+ type: z2.literal("web_search_tool_result"),
152
+ tool_use_id: z2.string(),
153
+ content: z2.union([
154
+ z2.array(
155
+ z2.object({
156
+ type: z2.literal("web_search_result"),
157
+ url: z2.string(),
158
+ title: z2.string(),
159
+ encrypted_content: z2.string(),
160
+ page_age: z2.string().nullish()
161
+ })
162
+ ),
163
+ z2.object({
164
+ type: z2.literal("web_search_tool_result_error"),
165
+ error_code: z2.string()
166
+ })
167
+ ])
168
+ }),
169
+ // code execution results for code_execution_20250522 tool:
170
+ z2.object({
171
+ type: z2.literal("code_execution_tool_result"),
172
+ tool_use_id: z2.string(),
173
+ content: z2.union([
174
+ z2.object({
175
+ type: z2.literal("code_execution_result"),
176
+ stdout: z2.string(),
177
+ stderr: z2.string(),
178
+ return_code: z2.number()
179
+ }),
180
+ z2.object({
181
+ type: z2.literal("code_execution_tool_result_error"),
182
+ error_code: z2.string()
183
+ })
184
+ ])
185
+ }),
186
+ // bash code execution results for code_execution_20250825 tool:
187
+ z2.object({
188
+ type: z2.literal("bash_code_execution_tool_result"),
189
+ tool_use_id: z2.string(),
190
+ content: z2.discriminatedUnion("type", [
191
+ z2.object({
192
+ type: z2.literal("bash_code_execution_result"),
193
+ content: z2.array(
194
+ z2.object({
195
+ type: z2.literal("bash_code_execution_output"),
196
+ file_id: z2.string()
197
+ })
198
+ ),
199
+ stdout: z2.string(),
200
+ stderr: z2.string(),
201
+ return_code: z2.number()
202
+ }),
203
+ z2.object({
204
+ type: z2.literal("bash_code_execution_tool_result_error"),
205
+ error_code: z2.string()
206
+ })
207
+ ])
208
+ }),
209
+ // text editor code execution results for code_execution_20250825 tool:
210
+ z2.object({
211
+ type: z2.literal("text_editor_code_execution_tool_result"),
212
+ tool_use_id: z2.string(),
213
+ content: z2.discriminatedUnion("type", [
214
+ z2.object({
215
+ type: z2.literal("text_editor_code_execution_tool_result_error"),
216
+ error_code: z2.string()
217
+ }),
218
+ z2.object({
219
+ type: z2.literal("text_editor_code_execution_view_result"),
220
+ content: z2.string(),
221
+ file_type: z2.string(),
222
+ num_lines: z2.number().nullable(),
223
+ start_line: z2.number().nullable(),
224
+ total_lines: z2.number().nullable()
225
+ }),
226
+ z2.object({
227
+ type: z2.literal("text_editor_code_execution_create_result"),
228
+ is_file_update: z2.boolean()
229
+ }),
230
+ z2.object({
231
+ type: z2.literal(
232
+ "text_editor_code_execution_str_replace_result"
233
+ ),
234
+ lines: z2.array(z2.string()).nullable(),
235
+ new_lines: z2.number().nullable(),
236
+ new_start: z2.number().nullable(),
237
+ old_lines: z2.number().nullable(),
238
+ old_start: z2.number().nullable()
239
+ })
240
+ ])
241
+ })
242
+ ])
243
+ ),
244
+ stop_reason: z2.string().nullish(),
245
+ stop_sequence: z2.string().nullish(),
246
+ usage: z2.looseObject({
247
+ input_tokens: z2.number(),
248
+ output_tokens: z2.number(),
249
+ cache_creation_input_tokens: z2.number().nullish(),
250
+ cache_read_input_tokens: z2.number().nullish()
251
+ }),
252
+ container: z2.object({
253
+ expires_at: z2.string(),
254
+ id: z2.string(),
255
+ skills: z2.array(
256
+ z2.object({
257
+ type: z2.union([z2.literal("anthropic"), z2.literal("custom")]),
258
+ skill_id: z2.string(),
259
+ version: z2.string()
260
+ })
261
+ ).nullish()
262
+ }).nullish()
263
+ })
264
+ )
265
+ );
266
+ var anthropicMessagesChunkSchema = lazySchema(
267
+ () => zodSchema(
268
+ z2.discriminatedUnion("type", [
269
+ z2.object({
270
+ type: z2.literal("message_start"),
271
+ message: z2.object({
272
+ id: z2.string().nullish(),
273
+ model: z2.string().nullish(),
274
+ usage: z2.looseObject({
275
+ input_tokens: z2.number(),
276
+ cache_creation_input_tokens: z2.number().nullish(),
277
+ cache_read_input_tokens: z2.number().nullish()
278
+ })
279
+ })
280
+ }),
281
+ z2.object({
282
+ type: z2.literal("content_block_start"),
283
+ index: z2.number(),
284
+ content_block: z2.discriminatedUnion("type", [
285
+ z2.object({
286
+ type: z2.literal("text"),
287
+ text: z2.string()
288
+ }),
289
+ z2.object({
290
+ type: z2.literal("thinking"),
291
+ thinking: z2.string()
292
+ }),
293
+ z2.object({
294
+ type: z2.literal("tool_use"),
295
+ id: z2.string(),
296
+ name: z2.string()
297
+ }),
298
+ z2.object({
299
+ type: z2.literal("redacted_thinking"),
300
+ data: z2.string()
301
+ }),
302
+ z2.object({
303
+ type: z2.literal("server_tool_use"),
304
+ id: z2.string(),
305
+ name: z2.string(),
306
+ input: z2.record(z2.string(), z2.unknown()).nullish()
307
+ }),
308
+ z2.object({
309
+ type: z2.literal("web_fetch_tool_result"),
310
+ tool_use_id: z2.string(),
311
+ content: z2.union([
312
+ z2.object({
313
+ type: z2.literal("web_fetch_result"),
314
+ url: z2.string(),
315
+ retrieved_at: z2.string(),
316
+ content: z2.object({
317
+ type: z2.literal("document"),
318
+ title: z2.string().nullable(),
319
+ citations: z2.object({ enabled: z2.boolean() }).optional(),
320
+ source: z2.union([
321
+ z2.object({
322
+ type: z2.literal("base64"),
323
+ media_type: z2.literal("application/pdf"),
324
+ data: z2.string()
325
+ }),
326
+ z2.object({
327
+ type: z2.literal("text"),
328
+ media_type: z2.literal("text/plain"),
329
+ data: z2.string()
330
+ })
331
+ ])
332
+ })
333
+ }),
334
+ z2.object({
335
+ type: z2.literal("web_fetch_tool_result_error"),
336
+ error_code: z2.string()
337
+ })
338
+ ])
339
+ }),
340
+ z2.object({
341
+ type: z2.literal("web_search_tool_result"),
342
+ tool_use_id: z2.string(),
343
+ content: z2.union([
344
+ z2.array(
345
+ z2.object({
346
+ type: z2.literal("web_search_result"),
347
+ url: z2.string(),
348
+ title: z2.string(),
349
+ encrypted_content: z2.string(),
350
+ page_age: z2.string().nullish()
351
+ })
352
+ ),
353
+ z2.object({
354
+ type: z2.literal("web_search_tool_result_error"),
355
+ error_code: z2.string()
356
+ })
357
+ ])
358
+ }),
359
+ // code execution results for code_execution_20250522 tool:
360
+ z2.object({
361
+ type: z2.literal("code_execution_tool_result"),
362
+ tool_use_id: z2.string(),
363
+ content: z2.union([
364
+ z2.object({
365
+ type: z2.literal("code_execution_result"),
366
+ stdout: z2.string(),
367
+ stderr: z2.string(),
368
+ return_code: z2.number()
369
+ }),
370
+ z2.object({
371
+ type: z2.literal("code_execution_tool_result_error"),
372
+ error_code: z2.string()
373
+ })
374
+ ])
375
+ }),
376
+ // bash code execution results for code_execution_20250825 tool:
377
+ z2.object({
378
+ type: z2.literal("bash_code_execution_tool_result"),
379
+ tool_use_id: z2.string(),
380
+ content: z2.discriminatedUnion("type", [
381
+ z2.object({
382
+ type: z2.literal("bash_code_execution_result"),
383
+ content: z2.array(
384
+ z2.object({
385
+ type: z2.literal("bash_code_execution_output"),
386
+ file_id: z2.string()
387
+ })
388
+ ),
389
+ stdout: z2.string(),
390
+ stderr: z2.string(),
391
+ return_code: z2.number()
392
+ }),
393
+ z2.object({
394
+ type: z2.literal("bash_code_execution_tool_result_error"),
395
+ error_code: z2.string()
396
+ })
397
+ ])
398
+ }),
399
+ // text editor code execution results for code_execution_20250825 tool:
400
+ z2.object({
401
+ type: z2.literal("text_editor_code_execution_tool_result"),
402
+ tool_use_id: z2.string(),
403
+ content: z2.discriminatedUnion("type", [
404
+ z2.object({
405
+ type: z2.literal("text_editor_code_execution_tool_result_error"),
406
+ error_code: z2.string()
407
+ }),
408
+ z2.object({
409
+ type: z2.literal("text_editor_code_execution_view_result"),
410
+ content: z2.string(),
411
+ file_type: z2.string(),
412
+ num_lines: z2.number().nullable(),
413
+ start_line: z2.number().nullable(),
414
+ total_lines: z2.number().nullable()
415
+ }),
416
+ z2.object({
417
+ type: z2.literal("text_editor_code_execution_create_result"),
418
+ is_file_update: z2.boolean()
419
+ }),
420
+ z2.object({
421
+ type: z2.literal(
422
+ "text_editor_code_execution_str_replace_result"
423
+ ),
424
+ lines: z2.array(z2.string()).nullable(),
425
+ new_lines: z2.number().nullable(),
426
+ new_start: z2.number().nullable(),
427
+ old_lines: z2.number().nullable(),
428
+ old_start: z2.number().nullable()
429
+ })
430
+ ])
431
+ })
432
+ ])
433
+ }),
434
+ z2.object({
435
+ type: z2.literal("content_block_delta"),
436
+ index: z2.number(),
437
+ delta: z2.discriminatedUnion("type", [
438
+ z2.object({
439
+ type: z2.literal("input_json_delta"),
440
+ partial_json: z2.string()
441
+ }),
442
+ z2.object({
443
+ type: z2.literal("text_delta"),
444
+ text: z2.string()
445
+ }),
446
+ z2.object({
447
+ type: z2.literal("thinking_delta"),
448
+ thinking: z2.string()
449
+ }),
450
+ z2.object({
451
+ type: z2.literal("signature_delta"),
452
+ signature: z2.string()
453
+ }),
454
+ z2.object({
455
+ type: z2.literal("citations_delta"),
456
+ citation: z2.discriminatedUnion("type", [
457
+ z2.object({
458
+ type: z2.literal("web_search_result_location"),
459
+ cited_text: z2.string(),
460
+ url: z2.string(),
461
+ title: z2.string(),
462
+ encrypted_index: z2.string()
463
+ }),
464
+ z2.object({
465
+ type: z2.literal("page_location"),
466
+ cited_text: z2.string(),
467
+ document_index: z2.number(),
468
+ document_title: z2.string().nullable(),
469
+ start_page_number: z2.number(),
470
+ end_page_number: z2.number()
471
+ }),
472
+ z2.object({
473
+ type: z2.literal("char_location"),
474
+ cited_text: z2.string(),
475
+ document_index: z2.number(),
476
+ document_title: z2.string().nullable(),
477
+ start_char_index: z2.number(),
478
+ end_char_index: z2.number()
479
+ })
480
+ ])
481
+ })
482
+ ])
483
+ }),
484
+ z2.object({
485
+ type: z2.literal("content_block_stop"),
486
+ index: z2.number()
487
+ }),
488
+ z2.object({
489
+ type: z2.literal("error"),
490
+ error: z2.object({
491
+ type: z2.string(),
492
+ message: z2.string()
493
+ })
494
+ }),
495
+ z2.object({
496
+ type: z2.literal("message_delta"),
497
+ delta: z2.object({
498
+ stop_reason: z2.string().nullish(),
499
+ stop_sequence: z2.string().nullish(),
500
+ container: z2.object({
501
+ expires_at: z2.string(),
502
+ id: z2.string(),
503
+ skills: z2.array(
504
+ z2.object({
505
+ type: z2.union([
506
+ z2.literal("anthropic"),
507
+ z2.literal("custom")
508
+ ]),
509
+ skill_id: z2.string(),
510
+ version: z2.string()
511
+ })
512
+ ).nullish()
513
+ }).nullish()
514
+ }),
515
+ usage: z2.looseObject({
516
+ output_tokens: z2.number(),
517
+ cache_creation_input_tokens: z2.number().nullish()
518
+ })
519
+ }),
520
+ z2.object({
521
+ type: z2.literal("message_stop")
522
+ }),
523
+ z2.object({
524
+ type: z2.literal("ping")
525
+ })
526
+ ])
527
+ )
528
+ );
529
+ var anthropicReasoningMetadataSchema = lazySchema(
530
+ () => zodSchema(
531
+ z2.object({
532
+ signature: z2.string().optional(),
533
+ redactedData: z2.string().optional()
534
+ })
535
+ )
536
+ );
537
+ var anthropicFilePartProviderOptions = z3.object({
538
+ /**
539
+ * Citation configuration for this document.
540
+ * When enabled, this document will generate citations in the response.
541
+ */
542
+ citations: z3.object({
543
+ /**
544
+ * Enable citations for this document
545
+ */
546
+ enabled: z3.boolean()
547
+ }).optional(),
548
+ /**
549
+ * Custom title for the document.
550
+ * If not provided, the filename will be used.
551
+ */
552
+ title: z3.string().optional(),
553
+ /**
554
+ * Context about the document that will be passed to the model
555
+ * but not used towards cited content.
556
+ * Useful for storing document metadata as text or stringified JSON.
557
+ */
558
+ context: z3.string().optional()
559
+ });
560
+ var anthropicProviderOptions = z3.object({
561
+ sendReasoning: z3.boolean().optional(),
562
+ /**
563
+ * Determines how structured outputs are generated.
564
+ *
565
+ * - `outputFormat`: Use the `output_format` parameter to specify the structured output format.
566
+ * - `jsonTool`: Use a special 'json' tool to specify the structured output format (default).
567
+ * - `auto`: Use 'outputFormat' when supported, otherwise use 'jsonTool'.
568
+ */
569
+ structuredOutputMode: z3.enum(["outputFormat", "jsonTool", "auto"]).optional(),
570
+ /**
571
+ * Configuration for enabling Claude's extended thinking.
572
+ *
573
+ * When enabled, responses include thinking content blocks showing Claude's thinking process before the final answer.
574
+ * Requires a minimum budget of 1,024 tokens and counts towards the `max_tokens` limit.
575
+ */
576
+ thinking: z3.object({
577
+ type: z3.union([z3.literal("enabled"), z3.literal("disabled")]),
578
+ budgetTokens: z3.number().optional()
579
+ }).optional(),
580
+ /**
581
+ * Whether to disable parallel function calling during tool use. Default is false.
582
+ * When set to true, Claude will use at most one tool per response.
583
+ */
584
+ disableParallelToolUse: z3.boolean().optional(),
585
+ /**
586
+ * Cache control settings for this message.
587
+ * See https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
588
+ */
589
+ cacheControl: z3.object({
590
+ type: z3.literal("ephemeral"),
591
+ ttl: z3.union([z3.literal("5m"), z3.literal("1h")]).optional()
592
+ }).optional(),
593
+ /**
594
+ * Agent Skills configuration. Skills enable Claude to perform specialized tasks
595
+ * like document processing (PPTX, DOCX, PDF, XLSX) and data analysis.
596
+ * Requires code execution tool to be enabled.
597
+ */
598
+ container: z3.object({
599
+ id: z3.string().optional(),
600
+ skills: z3.array(
601
+ z3.object({
602
+ type: z3.union([z3.literal("anthropic"), z3.literal("custom")]),
603
+ skillId: z3.string(),
604
+ version: z3.string().optional()
605
+ })
606
+ ).optional()
607
+ }).optional(),
608
+ /**
609
+ * @default 'high'
610
+ */
611
+ effort: z3.enum(["low", "medium", "high"]).optional()
612
+ });
613
+ var MAX_CACHE_BREAKPOINTS = 4;
614
+ function getCacheControl(providerMetadata) {
615
+ var _a;
616
+ const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic;
617
+ const cacheControlValue = (_a = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a : anthropic2 == null ? void 0 : anthropic2.cache_control;
618
+ return cacheControlValue;
619
+ }
620
+ var CacheControlValidator = class {
621
+ constructor() {
622
+ this.breakpointCount = 0;
623
+ this.warnings = [];
624
+ }
625
+ getCacheControl(providerMetadata, context) {
626
+ const cacheControlValue = getCacheControl(providerMetadata);
627
+ if (!cacheControlValue) {
628
+ return void 0;
629
+ }
630
+ if (!context.canCache) {
631
+ this.warnings.push({
632
+ type: "unsupported-setting",
633
+ setting: "cacheControl",
634
+ details: `cache_control cannot be set on ${context.type}. It will be ignored.`
635
+ });
636
+ return void 0;
637
+ }
638
+ this.breakpointCount++;
639
+ if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) {
640
+ this.warnings.push({
641
+ type: "unsupported-setting",
642
+ setting: "cacheControl",
643
+ details: `Maximum ${MAX_CACHE_BREAKPOINTS} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`
644
+ });
645
+ return void 0;
646
+ }
647
+ return cacheControlValue;
648
+ }
649
+ getWarnings() {
650
+ return this.warnings;
651
+ }
652
+ };
653
+ var textEditor_20250728ArgsSchema = lazySchema(
654
+ () => zodSchema(
655
+ z4.object({
656
+ maxCharacters: z4.number().optional()
657
+ })
658
+ )
659
+ );
660
+ var textEditor_20250728InputSchema = lazySchema(
661
+ () => zodSchema(
662
+ z4.object({
663
+ command: z4.enum(["view", "create", "str_replace", "insert"]),
664
+ path: z4.string(),
665
+ file_text: z4.string().optional(),
666
+ insert_line: z4.number().int().optional(),
667
+ new_str: z4.string().optional(),
668
+ old_str: z4.string().optional(),
669
+ view_range: z4.array(z4.number().int()).optional()
670
+ })
671
+ )
672
+ );
673
+ var factory = createProviderDefinedToolFactory({
674
+ id: "anthropic.text_editor_20250728",
675
+ name: "str_replace_based_edit_tool",
676
+ inputSchema: textEditor_20250728InputSchema
677
+ });
678
+ var textEditor_20250728 = (args = {}) => {
679
+ return factory(args);
680
+ };
681
+ var webSearch_20250305ArgsSchema = lazySchema(
682
+ () => zodSchema(
683
+ z5.object({
684
+ maxUses: z5.number().optional(),
685
+ allowedDomains: z5.array(z5.string()).optional(),
686
+ blockedDomains: z5.array(z5.string()).optional(),
687
+ userLocation: z5.object({
688
+ type: z5.literal("approximate"),
689
+ city: z5.string().optional(),
690
+ region: z5.string().optional(),
691
+ country: z5.string().optional(),
692
+ timezone: z5.string().optional()
693
+ }).optional()
694
+ })
695
+ )
696
+ );
697
+ var webSearch_20250305OutputSchema = lazySchema(
698
+ () => zodSchema(
699
+ z5.array(
700
+ z5.object({
701
+ url: z5.string(),
702
+ title: z5.string().nullable(),
703
+ pageAge: z5.string().nullable(),
704
+ encryptedContent: z5.string(),
705
+ type: z5.literal("web_search_result")
706
+ })
707
+ )
708
+ )
709
+ );
710
+ var webSearch_20250305InputSchema = lazySchema(
711
+ () => zodSchema(
712
+ z5.object({
713
+ query: z5.string()
714
+ })
715
+ )
716
+ );
717
+ var factory2 = createProviderDefinedToolFactoryWithOutputSchema({
718
+ id: "anthropic.web_search_20250305",
719
+ name: "web_search",
720
+ inputSchema: webSearch_20250305InputSchema,
721
+ outputSchema: webSearch_20250305OutputSchema
722
+ });
723
+ var webSearch_20250305 = (args = {}) => {
724
+ return factory2(args);
725
+ };
726
+ var webFetch_20250910ArgsSchema = lazySchema(
727
+ () => zodSchema(
728
+ z6.object({
729
+ maxUses: z6.number().optional(),
730
+ allowedDomains: z6.array(z6.string()).optional(),
731
+ blockedDomains: z6.array(z6.string()).optional(),
732
+ citations: z6.object({ enabled: z6.boolean() }).optional(),
733
+ maxContentTokens: z6.number().optional()
734
+ })
735
+ )
736
+ );
737
+ var webFetch_20250910OutputSchema = lazySchema(
738
+ () => zodSchema(
739
+ z6.object({
740
+ type: z6.literal("web_fetch_result"),
741
+ url: z6.string(),
742
+ content: z6.object({
743
+ type: z6.literal("document"),
744
+ title: z6.string().nullable(),
745
+ citations: z6.object({ enabled: z6.boolean() }).optional(),
746
+ source: z6.union([
747
+ z6.object({
748
+ type: z6.literal("base64"),
749
+ mediaType: z6.literal("application/pdf"),
750
+ data: z6.string()
751
+ }),
752
+ z6.object({
753
+ type: z6.literal("text"),
754
+ mediaType: z6.literal("text/plain"),
755
+ data: z6.string()
756
+ })
757
+ ])
758
+ }),
759
+ retrievedAt: z6.string().nullable()
760
+ })
761
+ )
762
+ );
763
+ var webFetch_20250910InputSchema = lazySchema(
764
+ () => zodSchema(
765
+ z6.object({
766
+ url: z6.string()
767
+ })
768
+ )
769
+ );
770
+ var factory3 = createProviderDefinedToolFactoryWithOutputSchema({
771
+ id: "anthropic.web_fetch_20250910",
772
+ name: "web_fetch",
773
+ inputSchema: webFetch_20250910InputSchema,
774
+ outputSchema: webFetch_20250910OutputSchema
775
+ });
776
+ var webFetch_20250910 = (args = {}) => {
777
+ return factory3(args);
778
+ };
779
+ async function prepareTools({
780
+ tools,
781
+ toolChoice,
782
+ disableParallelToolUse,
783
+ cacheControlValidator
784
+ }) {
785
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
786
+ const toolWarnings = [];
787
+ const betas = /* @__PURE__ */ new Set();
788
+ const validator = cacheControlValidator || new CacheControlValidator();
789
+ if (tools == null) {
790
+ return { tools: void 0, toolChoice: void 0, toolWarnings, betas };
791
+ }
792
+ const anthropicTools2 = [];
793
+ for (const tool of tools) {
794
+ switch (tool.type) {
795
+ case "function": {
796
+ const cacheControl = validator.getCacheControl(tool.providerOptions, {
797
+ type: "tool definition",
798
+ canCache: true
799
+ });
800
+ anthropicTools2.push({
801
+ name: tool.name,
802
+ description: tool.description,
803
+ input_schema: tool.inputSchema,
804
+ cache_control: cacheControl
805
+ });
806
+ break;
807
+ }
808
+ case "provider-defined": {
809
+ switch (tool.id) {
810
+ case "anthropic.code_execution_20250522": {
811
+ betas.add("code-execution-2025-05-22");
812
+ anthropicTools2.push({
813
+ type: "code_execution_20250522",
814
+ name: "code_execution",
815
+ cache_control: void 0
816
+ });
817
+ break;
818
+ }
819
+ case "anthropic.code_execution_20250825": {
820
+ betas.add("code-execution-2025-08-25");
821
+ anthropicTools2.push({
822
+ type: "code_execution_20250825",
823
+ name: "code_execution"
824
+ });
825
+ break;
826
+ }
827
+ case "anthropic.computer_20250124": {
828
+ betas.add("computer-use-2025-01-24");
829
+ anthropicTools2.push({
830
+ name: "computer",
831
+ type: "computer_20250124",
832
+ display_width_px: tool.args.displayWidthPx,
833
+ display_height_px: tool.args.displayHeightPx,
834
+ display_number: tool.args.displayNumber,
835
+ cache_control: void 0
836
+ });
837
+ break;
838
+ }
839
+ case "anthropic.computer_20241022": {
840
+ betas.add("computer-use-2024-10-22");
841
+ anthropicTools2.push({
842
+ name: "computer",
843
+ type: "computer_20241022",
844
+ display_width_px: tool.args.displayWidthPx,
845
+ display_height_px: tool.args.displayHeightPx,
846
+ display_number: tool.args.displayNumber,
847
+ cache_control: void 0
848
+ });
849
+ break;
850
+ }
851
+ case "anthropic.text_editor_20250124": {
852
+ betas.add("computer-use-2025-01-24");
853
+ anthropicTools2.push({
854
+ name: "str_replace_editor",
855
+ type: "text_editor_20250124",
856
+ cache_control: void 0
857
+ });
858
+ break;
859
+ }
860
+ case "anthropic.text_editor_20241022": {
861
+ betas.add("computer-use-2024-10-22");
862
+ anthropicTools2.push({
863
+ name: "str_replace_editor",
864
+ type: "text_editor_20241022",
865
+ cache_control: void 0
866
+ });
867
+ break;
868
+ }
869
+ case "anthropic.text_editor_20250429": {
870
+ betas.add("computer-use-2025-01-24");
871
+ anthropicTools2.push({
872
+ name: "str_replace_based_edit_tool",
873
+ type: "text_editor_20250429",
874
+ cache_control: void 0
875
+ });
876
+ break;
877
+ }
878
+ case "anthropic.text_editor_20250728": {
879
+ const args = await validateTypes({
880
+ value: tool.args,
881
+ schema: textEditor_20250728ArgsSchema
882
+ });
883
+ anthropicTools2.push({
884
+ name: "str_replace_based_edit_tool",
885
+ type: "text_editor_20250728",
886
+ max_characters: args.maxCharacters,
887
+ cache_control: void 0
888
+ });
889
+ break;
890
+ }
891
+ case "anthropic.bash_20250124": {
892
+ betas.add("computer-use-2025-01-24");
893
+ anthropicTools2.push({
894
+ name: "bash",
895
+ type: "bash_20250124",
896
+ cache_control: void 0
897
+ });
898
+ break;
899
+ }
900
+ case "anthropic.bash_20241022": {
901
+ betas.add("computer-use-2024-10-22");
902
+ anthropicTools2.push({
903
+ name: "bash",
904
+ type: "bash_20241022",
905
+ cache_control: void 0
906
+ });
907
+ break;
908
+ }
909
+ case "anthropic.memory_20250818": {
910
+ betas.add("context-management-2025-06-27");
911
+ anthropicTools2.push({
912
+ name: "memory",
913
+ type: "memory_20250818"
914
+ });
915
+ break;
916
+ }
917
+ case "anthropic.web_fetch_20250910": {
918
+ betas.add("web-fetch-2025-09-10");
919
+ const args = await validateTypes({
920
+ value: tool.args,
921
+ schema: webFetch_20250910ArgsSchema
922
+ });
923
+ anthropicTools2.push({
924
+ type: "web_fetch_20250910",
925
+ name: "web_fetch",
926
+ max_uses: args.maxUses,
927
+ allowed_domains: args.allowedDomains,
928
+ blocked_domains: args.blockedDomains,
929
+ citations: args.citations,
930
+ max_content_tokens: args.maxContentTokens,
931
+ cache_control: void 0
932
+ });
933
+ break;
934
+ }
935
+ case "anthropic.web_search_20250305": {
936
+ const args = await validateTypes({
937
+ value: tool.args,
938
+ schema: webSearch_20250305ArgsSchema
939
+ });
940
+ anthropicTools2.push({
941
+ type: "web_search_20250305",
942
+ name: "web_search",
943
+ max_uses: args.maxUses,
944
+ allowed_domains: args.allowedDomains,
945
+ blocked_domains: args.blockedDomains,
946
+ user_location: args.userLocation,
947
+ cache_control: void 0
948
+ });
949
+ break;
950
+ }
951
+ default: {
952
+ toolWarnings.push({ type: "unsupported-tool", tool });
953
+ break;
954
+ }
955
+ }
956
+ break;
957
+ }
958
+ default: {
959
+ toolWarnings.push({ type: "unsupported-tool", tool });
960
+ break;
961
+ }
962
+ }
963
+ }
964
+ if (toolChoice == null) {
965
+ return {
966
+ tools: anthropicTools2,
967
+ toolChoice: disableParallelToolUse ? { type: "auto", disable_parallel_tool_use: disableParallelToolUse } : void 0,
968
+ toolWarnings,
969
+ betas
970
+ };
971
+ }
972
+ const type = toolChoice.type;
973
+ switch (type) {
974
+ case "auto":
975
+ return {
976
+ tools: anthropicTools2,
977
+ toolChoice: {
978
+ type: "auto",
979
+ disable_parallel_tool_use: disableParallelToolUse
980
+ },
981
+ toolWarnings,
982
+ betas
983
+ };
984
+ case "required":
985
+ return {
986
+ tools: anthropicTools2,
987
+ toolChoice: {
988
+ type: "any",
989
+ disable_parallel_tool_use: disableParallelToolUse
990
+ },
991
+ toolWarnings,
992
+ betas
993
+ };
994
+ case "none":
995
+ return { tools: void 0, toolChoice: void 0, toolWarnings, betas };
996
+ case "tool":
997
+ return {
998
+ tools: anthropicTools2,
999
+ toolChoice: {
1000
+ type: "tool",
1001
+ name: toolChoice.toolName,
1002
+ disable_parallel_tool_use: disableParallelToolUse
1003
+ },
1004
+ toolWarnings,
1005
+ betas
1006
+ };
1007
+ default: {
1008
+ const _exhaustiveCheck = type;
1009
+ throw new UnsupportedFunctionalityError({
1010
+ functionality: `tool choice type: ${_exhaustiveCheck}`
1011
+ });
1012
+ }
1013
+ }
1014
+ }
1015
+ var codeExecution_20250522OutputSchema = lazySchema(
1016
+ () => zodSchema(
1017
+ z7.object({
1018
+ type: z7.literal("code_execution_result"),
1019
+ stdout: z7.string(),
1020
+ stderr: z7.string(),
1021
+ return_code: z7.number()
1022
+ })
1023
+ )
1024
+ );
1025
+ var codeExecution_20250522InputSchema = lazySchema(
1026
+ () => zodSchema(
1027
+ z7.object({
1028
+ code: z7.string()
1029
+ })
1030
+ )
1031
+ );
1032
+ var factory4 = createProviderDefinedToolFactoryWithOutputSchema({
1033
+ id: "anthropic.code_execution_20250522",
1034
+ name: "code_execution",
1035
+ inputSchema: codeExecution_20250522InputSchema,
1036
+ outputSchema: codeExecution_20250522OutputSchema
1037
+ });
1038
+ var codeExecution_20250522 = (args = {}) => {
1039
+ return factory4(args);
1040
+ };
1041
+ var codeExecution_20250825OutputSchema = lazySchema(
1042
+ () => zodSchema(
1043
+ z8.discriminatedUnion("type", [
1044
+ z8.object({
1045
+ type: z8.literal("bash_code_execution_result"),
1046
+ content: z8.array(
1047
+ z8.object({
1048
+ type: z8.literal("bash_code_execution_output"),
1049
+ file_id: z8.string()
1050
+ })
1051
+ ),
1052
+ stdout: z8.string(),
1053
+ stderr: z8.string(),
1054
+ return_code: z8.number()
1055
+ }),
1056
+ z8.object({
1057
+ type: z8.literal("bash_code_execution_tool_result_error"),
1058
+ error_code: z8.string()
1059
+ }),
1060
+ z8.object({
1061
+ type: z8.literal("text_editor_code_execution_tool_result_error"),
1062
+ error_code: z8.string()
1063
+ }),
1064
+ z8.object({
1065
+ type: z8.literal("text_editor_code_execution_view_result"),
1066
+ content: z8.string(),
1067
+ file_type: z8.string(),
1068
+ num_lines: z8.number().nullable(),
1069
+ start_line: z8.number().nullable(),
1070
+ total_lines: z8.number().nullable()
1071
+ }),
1072
+ z8.object({
1073
+ type: z8.literal("text_editor_code_execution_create_result"),
1074
+ is_file_update: z8.boolean()
1075
+ }),
1076
+ z8.object({
1077
+ type: z8.literal("text_editor_code_execution_str_replace_result"),
1078
+ lines: z8.array(z8.string()).nullable(),
1079
+ new_lines: z8.number().nullable(),
1080
+ new_start: z8.number().nullable(),
1081
+ old_lines: z8.number().nullable(),
1082
+ old_start: z8.number().nullable()
1083
+ })
1084
+ ])
1085
+ )
1086
+ );
1087
+ var codeExecution_20250825InputSchema = lazySchema(
1088
+ () => zodSchema(
1089
+ z8.discriminatedUnion("type", [
1090
+ z8.object({
1091
+ type: z8.literal("bash_code_execution"),
1092
+ command: z8.string()
1093
+ }),
1094
+ z8.discriminatedUnion("command", [
1095
+ z8.object({
1096
+ type: z8.literal("text_editor_code_execution"),
1097
+ command: z8.literal("view"),
1098
+ path: z8.string()
1099
+ }),
1100
+ z8.object({
1101
+ type: z8.literal("text_editor_code_execution"),
1102
+ command: z8.literal("create"),
1103
+ path: z8.string(),
1104
+ file_text: z8.string().nullish()
1105
+ }),
1106
+ z8.object({
1107
+ type: z8.literal("text_editor_code_execution"),
1108
+ command: z8.literal("str_replace"),
1109
+ path: z8.string(),
1110
+ old_str: z8.string(),
1111
+ new_str: z8.string()
1112
+ })
1113
+ ])
1114
+ ])
1115
+ )
1116
+ );
1117
+ var factory5 = createProviderDefinedToolFactoryWithOutputSchema({
1118
+ id: "anthropic.code_execution_20250825",
1119
+ name: "code_execution",
1120
+ inputSchema: codeExecution_20250825InputSchema,
1121
+ outputSchema: codeExecution_20250825OutputSchema
1122
+ });
1123
+ var codeExecution_20250825 = (args = {}) => {
1124
+ return factory5(args);
1125
+ };
1126
+ function convertToString(data) {
1127
+ if (typeof data === "string") {
1128
+ return Buffer.from(data, "base64").toString("utf-8");
1129
+ }
1130
+ if (data instanceof Uint8Array) {
1131
+ return new TextDecoder().decode(data);
1132
+ }
1133
+ if (data instanceof URL) {
1134
+ throw new UnsupportedFunctionalityError({
1135
+ functionality: "URL-based text documents are not supported for citations"
1136
+ });
1137
+ }
1138
+ throw new UnsupportedFunctionalityError({
1139
+ functionality: `unsupported data type for text documents: ${typeof data}`
1140
+ });
1141
+ }
1142
+ async function convertToAnthropicMessagesPrompt({
1143
+ prompt,
1144
+ sendReasoning,
1145
+ warnings,
1146
+ cacheControlValidator
1147
+ }) {
1148
+ var _a, _b, _c, _d, _e;
1149
+ const betas = /* @__PURE__ */ new Set();
1150
+ const blocks = groupIntoBlocks(prompt);
1151
+ const validator = cacheControlValidator || new CacheControlValidator();
1152
+ let system = void 0;
1153
+ const messages = [];
1154
+ async function shouldEnableCitations(providerMetadata) {
1155
+ var _a2, _b2;
1156
+ const anthropicOptions = await parseProviderOptions({
1157
+ provider: "anthropic",
1158
+ providerOptions: providerMetadata,
1159
+ schema: anthropicFilePartProviderOptions
1160
+ });
1161
+ return (_b2 = (_a2 = anthropicOptions == null ? void 0 : anthropicOptions.citations) == null ? void 0 : _a2.enabled) != null ? _b2 : false;
1162
+ }
1163
+ async function getDocumentMetadata(providerMetadata) {
1164
+ const anthropicOptions = await parseProviderOptions({
1165
+ provider: "anthropic",
1166
+ providerOptions: providerMetadata,
1167
+ schema: anthropicFilePartProviderOptions
1168
+ });
1169
+ return {
1170
+ title: anthropicOptions == null ? void 0 : anthropicOptions.title,
1171
+ context: anthropicOptions == null ? void 0 : anthropicOptions.context
1172
+ };
1173
+ }
1174
+ for (let i = 0; i < blocks.length; i++) {
1175
+ const block = blocks[i];
1176
+ const isLastBlock = i === blocks.length - 1;
1177
+ const type = block.type;
1178
+ switch (type) {
1179
+ case "system": {
1180
+ if (system != null) {
1181
+ throw new UnsupportedFunctionalityError({
1182
+ functionality: "Multiple system messages that are separated by user/assistant messages"
1183
+ });
1184
+ }
1185
+ system = block.messages.map(({ content, providerOptions }) => ({
1186
+ type: "text",
1187
+ text: content,
1188
+ cache_control: validator.getCacheControl(providerOptions, {
1189
+ type: "system message",
1190
+ canCache: true
1191
+ })
1192
+ }));
1193
+ break;
1194
+ }
1195
+ case "user": {
1196
+ const anthropicContent = [];
1197
+ for (const message of block.messages) {
1198
+ const { role, content } = message;
1199
+ switch (role) {
1200
+ case "user": {
1201
+ for (let j = 0; j < content.length; j++) {
1202
+ const part = content[j];
1203
+ const isLastPart = j === content.length - 1;
1204
+ const cacheControl = (_a = validator.getCacheControl(part.providerOptions, {
1205
+ type: "user message part",
1206
+ canCache: true
1207
+ })) != null ? _a : isLastPart ? validator.getCacheControl(message.providerOptions, {
1208
+ type: "user message",
1209
+ canCache: true
1210
+ }) : void 0;
1211
+ switch (part.type) {
1212
+ case "text": {
1213
+ anthropicContent.push({
1214
+ type: "text",
1215
+ text: part.text,
1216
+ cache_control: cacheControl
1217
+ });
1218
+ break;
1219
+ }
1220
+ case "file": {
1221
+ if (part.mediaType.startsWith("image/")) {
1222
+ anthropicContent.push({
1223
+ type: "image",
1224
+ source: part.data instanceof URL ? {
1225
+ type: "url",
1226
+ url: part.data.toString()
1227
+ } : {
1228
+ type: "base64",
1229
+ media_type: part.mediaType === "image/*" ? "image/jpeg" : part.mediaType,
1230
+ data: convertToBase64(part.data)
1231
+ },
1232
+ cache_control: cacheControl
1233
+ });
1234
+ } else if (part.mediaType === "application/pdf") {
1235
+ betas.add("pdfs-2024-09-25");
1236
+ const enableCitations = await shouldEnableCitations(
1237
+ part.providerOptions
1238
+ );
1239
+ const metadata = await getDocumentMetadata(
1240
+ part.providerOptions
1241
+ );
1242
+ anthropicContent.push({
1243
+ type: "document",
1244
+ source: part.data instanceof URL ? {
1245
+ type: "url",
1246
+ url: part.data.toString()
1247
+ } : {
1248
+ type: "base64",
1249
+ media_type: "application/pdf",
1250
+ data: convertToBase64(part.data)
1251
+ },
1252
+ title: (_b = metadata.title) != null ? _b : part.filename,
1253
+ ...metadata.context && { context: metadata.context },
1254
+ ...enableCitations && {
1255
+ citations: { enabled: true }
1256
+ },
1257
+ cache_control: cacheControl
1258
+ });
1259
+ } else if (part.mediaType === "text/plain") {
1260
+ const enableCitations = await shouldEnableCitations(
1261
+ part.providerOptions
1262
+ );
1263
+ const metadata = await getDocumentMetadata(
1264
+ part.providerOptions
1265
+ );
1266
+ anthropicContent.push({
1267
+ type: "document",
1268
+ source: part.data instanceof URL ? {
1269
+ type: "url",
1270
+ url: part.data.toString()
1271
+ } : {
1272
+ type: "text",
1273
+ media_type: "text/plain",
1274
+ data: convertToString(part.data)
1275
+ },
1276
+ title: (_c = metadata.title) != null ? _c : part.filename,
1277
+ ...metadata.context && { context: metadata.context },
1278
+ ...enableCitations && {
1279
+ citations: { enabled: true }
1280
+ },
1281
+ cache_control: cacheControl
1282
+ });
1283
+ } else {
1284
+ throw new UnsupportedFunctionalityError({
1285
+ functionality: `media type: ${part.mediaType}`
1286
+ });
1287
+ }
1288
+ break;
1289
+ }
1290
+ }
1291
+ }
1292
+ break;
1293
+ }
1294
+ case "tool": {
1295
+ for (let i2 = 0; i2 < content.length; i2++) {
1296
+ const part = content[i2];
1297
+ const isLastPart = i2 === content.length - 1;
1298
+ const cacheControl = (_d = validator.getCacheControl(part.providerOptions, {
1299
+ type: "tool result part",
1300
+ canCache: true
1301
+ })) != null ? _d : isLastPart ? validator.getCacheControl(message.providerOptions, {
1302
+ type: "tool result message",
1303
+ canCache: true
1304
+ }) : void 0;
1305
+ const output = part.output;
1306
+ let contentValue;
1307
+ switch (output.type) {
1308
+ case "content":
1309
+ contentValue = output.value.map((contentPart) => {
1310
+ switch (contentPart.type) {
1311
+ case "text":
1312
+ return {
1313
+ type: "text",
1314
+ text: contentPart.text
1315
+ };
1316
+ case "media": {
1317
+ if (contentPart.mediaType.startsWith("image/")) {
1318
+ return {
1319
+ type: "image",
1320
+ source: {
1321
+ type: "base64",
1322
+ media_type: contentPart.mediaType,
1323
+ data: contentPart.data
1324
+ }
1325
+ };
1326
+ }
1327
+ if (contentPart.mediaType === "application/pdf") {
1328
+ betas.add("pdfs-2024-09-25");
1329
+ return {
1330
+ type: "document",
1331
+ source: {
1332
+ type: "base64",
1333
+ media_type: contentPart.mediaType,
1334
+ data: contentPart.data
1335
+ }
1336
+ };
1337
+ }
1338
+ throw new UnsupportedFunctionalityError({
1339
+ functionality: `media type: ${contentPart.mediaType}`
1340
+ });
1341
+ }
1342
+ }
1343
+ });
1344
+ break;
1345
+ case "text":
1346
+ case "error-text":
1347
+ contentValue = output.value;
1348
+ break;
1349
+ case "json":
1350
+ case "error-json":
1351
+ default:
1352
+ contentValue = JSON.stringify(output.value);
1353
+ break;
1354
+ }
1355
+ anthropicContent.push({
1356
+ type: "tool_result",
1357
+ tool_use_id: part.toolCallId,
1358
+ content: contentValue,
1359
+ is_error: output.type === "error-text" || output.type === "error-json" ? true : void 0,
1360
+ cache_control: cacheControl
1361
+ });
1362
+ }
1363
+ break;
1364
+ }
1365
+ default: {
1366
+ const _exhaustiveCheck = role;
1367
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1368
+ }
1369
+ }
1370
+ }
1371
+ messages.push({ role: "user", content: anthropicContent });
1372
+ break;
1373
+ }
1374
+ case "assistant": {
1375
+ const anthropicContent = [];
1376
+ for (let j = 0; j < block.messages.length; j++) {
1377
+ const message = block.messages[j];
1378
+ const isLastMessage = j === block.messages.length - 1;
1379
+ const { content } = message;
1380
+ for (let k = 0; k < content.length; k++) {
1381
+ const part = content[k];
1382
+ const isLastContentPart = k === content.length - 1;
1383
+ const cacheControl = (_e = validator.getCacheControl(part.providerOptions, {
1384
+ type: "assistant message part",
1385
+ canCache: true
1386
+ })) != null ? _e : isLastContentPart ? validator.getCacheControl(message.providerOptions, {
1387
+ type: "assistant message",
1388
+ canCache: true
1389
+ }) : void 0;
1390
+ switch (part.type) {
1391
+ case "text": {
1392
+ anthropicContent.push({
1393
+ type: "text",
1394
+ text: (
1395
+ // trim the last text part if it's the last message in the block
1396
+ // because Anthropic does not allow trailing whitespace
1397
+ // in pre-filled assistant responses
1398
+ isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text
1399
+ ),
1400
+ cache_control: cacheControl
1401
+ });
1402
+ break;
1403
+ }
1404
+ case "reasoning": {
1405
+ if (sendReasoning) {
1406
+ const reasoningMetadata = await parseProviderOptions({
1407
+ provider: "anthropic",
1408
+ providerOptions: part.providerOptions,
1409
+ schema: anthropicReasoningMetadataSchema
1410
+ });
1411
+ if (reasoningMetadata != null) {
1412
+ if (reasoningMetadata.signature != null) {
1413
+ validator.getCacheControl(part.providerOptions, {
1414
+ type: "thinking block",
1415
+ canCache: false
1416
+ });
1417
+ anthropicContent.push({
1418
+ type: "thinking",
1419
+ thinking: part.text,
1420
+ signature: reasoningMetadata.signature
1421
+ });
1422
+ } else if (reasoningMetadata.redactedData != null) {
1423
+ validator.getCacheControl(part.providerOptions, {
1424
+ type: "redacted thinking block",
1425
+ canCache: false
1426
+ });
1427
+ anthropicContent.push({
1428
+ type: "redacted_thinking",
1429
+ data: reasoningMetadata.redactedData
1430
+ });
1431
+ } else {
1432
+ warnings.push({
1433
+ type: "other",
1434
+ message: "unsupported reasoning metadata"
1435
+ });
1436
+ }
1437
+ } else {
1438
+ warnings.push({
1439
+ type: "other",
1440
+ message: "unsupported reasoning metadata"
1441
+ });
1442
+ }
1443
+ } else {
1444
+ warnings.push({
1445
+ type: "other",
1446
+ message: "sending reasoning content is disabled for this model"
1447
+ });
1448
+ }
1449
+ break;
1450
+ }
1451
+ case "tool-call": {
1452
+ if (part.providerExecuted) {
1453
+ if (part.toolName === "code_execution" && part.input != null && typeof part.input === "object" && "type" in part.input && typeof part.input.type === "string" && (part.input.type === "bash_code_execution" || part.input.type === "text_editor_code_execution")) {
1454
+ anthropicContent.push({
1455
+ type: "server_tool_use",
1456
+ id: part.toolCallId,
1457
+ name: part.input.type,
1458
+ // map back to subtool name
1459
+ input: part.input,
1460
+ cache_control: cacheControl
1461
+ });
1462
+ } else if (part.toolName === "code_execution" || // code execution 20250522
1463
+ part.toolName === "web_fetch" || part.toolName === "web_search") {
1464
+ anthropicContent.push({
1465
+ type: "server_tool_use",
1466
+ id: part.toolCallId,
1467
+ name: part.toolName,
1468
+ input: part.input,
1469
+ cache_control: cacheControl
1470
+ });
1471
+ } else {
1472
+ warnings.push({
1473
+ type: "other",
1474
+ message: `provider executed tool call for tool ${part.toolName} is not supported`
1475
+ });
1476
+ }
1477
+ break;
1478
+ }
1479
+ anthropicContent.push({
1480
+ type: "tool_use",
1481
+ id: part.toolCallId,
1482
+ name: part.toolName,
1483
+ input: part.input,
1484
+ cache_control: cacheControl
1485
+ });
1486
+ break;
1487
+ }
1488
+ case "tool-result": {
1489
+ if (part.toolName === "code_execution") {
1490
+ const output = part.output;
1491
+ if (output.type !== "json") {
1492
+ warnings.push({
1493
+ type: "other",
1494
+ message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
1495
+ });
1496
+ break;
1497
+ }
1498
+ if (output.value == null || typeof output.value !== "object" || !("type" in output.value) || typeof output.value.type !== "string") {
1499
+ warnings.push({
1500
+ type: "other",
1501
+ message: `provider executed tool result output value is not a valid code execution result for tool ${part.toolName}`
1502
+ });
1503
+ break;
1504
+ }
1505
+ if (output.value.type === "code_execution_result") {
1506
+ const codeExecutionOutput = await validateTypes({
1507
+ value: output.value,
1508
+ schema: codeExecution_20250522OutputSchema
1509
+ });
1510
+ anthropicContent.push({
1511
+ type: "code_execution_tool_result",
1512
+ tool_use_id: part.toolCallId,
1513
+ content: {
1514
+ type: codeExecutionOutput.type,
1515
+ stdout: codeExecutionOutput.stdout,
1516
+ stderr: codeExecutionOutput.stderr,
1517
+ return_code: codeExecutionOutput.return_code
1518
+ },
1519
+ cache_control: cacheControl
1520
+ });
1521
+ } else {
1522
+ const codeExecutionOutput = await validateTypes({
1523
+ value: output.value,
1524
+ schema: codeExecution_20250825OutputSchema
1525
+ });
1526
+ anthropicContent.push(
1527
+ codeExecutionOutput.type === "bash_code_execution_result" || codeExecutionOutput.type === "bash_code_execution_tool_result_error" ? {
1528
+ type: "bash_code_execution_tool_result",
1529
+ tool_use_id: part.toolCallId,
1530
+ cache_control: cacheControl,
1531
+ content: codeExecutionOutput
1532
+ } : {
1533
+ type: "text_editor_code_execution_tool_result",
1534
+ tool_use_id: part.toolCallId,
1535
+ cache_control: cacheControl,
1536
+ content: codeExecutionOutput
1537
+ }
1538
+ );
1539
+ }
1540
+ break;
1541
+ }
1542
+ if (part.toolName === "web_fetch") {
1543
+ const output = part.output;
1544
+ if (output.type !== "json") {
1545
+ warnings.push({
1546
+ type: "other",
1547
+ message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
1548
+ });
1549
+ break;
1550
+ }
1551
+ const webFetchOutput = await validateTypes({
1552
+ value: output.value,
1553
+ schema: webFetch_20250910OutputSchema
1554
+ });
1555
+ anthropicContent.push({
1556
+ type: "web_fetch_tool_result",
1557
+ tool_use_id: part.toolCallId,
1558
+ content: {
1559
+ type: "web_fetch_result",
1560
+ url: webFetchOutput.url,
1561
+ retrieved_at: webFetchOutput.retrievedAt,
1562
+ content: {
1563
+ type: "document",
1564
+ title: webFetchOutput.content.title,
1565
+ citations: webFetchOutput.content.citations,
1566
+ source: {
1567
+ type: webFetchOutput.content.source.type,
1568
+ media_type: webFetchOutput.content.source.mediaType,
1569
+ data: webFetchOutput.content.source.data
1570
+ }
1571
+ }
1572
+ },
1573
+ cache_control: cacheControl
1574
+ });
1575
+ break;
1576
+ }
1577
+ if (part.toolName === "web_search") {
1578
+ const output = part.output;
1579
+ if (output.type !== "json") {
1580
+ warnings.push({
1581
+ type: "other",
1582
+ message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
1583
+ });
1584
+ break;
1585
+ }
1586
+ const webSearchOutput = await validateTypes({
1587
+ value: output.value,
1588
+ schema: webSearch_20250305OutputSchema
1589
+ });
1590
+ anthropicContent.push({
1591
+ type: "web_search_tool_result",
1592
+ tool_use_id: part.toolCallId,
1593
+ content: webSearchOutput.map((result) => ({
1594
+ url: result.url,
1595
+ title: result.title,
1596
+ page_age: result.pageAge,
1597
+ encrypted_content: result.encryptedContent,
1598
+ type: result.type
1599
+ })),
1600
+ cache_control: cacheControl
1601
+ });
1602
+ break;
1603
+ }
1604
+ warnings.push({
1605
+ type: "other",
1606
+ message: `provider executed tool result for tool ${part.toolName} is not supported`
1607
+ });
1608
+ break;
1609
+ }
1610
+ }
1611
+ }
1612
+ }
1613
+ messages.push({ role: "assistant", content: anthropicContent });
1614
+ break;
1615
+ }
1616
+ default: {
1617
+ const _exhaustiveCheck = type;
1618
+ throw new Error(`content type: ${_exhaustiveCheck}`);
1619
+ }
1620
+ }
1621
+ }
1622
+ return {
1623
+ prompt: { system, messages },
1624
+ betas
1625
+ };
1626
+ }
1627
+ function groupIntoBlocks(prompt) {
1628
+ const blocks = [];
1629
+ let currentBlock = void 0;
1630
+ for (const message of prompt) {
1631
+ const { role } = message;
1632
+ switch (role) {
1633
+ case "system": {
1634
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "system") {
1635
+ currentBlock = { type: "system", messages: [] };
1636
+ blocks.push(currentBlock);
1637
+ }
1638
+ currentBlock.messages.push(message);
1639
+ break;
1640
+ }
1641
+ case "assistant": {
1642
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "assistant") {
1643
+ currentBlock = { type: "assistant", messages: [] };
1644
+ blocks.push(currentBlock);
1645
+ }
1646
+ currentBlock.messages.push(message);
1647
+ break;
1648
+ }
1649
+ case "user": {
1650
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
1651
+ currentBlock = { type: "user", messages: [] };
1652
+ blocks.push(currentBlock);
1653
+ }
1654
+ currentBlock.messages.push(message);
1655
+ break;
1656
+ }
1657
+ case "tool": {
1658
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
1659
+ currentBlock = { type: "user", messages: [] };
1660
+ blocks.push(currentBlock);
1661
+ }
1662
+ currentBlock.messages.push(message);
1663
+ break;
1664
+ }
1665
+ default: {
1666
+ const _exhaustiveCheck = role;
1667
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1668
+ }
1669
+ }
1670
+ }
1671
+ return blocks;
1672
+ }
1673
+ function mapAnthropicStopReason({
1674
+ finishReason,
1675
+ isJsonResponseFromTool
1676
+ }) {
1677
+ switch (finishReason) {
1678
+ case "pause_turn":
1679
+ case "end_turn":
1680
+ case "stop_sequence":
1681
+ return "stop";
1682
+ case "refusal":
1683
+ return "content-filter";
1684
+ case "tool_use":
1685
+ return isJsonResponseFromTool ? "stop" : "tool-calls";
1686
+ case "max_tokens":
1687
+ return "length";
1688
+ default:
1689
+ return "unknown";
1690
+ }
1691
+ }
1692
+ function createCitationSource(citation, citationDocuments, generateId3) {
1693
+ var _a;
1694
+ if (citation.type !== "page_location" && citation.type !== "char_location") {
1695
+ return;
1696
+ }
1697
+ const documentInfo = citationDocuments[citation.document_index];
1698
+ if (!documentInfo) {
1699
+ return;
1700
+ }
1701
+ return {
1702
+ type: "source",
1703
+ sourceType: "document",
1704
+ id: generateId3(),
1705
+ mediaType: documentInfo.mediaType,
1706
+ title: (_a = citation.document_title) != null ? _a : documentInfo.title,
1707
+ filename: documentInfo.filename,
1708
+ providerMetadata: {
1709
+ anthropic: citation.type === "page_location" ? {
1710
+ citedText: citation.cited_text,
1711
+ startPageNumber: citation.start_page_number,
1712
+ endPageNumber: citation.end_page_number
1713
+ } : {
1714
+ citedText: citation.cited_text,
1715
+ startCharIndex: citation.start_char_index,
1716
+ endCharIndex: citation.end_char_index
1717
+ }
1718
+ }
1719
+ };
1720
+ }
1721
+ var AnthropicMessagesLanguageModel = class {
1722
+ constructor(modelId, config) {
1723
+ this.specificationVersion = "v2";
1724
+ var _a;
1725
+ this.modelId = modelId;
1726
+ this.config = config;
1727
+ this.generateId = (_a = config.generateId) != null ? _a : generateId;
1728
+ }
1729
+ supportsUrl(url) {
1730
+ return url.protocol === "https:";
1731
+ }
1732
+ get provider() {
1733
+ return this.config.provider;
1734
+ }
1735
+ get supportedUrls() {
1736
+ var _a, _b, _c;
1737
+ return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
1738
+ }
1739
+ async getArgs({
1740
+ userSuppliedBetas,
1741
+ prompt,
1742
+ maxOutputTokens,
1743
+ temperature,
1744
+ topP,
1745
+ topK,
1746
+ frequencyPenalty,
1747
+ presencePenalty,
1748
+ stopSequences,
1749
+ responseFormat,
1750
+ seed,
1751
+ tools,
1752
+ toolChoice,
1753
+ providerOptions
1754
+ }) {
1755
+ var _a, _b, _c, _d, _e;
1756
+ const warnings = [];
1757
+ if (frequencyPenalty != null) {
1758
+ warnings.push({
1759
+ type: "unsupported-setting",
1760
+ setting: "frequencyPenalty"
1761
+ });
1762
+ }
1763
+ if (presencePenalty != null) {
1764
+ warnings.push({
1765
+ type: "unsupported-setting",
1766
+ setting: "presencePenalty"
1767
+ });
1768
+ }
1769
+ if (seed != null) {
1770
+ warnings.push({
1771
+ type: "unsupported-setting",
1772
+ setting: "seed"
1773
+ });
1774
+ }
1775
+ if (temperature != null && temperature > 1) {
1776
+ warnings.push({
1777
+ type: "unsupported-setting",
1778
+ setting: "temperature",
1779
+ details: `${temperature} exceeds anthropic maximum of 1.0. clamped to 1.0`
1780
+ });
1781
+ temperature = 1;
1782
+ } else if (temperature != null && temperature < 0) {
1783
+ warnings.push({
1784
+ type: "unsupported-setting",
1785
+ setting: "temperature",
1786
+ details: `${temperature} is below anthropic minimum of 0. clamped to 0`
1787
+ });
1788
+ temperature = 0;
1789
+ }
1790
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
1791
+ if (responseFormat.schema == null) {
1792
+ warnings.push({
1793
+ type: "unsupported-setting",
1794
+ setting: "responseFormat",
1795
+ details: "JSON response format requires a schema. The response format is ignored."
1796
+ });
1797
+ } else if (tools != null) {
1798
+ warnings.push({
1799
+ type: "unsupported-setting",
1800
+ setting: "tools",
1801
+ details: "JSON response format does not support tools. The provided tools are ignored."
1802
+ });
1803
+ }
1804
+ }
1805
+ const anthropicOptions = await parseProviderOptions({
1806
+ provider: "anthropic",
1807
+ providerOptions,
1808
+ schema: anthropicProviderOptions
1809
+ });
1810
+ const {
1811
+ maxOutputTokens: maxOutputTokensForModel,
1812
+ supportsStructuredOutput,
1813
+ isKnownModel
1814
+ } = getModelCapabilities(this.modelId);
1815
+ const structureOutputMode = (_a = anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _a : "jsonTool";
1816
+ const useStructuredOutput = structureOutputMode === "outputFormat" || structureOutputMode === "auto" && supportsStructuredOutput;
1817
+ const jsonResponseTool = (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !useStructuredOutput ? {
1818
+ type: "function",
1819
+ name: "json",
1820
+ description: "Respond with a JSON object.",
1821
+ inputSchema: responseFormat.schema
1822
+ } : void 0;
1823
+ const cacheControlValidator = new CacheControlValidator();
1824
+ const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({
1825
+ prompt,
1826
+ sendReasoning: (_b = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _b : true,
1827
+ warnings,
1828
+ cacheControlValidator
1829
+ });
1830
+ const isThinking = ((_c = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _c.type) === "enabled";
1831
+ const thinkingBudget = (_d = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _d.budgetTokens;
1832
+ const maxTokens = maxOutputTokens != null ? maxOutputTokens : maxOutputTokensForModel;
1833
+ const baseArgs = {
1834
+ // model id:
1835
+ model: this.modelId,
1836
+ // standardized settings:
1837
+ max_tokens: maxTokens,
1838
+ temperature,
1839
+ top_k: topK,
1840
+ top_p: topP,
1841
+ stop_sequences: stopSequences,
1842
+ // provider specific settings:
1843
+ ...isThinking && {
1844
+ thinking: { type: "enabled", budget_tokens: thinkingBudget }
1845
+ },
1846
+ ...(anthropicOptions == null ? void 0 : anthropicOptions.effort) && {
1847
+ output_config: { effort: anthropicOptions.effort }
1848
+ },
1849
+ // structured output:
1850
+ ...useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && {
1851
+ output_format: {
1852
+ type: "json_schema",
1853
+ schema: responseFormat.schema
1854
+ }
1855
+ },
1856
+ // container with agent skills:
1857
+ ...(anthropicOptions == null ? void 0 : anthropicOptions.container) && {
1858
+ container: {
1859
+ id: anthropicOptions.container.id,
1860
+ skills: (_e = anthropicOptions.container.skills) == null ? void 0 : _e.map((skill) => ({
1861
+ type: skill.type,
1862
+ skill_id: skill.skillId,
1863
+ version: skill.version
1864
+ }))
1865
+ }
1866
+ },
1867
+ // prompt:
1868
+ system: messagesPrompt.system,
1869
+ messages: messagesPrompt.messages
1870
+ };
1871
+ if (isThinking) {
1872
+ if (thinkingBudget == null) {
1873
+ throw new UnsupportedFunctionalityError({
1874
+ functionality: "thinking requires a budget"
1875
+ });
1876
+ }
1877
+ if (baseArgs.temperature != null) {
1878
+ baseArgs.temperature = void 0;
1879
+ warnings.push({
1880
+ type: "unsupported-setting",
1881
+ setting: "temperature",
1882
+ details: "temperature is not supported when thinking is enabled"
1883
+ });
1884
+ }
1885
+ if (topK != null) {
1886
+ baseArgs.top_k = void 0;
1887
+ warnings.push({
1888
+ type: "unsupported-setting",
1889
+ setting: "topK",
1890
+ details: "topK is not supported when thinking is enabled"
1891
+ });
1892
+ }
1893
+ if (topP != null) {
1894
+ baseArgs.top_p = void 0;
1895
+ warnings.push({
1896
+ type: "unsupported-setting",
1897
+ setting: "topP",
1898
+ details: "topP is not supported when thinking is enabled"
1899
+ });
1900
+ }
1901
+ baseArgs.max_tokens = maxTokens + thinkingBudget;
1902
+ }
1903
+ if (isKnownModel && baseArgs.max_tokens > maxOutputTokensForModel) {
1904
+ if (maxOutputTokens != null) {
1905
+ warnings.push({
1906
+ type: "unsupported-setting",
1907
+ setting: "maxOutputTokens",
1908
+ details: `${baseArgs.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${maxOutputTokensForModel} max output tokens. The max output tokens have been limited to ${maxOutputTokensForModel}.`
1909
+ });
1910
+ }
1911
+ baseArgs.max_tokens = maxOutputTokensForModel;
1912
+ }
1913
+ if ((anthropicOptions == null ? void 0 : anthropicOptions.container) && anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0) {
1914
+ betas.add("code-execution-2025-08-25");
1915
+ betas.add("skills-2025-10-02");
1916
+ betas.add("files-api-2025-04-14");
1917
+ if (!(tools == null ? void 0 : tools.some(
1918
+ (tool) => tool.type === "provider-defined" && tool.id === "anthropic.code_execution_20250825"
1919
+ ))) {
1920
+ warnings.push({
1921
+ type: "other",
1922
+ message: "code execution tool is required when using skills"
1923
+ });
1924
+ }
1925
+ }
1926
+ if (anthropicOptions == null ? void 0 : anthropicOptions.effort) {
1927
+ betas.add("effort-2025-11-24");
1928
+ }
1929
+ if (useStructuredOutput) {
1930
+ betas.add("structured-outputs-2025-11-13");
1931
+ }
1932
+ const {
1933
+ tools: anthropicTools2,
1934
+ toolChoice: anthropicToolChoice,
1935
+ toolWarnings,
1936
+ betas: toolsBetas
1937
+ } = await prepareTools(
1938
+ jsonResponseTool != null ? {
1939
+ tools: [jsonResponseTool],
1940
+ toolChoice: { type: "tool", toolName: jsonResponseTool.name },
1941
+ disableParallelToolUse: true,
1942
+ cacheControlValidator
1943
+ } : {
1944
+ tools: tools != null ? tools : [],
1945
+ toolChoice,
1946
+ disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse,
1947
+ cacheControlValidator
1948
+ }
1949
+ );
1950
+ const cacheWarnings = cacheControlValidator.getWarnings();
1951
+ return {
1952
+ args: {
1953
+ ...baseArgs,
1954
+ tools: anthropicTools2,
1955
+ tool_choice: anthropicToolChoice
1956
+ },
1957
+ warnings: [...warnings, ...toolWarnings, ...cacheWarnings],
1958
+ betas: /* @__PURE__ */ new Set([...betas, ...toolsBetas, ...userSuppliedBetas]),
1959
+ usesJsonResponseTool: jsonResponseTool != null
1960
+ };
1961
+ }
1962
+ async getHeaders({
1963
+ betas,
1964
+ headers
1965
+ }) {
1966
+ return combineHeaders(
1967
+ await resolve(this.config.headers),
1968
+ headers,
1969
+ betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {}
1970
+ );
1971
+ }
1972
+ async getBetasFromHeaders(requestHeaders) {
1973
+ var _a, _b;
1974
+ const configHeaders = await resolve(this.config.headers);
1975
+ const configBetaHeader = (_a = configHeaders["anthropic-beta"]) != null ? _a : "";
1976
+ const requestBetaHeader = (_b = requestHeaders == null ? void 0 : requestHeaders["anthropic-beta"]) != null ? _b : "";
1977
+ return new Set(
1978
+ [
1979
+ ...configBetaHeader.toLowerCase().split(","),
1980
+ ...requestBetaHeader.toLowerCase().split(",")
1981
+ ].map((beta) => beta.trim()).filter((beta) => beta !== "")
1982
+ );
1983
+ }
1984
+ buildRequestUrl(isStreaming) {
1985
+ var _a, _b, _c;
1986
+ return (_c = (_b = (_a = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;
1987
+ }
1988
+ transformRequestBody(args) {
1989
+ var _a, _b, _c;
1990
+ return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;
1991
+ }
1992
+ extractCitationDocuments(prompt) {
1993
+ const isCitationPart = (part) => {
1994
+ var _a, _b;
1995
+ if (part.type !== "file") {
1996
+ return false;
1997
+ }
1998
+ if (part.mediaType !== "application/pdf" && part.mediaType !== "text/plain") {
1999
+ return false;
2000
+ }
2001
+ const anthropic2 = (_a = part.providerOptions) == null ? void 0 : _a.anthropic;
2002
+ const citationsConfig = anthropic2 == null ? void 0 : anthropic2.citations;
2003
+ return (_b = citationsConfig == null ? void 0 : citationsConfig.enabled) != null ? _b : false;
2004
+ };
2005
+ return prompt.filter((message) => message.role === "user").flatMap((message) => message.content).filter(isCitationPart).map((part) => {
2006
+ var _a;
2007
+ const filePart = part;
2008
+ return {
2009
+ title: (_a = filePart.filename) != null ? _a : "Untitled Document",
2010
+ filename: filePart.filename,
2011
+ mediaType: filePart.mediaType
2012
+ };
2013
+ });
2014
+ }
2015
+ async doGenerate(options) {
2016
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2017
+ const { args, warnings, betas, usesJsonResponseTool } = await this.getArgs({
2018
+ ...options,
2019
+ userSuppliedBetas: await this.getBetasFromHeaders(options.headers)
2020
+ });
2021
+ const citationDocuments = this.extractCitationDocuments(options.prompt);
2022
+ const {
2023
+ responseHeaders,
2024
+ value: response,
2025
+ rawValue: rawResponse
2026
+ } = await postJsonToApi({
2027
+ url: this.buildRequestUrl(false),
2028
+ headers: await this.getHeaders({ betas, headers: options.headers }),
2029
+ body: this.transformRequestBody(args),
2030
+ failedResponseHandler: anthropicFailedResponseHandler,
2031
+ successfulResponseHandler: createJsonResponseHandler(
2032
+ anthropicMessagesResponseSchema
2033
+ ),
2034
+ abortSignal: options.abortSignal,
2035
+ fetch: this.config.fetch
2036
+ });
2037
+ const content = [];
2038
+ for (const part of response.content) {
2039
+ switch (part.type) {
2040
+ case "text": {
2041
+ if (!usesJsonResponseTool) {
2042
+ content.push({ type: "text", text: part.text });
2043
+ if (part.citations) {
2044
+ for (const citation of part.citations) {
2045
+ const source = createCitationSource(
2046
+ citation,
2047
+ citationDocuments,
2048
+ this.generateId
2049
+ );
2050
+ if (source) {
2051
+ content.push(source);
2052
+ }
2053
+ }
2054
+ }
2055
+ }
2056
+ break;
2057
+ }
2058
+ case "thinking": {
2059
+ content.push({
2060
+ type: "reasoning",
2061
+ text: part.thinking,
2062
+ providerMetadata: {
2063
+ anthropic: {
2064
+ signature: part.signature
2065
+ }
2066
+ }
2067
+ });
2068
+ break;
2069
+ }
2070
+ case "redacted_thinking": {
2071
+ content.push({
2072
+ type: "reasoning",
2073
+ text: "",
2074
+ providerMetadata: {
2075
+ anthropic: {
2076
+ redactedData: part.data
2077
+ }
2078
+ }
2079
+ });
2080
+ break;
2081
+ }
2082
+ case "tool_use": {
2083
+ content.push(
2084
+ // when a json response tool is used, the tool call becomes the text:
2085
+ usesJsonResponseTool ? {
2086
+ type: "text",
2087
+ text: JSON.stringify(part.input)
2088
+ } : {
2089
+ type: "tool-call",
2090
+ toolCallId: part.id,
2091
+ toolName: part.name,
2092
+ input: JSON.stringify(part.input)
2093
+ }
2094
+ );
2095
+ break;
2096
+ }
2097
+ case "server_tool_use": {
2098
+ if (part.name === "text_editor_code_execution" || part.name === "bash_code_execution") {
2099
+ content.push({
2100
+ type: "tool-call",
2101
+ toolCallId: part.id,
2102
+ toolName: "code_execution",
2103
+ input: JSON.stringify({ type: part.name, ...part.input }),
2104
+ providerExecuted: true
2105
+ });
2106
+ } else if (part.name === "web_search" || part.name === "code_execution" || part.name === "web_fetch") {
2107
+ content.push({
2108
+ type: "tool-call",
2109
+ toolCallId: part.id,
2110
+ toolName: part.name,
2111
+ input: JSON.stringify(part.input),
2112
+ providerExecuted: true
2113
+ });
2114
+ }
2115
+ break;
2116
+ }
2117
+ case "web_fetch_tool_result": {
2118
+ if (part.content.type === "web_fetch_result") {
2119
+ content.push({
2120
+ type: "tool-result",
2121
+ toolCallId: part.tool_use_id,
2122
+ toolName: "web_fetch",
2123
+ result: {
2124
+ type: "web_fetch_result",
2125
+ url: part.content.url,
2126
+ retrievedAt: part.content.retrieved_at,
2127
+ content: {
2128
+ type: part.content.content.type,
2129
+ title: part.content.content.title,
2130
+ citations: part.content.content.citations,
2131
+ source: {
2132
+ type: part.content.content.source.type,
2133
+ mediaType: part.content.content.source.media_type,
2134
+ data: part.content.content.source.data
2135
+ }
2136
+ }
2137
+ },
2138
+ providerExecuted: true
2139
+ });
2140
+ } else if (part.content.type === "web_fetch_tool_result_error") {
2141
+ content.push({
2142
+ type: "tool-result",
2143
+ toolCallId: part.tool_use_id,
2144
+ toolName: "web_fetch",
2145
+ isError: true,
2146
+ result: {
2147
+ type: "web_fetch_tool_result_error",
2148
+ errorCode: part.content.error_code
2149
+ },
2150
+ providerExecuted: true
2151
+ });
2152
+ }
2153
+ break;
2154
+ }
2155
+ case "web_search_tool_result": {
2156
+ if (Array.isArray(part.content)) {
2157
+ content.push({
2158
+ type: "tool-result",
2159
+ toolCallId: part.tool_use_id,
2160
+ toolName: "web_search",
2161
+ result: part.content.map((result) => {
2162
+ var _a2;
2163
+ return {
2164
+ url: result.url,
2165
+ title: result.title,
2166
+ pageAge: (_a2 = result.page_age) != null ? _a2 : null,
2167
+ encryptedContent: result.encrypted_content,
2168
+ type: result.type
2169
+ };
2170
+ }),
2171
+ providerExecuted: true
2172
+ });
2173
+ for (const result of part.content) {
2174
+ content.push({
2175
+ type: "source",
2176
+ sourceType: "url",
2177
+ id: this.generateId(),
2178
+ url: result.url,
2179
+ title: result.title,
2180
+ providerMetadata: {
2181
+ anthropic: {
2182
+ pageAge: (_a = result.page_age) != null ? _a : null
2183
+ }
2184
+ }
2185
+ });
2186
+ }
2187
+ } else {
2188
+ content.push({
2189
+ type: "tool-result",
2190
+ toolCallId: part.tool_use_id,
2191
+ toolName: "web_search",
2192
+ isError: true,
2193
+ result: {
2194
+ type: "web_search_tool_result_error",
2195
+ errorCode: part.content.error_code
2196
+ },
2197
+ providerExecuted: true
2198
+ });
2199
+ }
2200
+ break;
2201
+ }
2202
+ // code execution 20250522:
2203
+ case "code_execution_tool_result": {
2204
+ if (part.content.type === "code_execution_result") {
2205
+ content.push({
2206
+ type: "tool-result",
2207
+ toolCallId: part.tool_use_id,
2208
+ toolName: "code_execution",
2209
+ result: {
2210
+ type: part.content.type,
2211
+ stdout: part.content.stdout,
2212
+ stderr: part.content.stderr,
2213
+ return_code: part.content.return_code
2214
+ },
2215
+ providerExecuted: true
2216
+ });
2217
+ } else if (part.content.type === "code_execution_tool_result_error") {
2218
+ content.push({
2219
+ type: "tool-result",
2220
+ toolCallId: part.tool_use_id,
2221
+ toolName: "code_execution",
2222
+ isError: true,
2223
+ result: {
2224
+ type: "code_execution_tool_result_error",
2225
+ errorCode: part.content.error_code
2226
+ },
2227
+ providerExecuted: true
2228
+ });
2229
+ }
2230
+ break;
2231
+ }
2232
+ // code execution 20250825:
2233
+ case "bash_code_execution_tool_result":
2234
+ case "text_editor_code_execution_tool_result": {
2235
+ content.push({
2236
+ type: "tool-result",
2237
+ toolCallId: part.tool_use_id,
2238
+ toolName: "code_execution",
2239
+ result: part.content,
2240
+ providerExecuted: true
2241
+ });
2242
+ break;
2243
+ }
2244
+ }
2245
+ }
2246
+ return {
2247
+ content,
2248
+ finishReason: mapAnthropicStopReason({
2249
+ finishReason: response.stop_reason,
2250
+ isJsonResponseFromTool: usesJsonResponseTool
2251
+ }),
2252
+ usage: {
2253
+ inputTokens: response.usage.input_tokens,
2254
+ outputTokens: response.usage.output_tokens,
2255
+ totalTokens: response.usage.input_tokens + response.usage.output_tokens,
2256
+ cachedInputTokens: (_b = response.usage.cache_read_input_tokens) != null ? _b : void 0
2257
+ },
2258
+ request: { body: args },
2259
+ response: {
2260
+ id: (_c = response.id) != null ? _c : void 0,
2261
+ modelId: (_d = response.model) != null ? _d : void 0,
2262
+ headers: responseHeaders,
2263
+ body: rawResponse
2264
+ },
2265
+ warnings,
2266
+ providerMetadata: {
2267
+ anthropic: {
2268
+ usage: response.usage,
2269
+ cacheCreationInputTokens: (_e = response.usage.cache_creation_input_tokens) != null ? _e : null,
2270
+ stopSequence: (_f = response.stop_sequence) != null ? _f : null,
2271
+ container: response.container ? {
2272
+ expiresAt: response.container.expires_at,
2273
+ id: response.container.id,
2274
+ skills: (_h = (_g = response.container.skills) == null ? void 0 : _g.map((skill) => ({
2275
+ type: skill.type,
2276
+ skillId: skill.skill_id,
2277
+ version: skill.version
2278
+ }))) != null ? _h : null
2279
+ } : null
2280
+ }
2281
+ }
2282
+ };
2283
+ }
2284
+ async doStream(options) {
2285
+ var _a, _b;
2286
+ const { args, warnings, betas, usesJsonResponseTool } = await this.getArgs({
2287
+ ...options,
2288
+ userSuppliedBetas: await this.getBetasFromHeaders(options.headers)
2289
+ });
2290
+ const citationDocuments = this.extractCitationDocuments(options.prompt);
2291
+ const body = { ...args, stream: true };
2292
+ const url = this.buildRequestUrl(true);
2293
+ const { responseHeaders, value: response } = await postJsonToApi({
2294
+ url,
2295
+ headers: await this.getHeaders({ betas, headers: options.headers }),
2296
+ body: this.transformRequestBody(body),
2297
+ failedResponseHandler: anthropicFailedResponseHandler,
2298
+ successfulResponseHandler: createEventSourceResponseHandler(
2299
+ anthropicMessagesChunkSchema
2300
+ ),
2301
+ abortSignal: options.abortSignal,
2302
+ fetch: this.config.fetch
2303
+ });
2304
+ let finishReason = "unknown";
2305
+ const usage = {
2306
+ inputTokens: void 0,
2307
+ outputTokens: void 0,
2308
+ totalTokens: void 0
2309
+ };
2310
+ const contentBlocks = {};
2311
+ let rawUsage = void 0;
2312
+ let cacheCreationInputTokens = null;
2313
+ let stopSequence = null;
2314
+ let container = null;
2315
+ let blockType = void 0;
2316
+ const generateId3 = this.generateId;
2317
+ const transformedStream = response.pipeThrough(
2318
+ new TransformStream({
2319
+ start(controller) {
2320
+ controller.enqueue({ type: "stream-start", warnings });
2321
+ },
2322
+ transform(chunk, controller) {
2323
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j;
2324
+ if (options.includeRawChunks) {
2325
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
2326
+ }
2327
+ if (!chunk.success) {
2328
+ controller.enqueue({ type: "error", error: chunk.error });
2329
+ return;
2330
+ }
2331
+ const value = chunk.value;
2332
+ switch (value.type) {
2333
+ case "ping": {
2334
+ return;
2335
+ }
2336
+ case "content_block_start": {
2337
+ const contentBlockType = value.content_block.type;
2338
+ blockType = contentBlockType;
2339
+ switch (contentBlockType) {
2340
+ case "text": {
2341
+ contentBlocks[value.index] = { type: "text" };
2342
+ controller.enqueue({
2343
+ type: "text-start",
2344
+ id: String(value.index)
2345
+ });
2346
+ return;
2347
+ }
2348
+ case "thinking": {
2349
+ contentBlocks[value.index] = { type: "reasoning" };
2350
+ controller.enqueue({
2351
+ type: "reasoning-start",
2352
+ id: String(value.index)
2353
+ });
2354
+ return;
2355
+ }
2356
+ case "redacted_thinking": {
2357
+ contentBlocks[value.index] = { type: "reasoning" };
2358
+ controller.enqueue({
2359
+ type: "reasoning-start",
2360
+ id: String(value.index),
2361
+ providerMetadata: {
2362
+ anthropic: {
2363
+ redactedData: value.content_block.data
2364
+ }
2365
+ }
2366
+ });
2367
+ return;
2368
+ }
2369
+ case "tool_use": {
2370
+ contentBlocks[value.index] = usesJsonResponseTool ? { type: "text" } : {
2371
+ type: "tool-call",
2372
+ toolCallId: value.content_block.id,
2373
+ toolName: value.content_block.name,
2374
+ input: "",
2375
+ firstDelta: true
2376
+ };
2377
+ controller.enqueue(
2378
+ usesJsonResponseTool ? { type: "text-start", id: String(value.index) } : {
2379
+ type: "tool-input-start",
2380
+ id: value.content_block.id,
2381
+ toolName: value.content_block.name
2382
+ }
2383
+ );
2384
+ return;
2385
+ }
2386
+ case "server_tool_use": {
2387
+ if ([
2388
+ "web_fetch",
2389
+ "web_search",
2390
+ // code execution 20250825:
2391
+ "code_execution",
2392
+ // code execution 20250825 text editor:
2393
+ "text_editor_code_execution",
2394
+ // code execution 20250825 bash:
2395
+ "bash_code_execution"
2396
+ ].includes(value.content_block.name)) {
2397
+ contentBlocks[value.index] = {
2398
+ type: "tool-call",
2399
+ toolCallId: value.content_block.id,
2400
+ toolName: value.content_block.name,
2401
+ input: "",
2402
+ providerExecuted: true,
2403
+ firstDelta: true
2404
+ };
2405
+ const mappedToolName = value.content_block.name === "text_editor_code_execution" || value.content_block.name === "bash_code_execution" ? "code_execution" : value.content_block.name;
2406
+ controller.enqueue({
2407
+ type: "tool-input-start",
2408
+ id: value.content_block.id,
2409
+ toolName: mappedToolName,
2410
+ providerExecuted: true
2411
+ });
2412
+ }
2413
+ return;
2414
+ }
2415
+ case "web_fetch_tool_result": {
2416
+ const part = value.content_block;
2417
+ if (part.content.type === "web_fetch_result") {
2418
+ controller.enqueue({
2419
+ type: "tool-result",
2420
+ toolCallId: part.tool_use_id,
2421
+ toolName: "web_fetch",
2422
+ result: {
2423
+ type: "web_fetch_result",
2424
+ url: part.content.url,
2425
+ retrievedAt: part.content.retrieved_at,
2426
+ content: {
2427
+ type: part.content.content.type,
2428
+ title: part.content.content.title,
2429
+ citations: part.content.content.citations,
2430
+ source: {
2431
+ type: part.content.content.source.type,
2432
+ mediaType: part.content.content.source.media_type,
2433
+ data: part.content.content.source.data
2434
+ }
2435
+ }
2436
+ },
2437
+ providerExecuted: true
2438
+ });
2439
+ } else if (part.content.type === "web_fetch_tool_result_error") {
2440
+ controller.enqueue({
2441
+ type: "tool-result",
2442
+ toolCallId: part.tool_use_id,
2443
+ toolName: "web_fetch",
2444
+ isError: true,
2445
+ result: {
2446
+ type: "web_fetch_tool_result_error",
2447
+ errorCode: part.content.error_code
2448
+ },
2449
+ providerExecuted: true
2450
+ });
2451
+ }
2452
+ return;
2453
+ }
2454
+ case "web_search_tool_result": {
2455
+ const part = value.content_block;
2456
+ if (Array.isArray(part.content)) {
2457
+ controller.enqueue({
2458
+ type: "tool-result",
2459
+ toolCallId: part.tool_use_id,
2460
+ toolName: "web_search",
2461
+ result: part.content.map((result) => {
2462
+ var _a3;
2463
+ return {
2464
+ url: result.url,
2465
+ title: result.title,
2466
+ pageAge: (_a3 = result.page_age) != null ? _a3 : null,
2467
+ encryptedContent: result.encrypted_content,
2468
+ type: result.type
2469
+ };
2470
+ }),
2471
+ providerExecuted: true
2472
+ });
2473
+ for (const result of part.content) {
2474
+ controller.enqueue({
2475
+ type: "source",
2476
+ sourceType: "url",
2477
+ id: generateId3(),
2478
+ url: result.url,
2479
+ title: result.title,
2480
+ providerMetadata: {
2481
+ anthropic: {
2482
+ pageAge: (_a2 = result.page_age) != null ? _a2 : null
2483
+ }
2484
+ }
2485
+ });
2486
+ }
2487
+ } else {
2488
+ controller.enqueue({
2489
+ type: "tool-result",
2490
+ toolCallId: part.tool_use_id,
2491
+ toolName: "web_search",
2492
+ isError: true,
2493
+ result: {
2494
+ type: "web_search_tool_result_error",
2495
+ errorCode: part.content.error_code
2496
+ },
2497
+ providerExecuted: true
2498
+ });
2499
+ }
2500
+ return;
2501
+ }
2502
+ // code execution 20250522:
2503
+ case "code_execution_tool_result": {
2504
+ const part = value.content_block;
2505
+ if (part.content.type === "code_execution_result") {
2506
+ controller.enqueue({
2507
+ type: "tool-result",
2508
+ toolCallId: part.tool_use_id,
2509
+ toolName: "code_execution",
2510
+ result: {
2511
+ type: part.content.type,
2512
+ stdout: part.content.stdout,
2513
+ stderr: part.content.stderr,
2514
+ return_code: part.content.return_code
2515
+ },
2516
+ providerExecuted: true
2517
+ });
2518
+ } else if (part.content.type === "code_execution_tool_result_error") {
2519
+ controller.enqueue({
2520
+ type: "tool-result",
2521
+ toolCallId: part.tool_use_id,
2522
+ toolName: "code_execution",
2523
+ isError: true,
2524
+ result: {
2525
+ type: "code_execution_tool_result_error",
2526
+ errorCode: part.content.error_code
2527
+ },
2528
+ providerExecuted: true
2529
+ });
2530
+ }
2531
+ return;
2532
+ }
2533
+ // code execution 20250825:
2534
+ case "bash_code_execution_tool_result":
2535
+ case "text_editor_code_execution_tool_result": {
2536
+ const part = value.content_block;
2537
+ controller.enqueue({
2538
+ type: "tool-result",
2539
+ toolCallId: part.tool_use_id,
2540
+ toolName: "code_execution",
2541
+ result: part.content,
2542
+ providerExecuted: true
2543
+ });
2544
+ return;
2545
+ }
2546
+ default: {
2547
+ const _exhaustiveCheck = contentBlockType;
2548
+ throw new Error(
2549
+ `Unsupported content block type: ${_exhaustiveCheck}`
2550
+ );
2551
+ }
2552
+ }
2553
+ }
2554
+ case "content_block_stop": {
2555
+ if (contentBlocks[value.index] != null) {
2556
+ const contentBlock = contentBlocks[value.index];
2557
+ switch (contentBlock.type) {
2558
+ case "text": {
2559
+ controller.enqueue({
2560
+ type: "text-end",
2561
+ id: String(value.index)
2562
+ });
2563
+ break;
2564
+ }
2565
+ case "reasoning": {
2566
+ controller.enqueue({
2567
+ type: "reasoning-end",
2568
+ id: String(value.index)
2569
+ });
2570
+ break;
2571
+ }
2572
+ case "tool-call":
2573
+ if (!usesJsonResponseTool) {
2574
+ controller.enqueue({
2575
+ type: "tool-input-end",
2576
+ id: contentBlock.toolCallId
2577
+ });
2578
+ const toolName = contentBlock.toolName === "text_editor_code_execution" || contentBlock.toolName === "bash_code_execution" ? "code_execution" : contentBlock.toolName;
2579
+ controller.enqueue({
2580
+ type: "tool-call",
2581
+ toolCallId: contentBlock.toolCallId,
2582
+ toolName,
2583
+ input: contentBlock.input === "" ? "{}" : contentBlock.input,
2584
+ providerExecuted: contentBlock.providerExecuted
2585
+ });
2586
+ }
2587
+ break;
2588
+ }
2589
+ delete contentBlocks[value.index];
2590
+ }
2591
+ blockType = void 0;
2592
+ return;
2593
+ }
2594
+ case "content_block_delta": {
2595
+ const deltaType = value.delta.type;
2596
+ switch (deltaType) {
2597
+ case "text_delta": {
2598
+ if (usesJsonResponseTool) {
2599
+ return;
2600
+ }
2601
+ controller.enqueue({
2602
+ type: "text-delta",
2603
+ id: String(value.index),
2604
+ delta: value.delta.text
2605
+ });
2606
+ return;
2607
+ }
2608
+ case "thinking_delta": {
2609
+ controller.enqueue({
2610
+ type: "reasoning-delta",
2611
+ id: String(value.index),
2612
+ delta: value.delta.thinking
2613
+ });
2614
+ return;
2615
+ }
2616
+ case "signature_delta": {
2617
+ if (blockType === "thinking") {
2618
+ controller.enqueue({
2619
+ type: "reasoning-delta",
2620
+ id: String(value.index),
2621
+ delta: "",
2622
+ providerMetadata: {
2623
+ anthropic: {
2624
+ signature: value.delta.signature
2625
+ }
2626
+ }
2627
+ });
2628
+ }
2629
+ return;
2630
+ }
2631
+ case "input_json_delta": {
2632
+ const contentBlock = contentBlocks[value.index];
2633
+ let delta = value.delta.partial_json;
2634
+ if (delta.length === 0) {
2635
+ return;
2636
+ }
2637
+ if (usesJsonResponseTool) {
2638
+ if ((contentBlock == null ? void 0 : contentBlock.type) !== "text") {
2639
+ return;
2640
+ }
2641
+ controller.enqueue({
2642
+ type: "text-delta",
2643
+ id: String(value.index),
2644
+ delta
2645
+ });
2646
+ } else {
2647
+ if ((contentBlock == null ? void 0 : contentBlock.type) !== "tool-call") {
2648
+ return;
2649
+ }
2650
+ if (contentBlock.firstDelta && (contentBlock.toolName === "bash_code_execution" || contentBlock.toolName === "text_editor_code_execution")) {
2651
+ delta = `{"type": "${contentBlock.toolName}",${delta.substring(1)}`;
2652
+ }
2653
+ controller.enqueue({
2654
+ type: "tool-input-delta",
2655
+ id: contentBlock.toolCallId,
2656
+ delta
2657
+ });
2658
+ contentBlock.input += delta;
2659
+ contentBlock.firstDelta = false;
2660
+ }
2661
+ return;
2662
+ }
2663
+ case "citations_delta": {
2664
+ const citation = value.delta.citation;
2665
+ const source = createCitationSource(
2666
+ citation,
2667
+ citationDocuments,
2668
+ generateId3
2669
+ );
2670
+ if (source) {
2671
+ controller.enqueue(source);
2672
+ }
2673
+ return;
2674
+ }
2675
+ default: {
2676
+ const _exhaustiveCheck = deltaType;
2677
+ throw new Error(
2678
+ `Unsupported delta type: ${_exhaustiveCheck}`
2679
+ );
2680
+ }
2681
+ }
2682
+ }
2683
+ case "message_start": {
2684
+ usage.inputTokens = value.message.usage.input_tokens;
2685
+ usage.cachedInputTokens = (_b2 = value.message.usage.cache_read_input_tokens) != null ? _b2 : void 0;
2686
+ rawUsage = {
2687
+ ...value.message.usage
2688
+ };
2689
+ cacheCreationInputTokens = (_c = value.message.usage.cache_creation_input_tokens) != null ? _c : null;
2690
+ controller.enqueue({
2691
+ type: "response-metadata",
2692
+ id: (_d = value.message.id) != null ? _d : void 0,
2693
+ modelId: (_e = value.message.model) != null ? _e : void 0
2694
+ });
2695
+ return;
2696
+ }
2697
+ case "message_delta": {
2698
+ usage.outputTokens = value.usage.output_tokens;
2699
+ usage.totalTokens = ((_f = usage.inputTokens) != null ? _f : 0) + ((_g = value.usage.output_tokens) != null ? _g : 0);
2700
+ finishReason = mapAnthropicStopReason({
2701
+ finishReason: value.delta.stop_reason,
2702
+ isJsonResponseFromTool: usesJsonResponseTool
2703
+ });
2704
+ stopSequence = (_h = value.delta.stop_sequence) != null ? _h : null;
2705
+ container = value.delta.container != null ? {
2706
+ expiresAt: value.delta.container.expires_at,
2707
+ id: value.delta.container.id,
2708
+ skills: (_j = (_i = value.delta.container.skills) == null ? void 0 : _i.map((skill) => ({
2709
+ type: skill.type,
2710
+ skillId: skill.skill_id,
2711
+ version: skill.version
2712
+ }))) != null ? _j : null
2713
+ } : null;
2714
+ rawUsage = {
2715
+ ...rawUsage,
2716
+ ...value.usage
2717
+ };
2718
+ return;
2719
+ }
2720
+ case "message_stop": {
2721
+ controller.enqueue({
2722
+ type: "finish",
2723
+ finishReason,
2724
+ usage,
2725
+ providerMetadata: {
2726
+ anthropic: {
2727
+ usage: rawUsage != null ? rawUsage : null,
2728
+ cacheCreationInputTokens,
2729
+ stopSequence,
2730
+ container
2731
+ }
2732
+ }
2733
+ });
2734
+ return;
2735
+ }
2736
+ case "error": {
2737
+ controller.enqueue({ type: "error", error: value.error });
2738
+ return;
2739
+ }
2740
+ default: {
2741
+ const _exhaustiveCheck = value;
2742
+ throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);
2743
+ }
2744
+ }
2745
+ }
2746
+ })
2747
+ );
2748
+ const [streamForFirstChunk, streamForConsumer] = transformedStream.tee();
2749
+ const firstChunkReader = streamForFirstChunk.getReader();
2750
+ try {
2751
+ await firstChunkReader.read();
2752
+ let result = await firstChunkReader.read();
2753
+ if (((_a = result.value) == null ? void 0 : _a.type) === "raw") {
2754
+ result = await firstChunkReader.read();
2755
+ }
2756
+ if (((_b = result.value) == null ? void 0 : _b.type) === "error") {
2757
+ const error = result.value.error;
2758
+ throw new APICallError({
2759
+ message: error.message,
2760
+ url,
2761
+ requestBodyValues: body,
2762
+ statusCode: error.type === "overloaded_error" ? 529 : 500,
2763
+ responseHeaders,
2764
+ responseBody: JSON.stringify(error),
2765
+ isRetryable: error.type === "overloaded_error"
2766
+ });
2767
+ }
2768
+ } finally {
2769
+ firstChunkReader.cancel().catch(() => {
2770
+ });
2771
+ firstChunkReader.releaseLock();
2772
+ }
2773
+ return {
2774
+ stream: streamForConsumer,
2775
+ request: { body },
2776
+ response: { headers: responseHeaders }
2777
+ };
2778
+ }
2779
+ };
2780
+ function getModelCapabilities(modelId) {
2781
+ if (modelId.includes("claude-sonnet-4-5") || modelId.includes("claude-opus-4-5")) {
2782
+ return {
2783
+ maxOutputTokens: 64e3,
2784
+ supportsStructuredOutput: true,
2785
+ isKnownModel: true
2786
+ };
2787
+ } else if (modelId.includes("claude-opus-4-1")) {
2788
+ return {
2789
+ maxOutputTokens: 32e3,
2790
+ supportsStructuredOutput: true,
2791
+ isKnownModel: true
2792
+ };
2793
+ } else if (modelId.includes("claude-sonnet-4-") || modelId.includes("claude-3-7-sonnet") || modelId.includes("claude-haiku-4-5")) {
2794
+ return {
2795
+ maxOutputTokens: 64e3,
2796
+ supportsStructuredOutput: false,
2797
+ isKnownModel: true
2798
+ };
2799
+ } else if (modelId.includes("claude-opus-4-")) {
2800
+ return {
2801
+ maxOutputTokens: 32e3,
2802
+ supportsStructuredOutput: false,
2803
+ isKnownModel: true
2804
+ };
2805
+ } else if (modelId.includes("claude-3-5-haiku")) {
2806
+ return {
2807
+ maxOutputTokens: 8192,
2808
+ supportsStructuredOutput: false,
2809
+ isKnownModel: true
2810
+ };
2811
+ } else if (modelId.includes("claude-3-haiku")) {
2812
+ return {
2813
+ maxOutputTokens: 4096,
2814
+ supportsStructuredOutput: false,
2815
+ isKnownModel: true
2816
+ };
2817
+ } else {
2818
+ return {
2819
+ maxOutputTokens: 4096,
2820
+ supportsStructuredOutput: false,
2821
+ isKnownModel: false
2822
+ };
2823
+ }
2824
+ }
2825
+ var bash_20241022InputSchema = lazySchema(
2826
+ () => zodSchema(
2827
+ z9.object({
2828
+ command: z9.string(),
2829
+ restart: z9.boolean().optional()
2830
+ })
2831
+ )
2832
+ );
2833
+ var bash_20241022 = createProviderDefinedToolFactory({
2834
+ id: "anthropic.bash_20241022",
2835
+ name: "bash",
2836
+ inputSchema: bash_20241022InputSchema
2837
+ });
2838
+ var bash_20250124InputSchema = lazySchema(
2839
+ () => zodSchema(
2840
+ z10.object({
2841
+ command: z10.string(),
2842
+ restart: z10.boolean().optional()
2843
+ })
2844
+ )
2845
+ );
2846
+ var bash_20250124 = createProviderDefinedToolFactory({
2847
+ id: "anthropic.bash_20250124",
2848
+ name: "bash",
2849
+ inputSchema: bash_20250124InputSchema
2850
+ });
2851
+ var computer_20241022InputSchema = lazySchema(
2852
+ () => zodSchema(
2853
+ z11.object({
2854
+ action: z11.enum([
2855
+ "key",
2856
+ "type",
2857
+ "mouse_move",
2858
+ "left_click",
2859
+ "left_click_drag",
2860
+ "right_click",
2861
+ "middle_click",
2862
+ "double_click",
2863
+ "screenshot",
2864
+ "cursor_position"
2865
+ ]),
2866
+ coordinate: z11.array(z11.number().int()).optional(),
2867
+ text: z11.string().optional()
2868
+ })
2869
+ )
2870
+ );
2871
+ var computer_20241022 = createProviderDefinedToolFactory({
2872
+ id: "anthropic.computer_20241022",
2873
+ name: "computer",
2874
+ inputSchema: computer_20241022InputSchema
2875
+ });
2876
+ var computer_20250124InputSchema = lazySchema(
2877
+ () => zodSchema(
2878
+ z12.object({
2879
+ action: z12.enum([
2880
+ "key",
2881
+ "hold_key",
2882
+ "type",
2883
+ "cursor_position",
2884
+ "mouse_move",
2885
+ "left_mouse_down",
2886
+ "left_mouse_up",
2887
+ "left_click",
2888
+ "left_click_drag",
2889
+ "right_click",
2890
+ "middle_click",
2891
+ "double_click",
2892
+ "triple_click",
2893
+ "scroll",
2894
+ "wait",
2895
+ "screenshot"
2896
+ ]),
2897
+ coordinate: z12.tuple([z12.number().int(), z12.number().int()]).optional(),
2898
+ duration: z12.number().optional(),
2899
+ scroll_amount: z12.number().optional(),
2900
+ scroll_direction: z12.enum(["up", "down", "left", "right"]).optional(),
2901
+ start_coordinate: z12.tuple([z12.number().int(), z12.number().int()]).optional(),
2902
+ text: z12.string().optional()
2903
+ })
2904
+ )
2905
+ );
2906
+ var computer_20250124 = createProviderDefinedToolFactory({
2907
+ id: "anthropic.computer_20250124",
2908
+ name: "computer",
2909
+ inputSchema: computer_20250124InputSchema
2910
+ });
2911
+ var memory_20250818InputSchema = lazySchema(
2912
+ () => zodSchema(
2913
+ z13.discriminatedUnion("command", [
2914
+ z13.object({
2915
+ command: z13.literal("view"),
2916
+ path: z13.string(),
2917
+ view_range: z13.tuple([z13.number(), z13.number()]).optional()
2918
+ }),
2919
+ z13.object({
2920
+ command: z13.literal("create"),
2921
+ path: z13.string(),
2922
+ file_text: z13.string()
2923
+ }),
2924
+ z13.object({
2925
+ command: z13.literal("str_replace"),
2926
+ path: z13.string(),
2927
+ old_str: z13.string(),
2928
+ new_str: z13.string()
2929
+ }),
2930
+ z13.object({
2931
+ command: z13.literal("insert"),
2932
+ path: z13.string(),
2933
+ insert_line: z13.number(),
2934
+ insert_text: z13.string()
2935
+ }),
2936
+ z13.object({
2937
+ command: z13.literal("delete"),
2938
+ path: z13.string()
2939
+ }),
2940
+ z13.object({
2941
+ command: z13.literal("rename"),
2942
+ old_path: z13.string(),
2943
+ new_path: z13.string()
2944
+ })
2945
+ ])
2946
+ )
2947
+ );
2948
+ var memory_20250818 = createProviderDefinedToolFactory({
2949
+ id: "anthropic.memory_20250818",
2950
+ name: "memory",
2951
+ inputSchema: memory_20250818InputSchema
2952
+ });
2953
+ var textEditor_20241022InputSchema = lazySchema(
2954
+ () => zodSchema(
2955
+ z14.object({
2956
+ command: z14.enum(["view", "create", "str_replace", "insert", "undo_edit"]),
2957
+ path: z14.string(),
2958
+ file_text: z14.string().optional(),
2959
+ insert_line: z14.number().int().optional(),
2960
+ new_str: z14.string().optional(),
2961
+ old_str: z14.string().optional(),
2962
+ view_range: z14.array(z14.number().int()).optional()
2963
+ })
2964
+ )
2965
+ );
2966
+ var textEditor_20241022 = createProviderDefinedToolFactory({
2967
+ id: "anthropic.text_editor_20241022",
2968
+ name: "str_replace_editor",
2969
+ inputSchema: textEditor_20241022InputSchema
2970
+ });
2971
+ var textEditor_20250124InputSchema = lazySchema(
2972
+ () => zodSchema(
2973
+ z15.object({
2974
+ command: z15.enum(["view", "create", "str_replace", "insert", "undo_edit"]),
2975
+ path: z15.string(),
2976
+ file_text: z15.string().optional(),
2977
+ insert_line: z15.number().int().optional(),
2978
+ new_str: z15.string().optional(),
2979
+ old_str: z15.string().optional(),
2980
+ view_range: z15.array(z15.number().int()).optional()
2981
+ })
2982
+ )
2983
+ );
2984
+ var textEditor_20250124 = createProviderDefinedToolFactory({
2985
+ id: "anthropic.text_editor_20250124",
2986
+ name: "str_replace_editor",
2987
+ inputSchema: textEditor_20250124InputSchema
2988
+ });
2989
+ var textEditor_20250429InputSchema = lazySchema(
2990
+ () => zodSchema(
2991
+ z16.object({
2992
+ command: z16.enum(["view", "create", "str_replace", "insert"]),
2993
+ path: z16.string(),
2994
+ file_text: z16.string().optional(),
2995
+ insert_line: z16.number().int().optional(),
2996
+ new_str: z16.string().optional(),
2997
+ old_str: z16.string().optional(),
2998
+ view_range: z16.array(z16.number().int()).optional()
2999
+ })
3000
+ )
3001
+ );
3002
+ var textEditor_20250429 = createProviderDefinedToolFactory({
3003
+ id: "anthropic.text_editor_20250429",
3004
+ name: "str_replace_based_edit_tool",
3005
+ inputSchema: textEditor_20250429InputSchema
3006
+ });
3007
+ var anthropicTools = {
3008
+ /**
3009
+ * The bash tool enables Claude to execute shell commands in a persistent bash session,
3010
+ * allowing system operations, script execution, and command-line automation.
3011
+ *
3012
+ * Image results are supported.
3013
+ *
3014
+ * Tool name must be `bash`.
3015
+ */
3016
+ bash_20241022,
3017
+ /**
3018
+ * The bash tool enables Claude to execute shell commands in a persistent bash session,
3019
+ * allowing system operations, script execution, and command-line automation.
3020
+ *
3021
+ * Image results are supported.
3022
+ *
3023
+ * Tool name must be `bash`.
3024
+ */
3025
+ bash_20250124,
3026
+ /**
3027
+ * Claude can analyze data, create visualizations, perform complex calculations,
3028
+ * run system commands, create and edit files, and process uploaded files directly within
3029
+ * the API conversation.
3030
+ *
3031
+ * The code execution tool allows Claude to run Bash commands and manipulate files,
3032
+ * including writing code, in a secure, sandboxed environment.
3033
+ *
3034
+ * Tool name must be `code_execution`.
3035
+ */
3036
+ codeExecution_20250522,
3037
+ /**
3038
+ * Claude can analyze data, create visualizations, perform complex calculations,
3039
+ * run system commands, create and edit files, and process uploaded files directly within
3040
+ * the API conversation.
3041
+ *
3042
+ * The code execution tool allows Claude to run both Python and Bash commands and manipulate files,
3043
+ * including writing code, in a secure, sandboxed environment.
3044
+ *
3045
+ * This is the latest version with enhanced Bash support and file operations.
3046
+ *
3047
+ * Tool name must be `code_execution`.
3048
+ */
3049
+ codeExecution_20250825,
3050
+ /**
3051
+ * Claude can interact with computer environments through the computer use tool, which
3052
+ * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
3053
+ *
3054
+ * Image results are supported.
3055
+ *
3056
+ * Tool name must be `computer`.
3057
+ *
3058
+ * @param displayWidthPx - The width of the display being controlled by the model in pixels.
3059
+ * @param displayHeightPx - The height of the display being controlled by the model in pixels.
3060
+ * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
3061
+ */
3062
+ computer_20241022,
3063
+ /**
3064
+ * Claude can interact with computer environments through the computer use tool, which
3065
+ * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
3066
+ *
3067
+ * Image results are supported.
3068
+ *
3069
+ * Tool name must be `computer`.
3070
+ *
3071
+ * @param displayWidthPx - The width of the display being controlled by the model in pixels.
3072
+ * @param displayHeightPx - The height of the display being controlled by the model in pixels.
3073
+ * @param displayNumber - The display number to control (only relevant for X11 environments). If specified, the tool will be provided a display number in the tool definition.
3074
+ */
3075
+ computer_20250124,
3076
+ /**
3077
+ * The memory tool enables Claude to store and retrieve information across conversations through a memory file directory.
3078
+ * Claude can create, read, update, and delete files that persist between sessions,
3079
+ * allowing it to build knowledge over time without keeping everything in the context window.
3080
+ * The memory tool operates client-side—you control where and how the data is stored through your own infrastructure.
3081
+ *
3082
+ * Supported models: Claude Sonnet 4.5, Claude Sonnet 4, Claude Opus 4.1, Claude Opus 4.
3083
+ *
3084
+ * Tool name must be `memory`.
3085
+ */
3086
+ memory_20250818,
3087
+ /**
3088
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files,
3089
+ * helping you debug, fix, and improve your code or other text documents. This allows Claude
3090
+ * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
3091
+ *
3092
+ * Supported models: Claude Sonnet 3.5
3093
+ *
3094
+ * Tool name must be `str_replace_editor`.
3095
+ */
3096
+ textEditor_20241022,
3097
+ /**
3098
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files,
3099
+ * helping you debug, fix, and improve your code or other text documents. This allows Claude
3100
+ * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
3101
+ *
3102
+ * Supported models: Claude Sonnet 3.7
3103
+ *
3104
+ * Tool name must be `str_replace_editor`.
3105
+ */
3106
+ textEditor_20250124,
3107
+ /**
3108
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files,
3109
+ * helping you debug, fix, and improve your code or other text documents. This allows Claude
3110
+ * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
3111
+ *
3112
+ * Note: This version does not support the "undo_edit" command.
3113
+ *
3114
+ * Tool name must be `str_replace_based_edit_tool`.
3115
+ *
3116
+ * @deprecated Use textEditor_20250728 instead
3117
+ */
3118
+ textEditor_20250429,
3119
+ /**
3120
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files,
3121
+ * helping you debug, fix, and improve your code or other text documents. This allows Claude
3122
+ * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
3123
+ *
3124
+ * Note: This version does not support the "undo_edit" command and adds optional max_characters parameter.
3125
+ *
3126
+ * Supported models: Claude Sonnet 4, Opus 4, and Opus 4.1
3127
+ *
3128
+ * Tool name must be `str_replace_based_edit_tool`.
3129
+ *
3130
+ * @param maxCharacters - Optional maximum number of characters to view in the file
3131
+ */
3132
+ textEditor_20250728,
3133
+ /**
3134
+ * Creates a web fetch tool that gives Claude direct access to real-time web content.
3135
+ *
3136
+ * Tool name must be `web_fetch`.
3137
+ *
3138
+ * @param maxUses - The max_uses parameter limits the number of web fetches performed
3139
+ * @param allowedDomains - Only fetch from these domains
3140
+ * @param blockedDomains - Never fetch from these domains
3141
+ * @param citations - Unlike web search where citations are always enabled, citations are optional for web fetch. Set "citations": {"enabled": true} to enable Claude to cite specific passages from fetched documents.
3142
+ * @param maxContentTokens - The max_content_tokens parameter limits the amount of content that will be included in the context.
3143
+ */
3144
+ webFetch_20250910,
3145
+ /**
3146
+ * Creates a web search tool that gives Claude direct access to real-time web content.
3147
+ *
3148
+ * Tool name must be `web_search`.
3149
+ *
3150
+ * @param maxUses - Maximum number of web searches Claude can perform during the conversation.
3151
+ * @param allowedDomains - Optional list of domains that Claude is allowed to search.
3152
+ * @param blockedDomains - Optional list of domains that Claude should avoid when searching.
3153
+ * @param userLocation - Optional user location information to provide geographically relevant search results.
3154
+ */
3155
+ webSearch_20250305
3156
+ };
3157
+ function createAnthropic(options = {}) {
3158
+ var _a, _b;
3159
+ const baseURL = (_a = withoutTrailingSlash(
3160
+ loadOptionalSetting({
3161
+ settingValue: options.baseURL,
3162
+ environmentVariableName: "ANTHROPIC_BASE_URL"
3163
+ })
3164
+ )) != null ? _a : "https://api.anthropic.com/v1";
3165
+ const providerName = (_b = options.name) != null ? _b : "anthropic.messages";
3166
+ const getHeaders = () => withUserAgentSuffix(
3167
+ {
3168
+ "anthropic-version": "2023-06-01",
3169
+ "x-api-key": loadApiKey({
3170
+ apiKey: options.apiKey,
3171
+ environmentVariableName: "ANTHROPIC_API_KEY",
3172
+ description: "Anthropic"
3173
+ }),
3174
+ ...options.headers
3175
+ },
3176
+ `ai-sdk/anthropic/${VERSION}`
3177
+ );
3178
+ const createChatModel = (modelId) => {
3179
+ var _a2;
3180
+ return new AnthropicMessagesLanguageModel(modelId, {
3181
+ provider: providerName,
3182
+ baseURL,
3183
+ headers: getHeaders,
3184
+ fetch: options.fetch,
3185
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
3186
+ supportedUrls: () => ({
3187
+ "image/*": [/^https?:\/\/.*$/]
3188
+ })
3189
+ });
3190
+ };
3191
+ const provider = function(modelId) {
3192
+ if (new.target) {
3193
+ throw new Error(
3194
+ "The Anthropic model function cannot be called with the new keyword."
3195
+ );
3196
+ }
3197
+ return createChatModel(modelId);
3198
+ };
3199
+ provider.languageModel = createChatModel;
3200
+ provider.chat = createChatModel;
3201
+ provider.messages = createChatModel;
3202
+ provider.textEmbeddingModel = (modelId) => {
3203
+ throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
3204
+ };
3205
+ provider.imageModel = (modelId) => {
3206
+ throw new NoSuchModelError({ modelId, modelType: "imageModel" });
3207
+ };
3208
+ provider.tools = anthropicTools;
3209
+ return provider;
3210
+ }
3211
+ var anthropic = createAnthropic();
3212
+ export {
3213
+ VERSION,
3214
+ anthropic,
3215
+ createAnthropic
3216
+ };