@grindxp/cli 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/web/client/assets/Copy.es-Bs4NgJu-.js +1 -0
  2. package/dist/web/client/assets/Sword.es-2Xm7T3t2.js +1 -0
  3. package/dist/web/client/assets/geist-cyrillic-wght-normal-CHSlOQsW.woff2 +0 -0
  4. package/dist/web/client/assets/geist-latin-ext-wght-normal-DMtmJ5ZE.woff2 +0 -0
  5. package/dist/web/client/assets/geist-latin-wght-normal-Dm3htQBi.woff2 +0 -0
  6. package/dist/web/client/assets/index-6XDcqRbL.js +42 -0
  7. package/dist/web/client/assets/index-BXM1N6tm.js +1 -0
  8. package/dist/web/client/assets/index-B_KMiE38.js +1 -0
  9. package/dist/web/client/assets/index-CGj2rOLm.js +1 -0
  10. package/dist/web/client/assets/index-CS5BuFbt.js +1 -0
  11. package/dist/web/client/assets/index-CYsASiu-.js +1 -0
  12. package/dist/web/client/assets/index-DAvwM0SX.js +1 -0
  13. package/dist/web/client/assets/index-DCBFp5DJ.js +1 -0
  14. package/dist/web/client/assets/index-DjKt1qNz.js +1 -0
  15. package/dist/web/client/assets/index-PIcFs1vr.js +1 -0
  16. package/dist/web/client/assets/instrument-serif-latin-400-italic-DKMiL14s.woff2 +0 -0
  17. package/dist/web/client/assets/instrument-serif-latin-400-italic-u__WvvIK.woff +0 -0
  18. package/dist/web/client/assets/instrument-serif-latin-400-normal-BVbkICAY.woff +0 -0
  19. package/dist/web/client/assets/instrument-serif-latin-400-normal-DnYpCC2O.woff2 +0 -0
  20. package/dist/web/client/assets/instrument-serif-latin-ext-400-italic-C9HzH3YL.woff2 +0 -0
  21. package/dist/web/client/assets/instrument-serif-latin-ext-400-italic-D7-lnxEk.woff +0 -0
  22. package/dist/web/client/assets/instrument-serif-latin-ext-400-normal-C2je3j2s.woff2 +0 -0
  23. package/dist/web/client/assets/instrument-serif-latin-ext-400-normal-CFCUzsTy.woff +0 -0
  24. package/dist/web/client/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  25. package/dist/web/client/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  26. package/dist/web/client/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  27. package/dist/web/client/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  28. package/dist/web/client/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  29. package/dist/web/client/assets/main-BI1EOhmt.js +18 -0
  30. package/dist/web/client/assets/styles-7TpWqjrh.css +1 -0
  31. package/dist/web/client/favicon.ico +0 -0
  32. package/dist/web/server/assets/_tanstack-start-manifest_v-B_rvI8DG.js +4 -0
  33. package/dist/web/server/assets/agent.functions-zpMkBrG3.js +19144 -0
  34. package/dist/web/server/assets/data.functions-9hSsMFx_.js +285 -0
  35. package/dist/web/server/assets/index-4SxmUYH6.js +14 -0
  36. package/dist/web/server/assets/index-BDL7hA7T.js +5924 -0
  37. package/dist/web/server/assets/index-BL8u2X7w.js +14 -0
  38. package/dist/web/server/assets/index-BRRsXrOi.js +14 -0
  39. package/dist/web/server/assets/index-BiD7uOOh.js +14 -0
  40. package/dist/web/server/assets/index-C09LXa7Z.js +4587 -0
  41. package/dist/web/server/assets/index-CJ_-TSqN.js +1426 -0
  42. package/dist/web/server/assets/index-D2fMUSdJ.js +477 -0
  43. package/dist/web/server/assets/index-D2yaimYL.js +14 -0
  44. package/dist/web/server/assets/index-D31yYLCV.js +2275 -0
  45. package/dist/web/server/assets/index-D3RUqTdb.js +14 -0
  46. package/dist/web/server/assets/index-D7z4dRpK.js +66 -0
  47. package/dist/web/server/assets/index-b30aLTKp.js +66 -0
  48. package/dist/web/server/assets/router-1koL9I3U.js +589 -0
  49. package/dist/web/server/assets/sessions-DOkG47Ex.js +403 -0
  50. package/dist/web/server/assets/start-HYkvq4Ni.js +4 -0
  51. package/dist/web/server/assets/token-W0NPKas8.js +86 -0
  52. package/dist/web/server/assets/token-util-1cB5CD6M.js +30 -0
  53. package/dist/web/server/assets/token-util-DA5xS0pj.js +451 -0
  54. package/dist/web/server/assets/vault.server-Ndu49yTf.js +19356 -0
  55. package/dist/web/server/server.js +4889 -0
  56. package/package.json +53 -51
@@ -0,0 +1,4587 @@
1
+ import { w as withoutTrailingSlash, l as loadOptionalSetting, I as InvalidArgumentError, g as generateId, p as parseProviderOptions, c as createToolNameMapping, a as combineHeaders, r as resolve, b as postJsonToApi, A as APICallError, d as loadApiKey, e as withUserAgentSuffix, f as createJsonResponseHandler, h as createEventSourceResponseHandler, v as validateTypes, i as isNonNullable, j as convertToBase64, U as UnsupportedFunctionalityError, o as object, k as array, m as discriminatedUnion, s as string, n as boolean, q as number, t as literal, u as union, _ as _enum, x as createJsonErrorResponseHandler, y as lazySchema, z as zodSchema, N as NoSuchModelError, B as looseObject, C as unknown, D as record, E as createProviderToolFactory, F as createProviderToolFactoryWithOutputSchema, G as tuple } from "./agent.functions-zpMkBrG3.js";
2
+ import "./sessions-DOkG47Ex.js";
3
+ import "../server.js";
4
+ import "node:async_hooks";
5
+ import "node:stream";
6
+ import "react/jsx-runtime";
7
+ import "@tanstack/react-router/ssr/server";
8
+ import "@tanstack/react-router";
9
+ import "./vault.server-Ndu49yTf.js";
10
+ import "node:fs";
11
+ import "node:os";
12
+ import "node:path";
13
+ import "path";
14
+ import "fs";
15
+ import "child_process";
16
+ import "node:buffer";
17
+ import "events";
18
+ import "https";
19
+ import "http";
20
+ import "net";
21
+ import "tls";
22
+ import "crypto";
23
+ import "stream";
24
+ import "url";
25
+ import "zlib";
26
+ import "buffer";
27
+ import "node:crypto";
28
+ import "fs/promises";
29
+ import "os";
30
+ import "node:child_process";
31
+ var VERSION = "3.0.46";
32
+ var anthropicErrorDataSchema = lazySchema(
33
+ () => zodSchema(
34
+ object({
35
+ type: literal("error"),
36
+ error: object({
37
+ type: string(),
38
+ message: string()
39
+ })
40
+ })
41
+ )
42
+ );
43
+ var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
44
+ errorSchema: anthropicErrorDataSchema,
45
+ errorToMessage: (data) => data.error.message
46
+ });
47
+ var anthropicMessagesResponseSchema = lazySchema(
48
+ () => zodSchema(
49
+ object({
50
+ type: literal("message"),
51
+ id: string().nullish(),
52
+ model: string().nullish(),
53
+ content: array(
54
+ discriminatedUnion("type", [
55
+ object({
56
+ type: literal("text"),
57
+ text: string(),
58
+ citations: array(
59
+ discriminatedUnion("type", [
60
+ object({
61
+ type: literal("web_search_result_location"),
62
+ cited_text: string(),
63
+ url: string(),
64
+ title: string(),
65
+ encrypted_index: string()
66
+ }),
67
+ object({
68
+ type: literal("page_location"),
69
+ cited_text: string(),
70
+ document_index: number(),
71
+ document_title: string().nullable(),
72
+ start_page_number: number(),
73
+ end_page_number: number()
74
+ }),
75
+ object({
76
+ type: literal("char_location"),
77
+ cited_text: string(),
78
+ document_index: number(),
79
+ document_title: string().nullable(),
80
+ start_char_index: number(),
81
+ end_char_index: number()
82
+ })
83
+ ])
84
+ ).optional()
85
+ }),
86
+ object({
87
+ type: literal("thinking"),
88
+ thinking: string(),
89
+ signature: string()
90
+ }),
91
+ object({
92
+ type: literal("redacted_thinking"),
93
+ data: string()
94
+ }),
95
+ object({
96
+ type: literal("compaction"),
97
+ content: string()
98
+ }),
99
+ object({
100
+ type: literal("tool_use"),
101
+ id: string(),
102
+ name: string(),
103
+ input: unknown(),
104
+ // Programmatic tool calling: caller info when triggered from code execution
105
+ caller: union([
106
+ object({
107
+ type: literal("code_execution_20250825"),
108
+ tool_id: string()
109
+ }),
110
+ object({
111
+ type: literal("direct")
112
+ })
113
+ ]).optional()
114
+ }),
115
+ object({
116
+ type: literal("server_tool_use"),
117
+ id: string(),
118
+ name: string(),
119
+ input: record(string(), unknown()).nullish()
120
+ }),
121
+ object({
122
+ type: literal("mcp_tool_use"),
123
+ id: string(),
124
+ name: string(),
125
+ input: unknown(),
126
+ server_name: string()
127
+ }),
128
+ object({
129
+ type: literal("mcp_tool_result"),
130
+ tool_use_id: string(),
131
+ is_error: boolean(),
132
+ content: array(
133
+ union([
134
+ string(),
135
+ object({ type: literal("text"), text: string() })
136
+ ])
137
+ )
138
+ }),
139
+ object({
140
+ type: literal("web_fetch_tool_result"),
141
+ tool_use_id: string(),
142
+ content: union([
143
+ object({
144
+ type: literal("web_fetch_result"),
145
+ url: string(),
146
+ retrieved_at: string(),
147
+ content: object({
148
+ type: literal("document"),
149
+ title: string().nullable(),
150
+ citations: object({ enabled: boolean() }).optional(),
151
+ source: union([
152
+ object({
153
+ type: literal("base64"),
154
+ media_type: literal("application/pdf"),
155
+ data: string()
156
+ }),
157
+ object({
158
+ type: literal("text"),
159
+ media_type: literal("text/plain"),
160
+ data: string()
161
+ })
162
+ ])
163
+ })
164
+ }),
165
+ object({
166
+ type: literal("web_fetch_tool_result_error"),
167
+ error_code: string()
168
+ })
169
+ ])
170
+ }),
171
+ object({
172
+ type: literal("web_search_tool_result"),
173
+ tool_use_id: string(),
174
+ content: union([
175
+ array(
176
+ object({
177
+ type: literal("web_search_result"),
178
+ url: string(),
179
+ title: string(),
180
+ encrypted_content: string(),
181
+ page_age: string().nullish()
182
+ })
183
+ ),
184
+ object({
185
+ type: literal("web_search_tool_result_error"),
186
+ error_code: string()
187
+ })
188
+ ])
189
+ }),
190
+ // code execution results for code_execution_20250522 tool:
191
+ object({
192
+ type: literal("code_execution_tool_result"),
193
+ tool_use_id: string(),
194
+ content: union([
195
+ object({
196
+ type: literal("code_execution_result"),
197
+ stdout: string(),
198
+ stderr: string(),
199
+ return_code: number(),
200
+ content: array(
201
+ object({
202
+ type: literal("code_execution_output"),
203
+ file_id: string()
204
+ })
205
+ ).optional().default([])
206
+ }),
207
+ object({
208
+ type: literal("code_execution_tool_result_error"),
209
+ error_code: string()
210
+ })
211
+ ])
212
+ }),
213
+ // bash code execution results for code_execution_20250825 tool:
214
+ object({
215
+ type: literal("bash_code_execution_tool_result"),
216
+ tool_use_id: string(),
217
+ content: discriminatedUnion("type", [
218
+ object({
219
+ type: literal("bash_code_execution_result"),
220
+ content: array(
221
+ object({
222
+ type: literal("bash_code_execution_output"),
223
+ file_id: string()
224
+ })
225
+ ),
226
+ stdout: string(),
227
+ stderr: string(),
228
+ return_code: number()
229
+ }),
230
+ object({
231
+ type: literal("bash_code_execution_tool_result_error"),
232
+ error_code: string()
233
+ })
234
+ ])
235
+ }),
236
+ // text editor code execution results for code_execution_20250825 tool:
237
+ object({
238
+ type: literal("text_editor_code_execution_tool_result"),
239
+ tool_use_id: string(),
240
+ content: discriminatedUnion("type", [
241
+ object({
242
+ type: literal("text_editor_code_execution_tool_result_error"),
243
+ error_code: string()
244
+ }),
245
+ object({
246
+ type: literal("text_editor_code_execution_view_result"),
247
+ content: string(),
248
+ file_type: string(),
249
+ num_lines: number().nullable(),
250
+ start_line: number().nullable(),
251
+ total_lines: number().nullable()
252
+ }),
253
+ object({
254
+ type: literal("text_editor_code_execution_create_result"),
255
+ is_file_update: boolean()
256
+ }),
257
+ object({
258
+ type: literal(
259
+ "text_editor_code_execution_str_replace_result"
260
+ ),
261
+ lines: array(string()).nullable(),
262
+ new_lines: number().nullable(),
263
+ new_start: number().nullable(),
264
+ old_lines: number().nullable(),
265
+ old_start: number().nullable()
266
+ })
267
+ ])
268
+ }),
269
+ // tool search tool results for tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119:
270
+ object({
271
+ type: literal("tool_search_tool_result"),
272
+ tool_use_id: string(),
273
+ content: union([
274
+ object({
275
+ type: literal("tool_search_tool_search_result"),
276
+ tool_references: array(
277
+ object({
278
+ type: literal("tool_reference"),
279
+ tool_name: string()
280
+ })
281
+ )
282
+ }),
283
+ object({
284
+ type: literal("tool_search_tool_result_error"),
285
+ error_code: string()
286
+ })
287
+ ])
288
+ })
289
+ ])
290
+ ),
291
+ stop_reason: string().nullish(),
292
+ stop_sequence: string().nullish(),
293
+ usage: looseObject({
294
+ input_tokens: number(),
295
+ output_tokens: number(),
296
+ cache_creation_input_tokens: number().nullish(),
297
+ cache_read_input_tokens: number().nullish(),
298
+ iterations: array(
299
+ object({
300
+ type: union([literal("compaction"), literal("message")]),
301
+ input_tokens: number(),
302
+ output_tokens: number()
303
+ })
304
+ ).nullish()
305
+ }),
306
+ container: object({
307
+ expires_at: string(),
308
+ id: string(),
309
+ skills: array(
310
+ object({
311
+ type: union([literal("anthropic"), literal("custom")]),
312
+ skill_id: string(),
313
+ version: string()
314
+ })
315
+ ).nullish()
316
+ }).nullish(),
317
+ context_management: object({
318
+ applied_edits: array(
319
+ union([
320
+ object({
321
+ type: literal("clear_tool_uses_20250919"),
322
+ cleared_tool_uses: number(),
323
+ cleared_input_tokens: number()
324
+ }),
325
+ object({
326
+ type: literal("clear_thinking_20251015"),
327
+ cleared_thinking_turns: number(),
328
+ cleared_input_tokens: number()
329
+ }),
330
+ object({
331
+ type: literal("compact_20260112")
332
+ })
333
+ ])
334
+ )
335
+ }).nullish()
336
+ })
337
+ )
338
+ );
339
+ var anthropicMessagesChunkSchema = lazySchema(
340
+ () => zodSchema(
341
+ discriminatedUnion("type", [
342
+ object({
343
+ type: literal("message_start"),
344
+ message: object({
345
+ id: string().nullish(),
346
+ model: string().nullish(),
347
+ role: string().nullish(),
348
+ usage: looseObject({
349
+ input_tokens: number(),
350
+ cache_creation_input_tokens: number().nullish(),
351
+ cache_read_input_tokens: number().nullish()
352
+ }),
353
+ // Programmatic tool calling: content may be pre-populated for deferred tool calls
354
+ content: array(
355
+ discriminatedUnion("type", [
356
+ object({
357
+ type: literal("tool_use"),
358
+ id: string(),
359
+ name: string(),
360
+ input: unknown(),
361
+ caller: union([
362
+ object({
363
+ type: literal("code_execution_20250825"),
364
+ tool_id: string()
365
+ }),
366
+ object({
367
+ type: literal("direct")
368
+ })
369
+ ]).optional()
370
+ })
371
+ ])
372
+ ).nullish(),
373
+ stop_reason: string().nullish(),
374
+ container: object({
375
+ expires_at: string(),
376
+ id: string()
377
+ }).nullish()
378
+ })
379
+ }),
380
+ object({
381
+ type: literal("content_block_start"),
382
+ index: number(),
383
+ content_block: discriminatedUnion("type", [
384
+ object({
385
+ type: literal("text"),
386
+ text: string()
387
+ }),
388
+ object({
389
+ type: literal("thinking"),
390
+ thinking: string()
391
+ }),
392
+ object({
393
+ type: literal("tool_use"),
394
+ id: string(),
395
+ name: string(),
396
+ // Programmatic tool calling: input may be present directly for deferred tool calls
397
+ input: record(string(), unknown()).optional(),
398
+ // Programmatic tool calling: caller info when triggered from code execution
399
+ caller: union([
400
+ object({
401
+ type: literal("code_execution_20250825"),
402
+ tool_id: string()
403
+ }),
404
+ object({
405
+ type: literal("direct")
406
+ })
407
+ ]).optional()
408
+ }),
409
+ object({
410
+ type: literal("redacted_thinking"),
411
+ data: string()
412
+ }),
413
+ object({
414
+ type: literal("compaction"),
415
+ content: string().nullish()
416
+ }),
417
+ object({
418
+ type: literal("server_tool_use"),
419
+ id: string(),
420
+ name: string(),
421
+ input: record(string(), unknown()).nullish()
422
+ }),
423
+ object({
424
+ type: literal("mcp_tool_use"),
425
+ id: string(),
426
+ name: string(),
427
+ input: unknown(),
428
+ server_name: string()
429
+ }),
430
+ object({
431
+ type: literal("mcp_tool_result"),
432
+ tool_use_id: string(),
433
+ is_error: boolean(),
434
+ content: array(
435
+ union([
436
+ string(),
437
+ object({ type: literal("text"), text: string() })
438
+ ])
439
+ )
440
+ }),
441
+ object({
442
+ type: literal("web_fetch_tool_result"),
443
+ tool_use_id: string(),
444
+ content: union([
445
+ object({
446
+ type: literal("web_fetch_result"),
447
+ url: string(),
448
+ retrieved_at: string(),
449
+ content: object({
450
+ type: literal("document"),
451
+ title: string().nullable(),
452
+ citations: object({ enabled: boolean() }).optional(),
453
+ source: union([
454
+ object({
455
+ type: literal("base64"),
456
+ media_type: literal("application/pdf"),
457
+ data: string()
458
+ }),
459
+ object({
460
+ type: literal("text"),
461
+ media_type: literal("text/plain"),
462
+ data: string()
463
+ })
464
+ ])
465
+ })
466
+ }),
467
+ object({
468
+ type: literal("web_fetch_tool_result_error"),
469
+ error_code: string()
470
+ })
471
+ ])
472
+ }),
473
+ object({
474
+ type: literal("web_search_tool_result"),
475
+ tool_use_id: string(),
476
+ content: union([
477
+ array(
478
+ object({
479
+ type: literal("web_search_result"),
480
+ url: string(),
481
+ title: string(),
482
+ encrypted_content: string(),
483
+ page_age: string().nullish()
484
+ })
485
+ ),
486
+ object({
487
+ type: literal("web_search_tool_result_error"),
488
+ error_code: string()
489
+ })
490
+ ])
491
+ }),
492
+ // code execution results for code_execution_20250522 tool:
493
+ object({
494
+ type: literal("code_execution_tool_result"),
495
+ tool_use_id: string(),
496
+ content: union([
497
+ object({
498
+ type: literal("code_execution_result"),
499
+ stdout: string(),
500
+ stderr: string(),
501
+ return_code: number(),
502
+ content: array(
503
+ object({
504
+ type: literal("code_execution_output"),
505
+ file_id: string()
506
+ })
507
+ ).optional().default([])
508
+ }),
509
+ object({
510
+ type: literal("code_execution_tool_result_error"),
511
+ error_code: string()
512
+ })
513
+ ])
514
+ }),
515
+ // bash code execution results for code_execution_20250825 tool:
516
+ object({
517
+ type: literal("bash_code_execution_tool_result"),
518
+ tool_use_id: string(),
519
+ content: discriminatedUnion("type", [
520
+ object({
521
+ type: literal("bash_code_execution_result"),
522
+ content: array(
523
+ object({
524
+ type: literal("bash_code_execution_output"),
525
+ file_id: string()
526
+ })
527
+ ),
528
+ stdout: string(),
529
+ stderr: string(),
530
+ return_code: number()
531
+ }),
532
+ object({
533
+ type: literal("bash_code_execution_tool_result_error"),
534
+ error_code: string()
535
+ })
536
+ ])
537
+ }),
538
+ // text editor code execution results for code_execution_20250825 tool:
539
+ object({
540
+ type: literal("text_editor_code_execution_tool_result"),
541
+ tool_use_id: string(),
542
+ content: discriminatedUnion("type", [
543
+ object({
544
+ type: literal("text_editor_code_execution_tool_result_error"),
545
+ error_code: string()
546
+ }),
547
+ object({
548
+ type: literal("text_editor_code_execution_view_result"),
549
+ content: string(),
550
+ file_type: string(),
551
+ num_lines: number().nullable(),
552
+ start_line: number().nullable(),
553
+ total_lines: number().nullable()
554
+ }),
555
+ object({
556
+ type: literal("text_editor_code_execution_create_result"),
557
+ is_file_update: boolean()
558
+ }),
559
+ object({
560
+ type: literal(
561
+ "text_editor_code_execution_str_replace_result"
562
+ ),
563
+ lines: array(string()).nullable(),
564
+ new_lines: number().nullable(),
565
+ new_start: number().nullable(),
566
+ old_lines: number().nullable(),
567
+ old_start: number().nullable()
568
+ })
569
+ ])
570
+ }),
571
+ // tool search tool results for tool_search_tool_regex_20251119 and tool_search_tool_bm25_20251119:
572
+ object({
573
+ type: literal("tool_search_tool_result"),
574
+ tool_use_id: string(),
575
+ content: union([
576
+ object({
577
+ type: literal("tool_search_tool_search_result"),
578
+ tool_references: array(
579
+ object({
580
+ type: literal("tool_reference"),
581
+ tool_name: string()
582
+ })
583
+ )
584
+ }),
585
+ object({
586
+ type: literal("tool_search_tool_result_error"),
587
+ error_code: string()
588
+ })
589
+ ])
590
+ })
591
+ ])
592
+ }),
593
+ object({
594
+ type: literal("content_block_delta"),
595
+ index: number(),
596
+ delta: discriminatedUnion("type", [
597
+ object({
598
+ type: literal("input_json_delta"),
599
+ partial_json: string()
600
+ }),
601
+ object({
602
+ type: literal("text_delta"),
603
+ text: string()
604
+ }),
605
+ object({
606
+ type: literal("thinking_delta"),
607
+ thinking: string()
608
+ }),
609
+ object({
610
+ type: literal("signature_delta"),
611
+ signature: string()
612
+ }),
613
+ object({
614
+ type: literal("compaction_delta"),
615
+ content: string().nullish()
616
+ }),
617
+ object({
618
+ type: literal("citations_delta"),
619
+ citation: discriminatedUnion("type", [
620
+ object({
621
+ type: literal("web_search_result_location"),
622
+ cited_text: string(),
623
+ url: string(),
624
+ title: string(),
625
+ encrypted_index: string()
626
+ }),
627
+ object({
628
+ type: literal("page_location"),
629
+ cited_text: string(),
630
+ document_index: number(),
631
+ document_title: string().nullable(),
632
+ start_page_number: number(),
633
+ end_page_number: number()
634
+ }),
635
+ object({
636
+ type: literal("char_location"),
637
+ cited_text: string(),
638
+ document_index: number(),
639
+ document_title: string().nullable(),
640
+ start_char_index: number(),
641
+ end_char_index: number()
642
+ })
643
+ ])
644
+ })
645
+ ])
646
+ }),
647
+ object({
648
+ type: literal("content_block_stop"),
649
+ index: number()
650
+ }),
651
+ object({
652
+ type: literal("error"),
653
+ error: object({
654
+ type: string(),
655
+ message: string()
656
+ })
657
+ }),
658
+ object({
659
+ type: literal("message_delta"),
660
+ delta: object({
661
+ stop_reason: string().nullish(),
662
+ stop_sequence: string().nullish(),
663
+ container: object({
664
+ expires_at: string(),
665
+ id: string(),
666
+ skills: array(
667
+ object({
668
+ type: union([
669
+ literal("anthropic"),
670
+ literal("custom")
671
+ ]),
672
+ skill_id: string(),
673
+ version: string()
674
+ })
675
+ ).nullish()
676
+ }).nullish()
677
+ }),
678
+ usage: looseObject({
679
+ input_tokens: number().nullish(),
680
+ output_tokens: number(),
681
+ cache_creation_input_tokens: number().nullish(),
682
+ cache_read_input_tokens: number().nullish(),
683
+ iterations: array(
684
+ object({
685
+ type: union([literal("compaction"), literal("message")]),
686
+ input_tokens: number(),
687
+ output_tokens: number()
688
+ })
689
+ ).nullish()
690
+ }),
691
+ context_management: object({
692
+ applied_edits: array(
693
+ union([
694
+ object({
695
+ type: literal("clear_tool_uses_20250919"),
696
+ cleared_tool_uses: number(),
697
+ cleared_input_tokens: number()
698
+ }),
699
+ object({
700
+ type: literal("clear_thinking_20251015"),
701
+ cleared_thinking_turns: number(),
702
+ cleared_input_tokens: number()
703
+ }),
704
+ object({
705
+ type: literal("compact_20260112")
706
+ })
707
+ ])
708
+ )
709
+ }).nullish()
710
+ }),
711
+ object({
712
+ type: literal("message_stop")
713
+ }),
714
+ object({
715
+ type: literal("ping")
716
+ })
717
+ ])
718
+ )
719
+ );
720
+ var anthropicReasoningMetadataSchema = lazySchema(
721
+ () => zodSchema(
722
+ object({
723
+ signature: string().optional(),
724
+ redactedData: string().optional()
725
+ })
726
+ )
727
+ );
728
+ var anthropicFilePartProviderOptions = object({
729
+ /**
730
+ * Citation configuration for this document.
731
+ * When enabled, this document will generate citations in the response.
732
+ */
733
+ citations: object({
734
+ /**
735
+ * Enable citations for this document
736
+ */
737
+ enabled: boolean()
738
+ }).optional(),
739
+ /**
740
+ * Custom title for the document.
741
+ * If not provided, the filename will be used.
742
+ */
743
+ title: string().optional(),
744
+ /**
745
+ * Context about the document that will be passed to the model
746
+ * but not used towards cited content.
747
+ * Useful for storing document metadata as text or stringified JSON.
748
+ */
749
+ context: string().optional()
750
+ });
751
+ var anthropicLanguageModelOptions = object({
752
+ /**
753
+ * Whether to send reasoning to the model.
754
+ *
755
+ * This allows you to deactivate reasoning inputs for models that do not support them.
756
+ */
757
+ sendReasoning: boolean().optional(),
758
+ /**
759
+ * Determines how structured outputs are generated.
760
+ *
761
+ * - `outputFormat`: Use the `output_format` parameter to specify the structured output format.
762
+ * - `jsonTool`: Use a special 'json' tool to specify the structured output format.
763
+ * - `auto`: Use 'outputFormat' when supported, otherwise use 'jsonTool' (default).
764
+ */
765
+ structuredOutputMode: _enum(["outputFormat", "jsonTool", "auto"]).optional(),
766
+ /**
767
+ * Configuration for enabling Claude's extended thinking.
768
+ *
769
+ * When enabled, responses include thinking content blocks showing Claude's thinking process before the final answer.
770
+ * Requires a minimum budget of 1,024 tokens and counts towards the `max_tokens` limit.
771
+ */
772
+ thinking: discriminatedUnion("type", [
773
+ object({
774
+ /** for Sonnet 4.6, Opus 4.6, and newer models */
775
+ type: literal("adaptive")
776
+ }),
777
+ object({
778
+ /** for models before Opus 4.6, except Sonnet 4.6 still supports it */
779
+ type: literal("enabled"),
780
+ budgetTokens: number().optional()
781
+ }),
782
+ object({
783
+ type: literal("disabled")
784
+ })
785
+ ]).optional(),
786
+ /**
787
+ * Whether to disable parallel function calling during tool use. Default is false.
788
+ * When set to true, Claude will use at most one tool per response.
789
+ */
790
+ disableParallelToolUse: boolean().optional(),
791
+ /**
792
+ * Cache control settings for this message.
793
+ * See https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
794
+ */
795
+ cacheControl: object({
796
+ type: literal("ephemeral"),
797
+ ttl: union([literal("5m"), literal("1h")]).optional()
798
+ }).optional(),
799
+ /**
800
+ * MCP servers to be utilized in this request.
801
+ */
802
+ mcpServers: array(
803
+ object({
804
+ type: literal("url"),
805
+ name: string(),
806
+ url: string(),
807
+ authorizationToken: string().nullish(),
808
+ toolConfiguration: object({
809
+ enabled: boolean().nullish(),
810
+ allowedTools: array(string()).nullish()
811
+ }).nullish()
812
+ })
813
+ ).optional(),
814
+ /**
815
+ * Agent Skills configuration. Skills enable Claude to perform specialized tasks
816
+ * like document processing (PPTX, DOCX, PDF, XLSX) and data analysis.
817
+ * Requires code execution tool to be enabled.
818
+ */
819
+ container: object({
820
+ id: string().optional(),
821
+ skills: array(
822
+ object({
823
+ type: union([literal("anthropic"), literal("custom")]),
824
+ skillId: string(),
825
+ version: string().optional()
826
+ })
827
+ ).optional()
828
+ }).optional(),
829
+ /**
830
+ * Whether to enable tool streaming (and structured output streaming).
831
+ *
832
+ * When set to false, the model will return all tool calls and results
833
+ * at once after a delay.
834
+ *
835
+ * @default true
836
+ */
837
+ toolStreaming: boolean().optional(),
838
+ /**
839
+ * @default 'high'
840
+ */
841
+ effort: _enum(["low", "medium", "high", "max"]).optional(),
842
+ /**
843
+ * Enable fast mode for faster inference (2.5x faster output token speeds).
844
+ * Only supported with claude-opus-4-6.
845
+ */
846
+ speed: _enum(["fast", "standard"]).optional(),
847
+ contextManagement: object({
848
+ edits: array(
849
+ discriminatedUnion("type", [
850
+ object({
851
+ type: literal("clear_tool_uses_20250919"),
852
+ trigger: discriminatedUnion("type", [
853
+ object({
854
+ type: literal("input_tokens"),
855
+ value: number()
856
+ }),
857
+ object({
858
+ type: literal("tool_uses"),
859
+ value: number()
860
+ })
861
+ ]).optional(),
862
+ keep: object({
863
+ type: literal("tool_uses"),
864
+ value: number()
865
+ }).optional(),
866
+ clearAtLeast: object({
867
+ type: literal("input_tokens"),
868
+ value: number()
869
+ }).optional(),
870
+ clearToolInputs: boolean().optional(),
871
+ excludeTools: array(string()).optional()
872
+ }),
873
+ object({
874
+ type: literal("clear_thinking_20251015"),
875
+ keep: union([
876
+ literal("all"),
877
+ object({
878
+ type: literal("thinking_turns"),
879
+ value: number()
880
+ })
881
+ ]).optional()
882
+ }),
883
+ object({
884
+ type: literal("compact_20260112"),
885
+ trigger: object({
886
+ type: literal("input_tokens"),
887
+ value: number()
888
+ }).optional(),
889
+ pauseAfterCompaction: boolean().optional(),
890
+ instructions: string().optional()
891
+ })
892
+ ])
893
+ )
894
+ }).optional()
895
+ });
896
+ var MAX_CACHE_BREAKPOINTS = 4;
897
+ function getCacheControl(providerMetadata) {
898
+ var _a;
899
+ const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic;
900
+ const cacheControlValue = (_a = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a : anthropic2 == null ? void 0 : anthropic2.cache_control;
901
+ return cacheControlValue;
902
+ }
903
+ var CacheControlValidator = class {
904
+ constructor() {
905
+ this.breakpointCount = 0;
906
+ this.warnings = [];
907
+ }
908
+ getCacheControl(providerMetadata, context) {
909
+ const cacheControlValue = getCacheControl(providerMetadata);
910
+ if (!cacheControlValue) {
911
+ return void 0;
912
+ }
913
+ if (!context.canCache) {
914
+ this.warnings.push({
915
+ type: "unsupported",
916
+ feature: "cache_control on non-cacheable context",
917
+ details: `cache_control cannot be set on ${context.type}. It will be ignored.`
918
+ });
919
+ return void 0;
920
+ }
921
+ this.breakpointCount++;
922
+ if (this.breakpointCount > MAX_CACHE_BREAKPOINTS) {
923
+ this.warnings.push({
924
+ type: "unsupported",
925
+ feature: "cacheControl breakpoint limit",
926
+ details: `Maximum ${MAX_CACHE_BREAKPOINTS} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`
927
+ });
928
+ return void 0;
929
+ }
930
+ return cacheControlValue;
931
+ }
932
+ getWarnings() {
933
+ return this.warnings;
934
+ }
935
+ };
936
+ var textEditor_20250728ArgsSchema = lazySchema(
937
+ () => zodSchema(
938
+ object({
939
+ maxCharacters: number().optional()
940
+ })
941
+ )
942
+ );
943
+ var textEditor_20250728InputSchema = lazySchema(
944
+ () => zodSchema(
945
+ object({
946
+ command: _enum(["view", "create", "str_replace", "insert"]),
947
+ path: string(),
948
+ file_text: string().optional(),
949
+ insert_line: number().int().optional(),
950
+ new_str: string().optional(),
951
+ insert_text: string().optional(),
952
+ old_str: string().optional(),
953
+ view_range: array(number().int()).optional()
954
+ })
955
+ )
956
+ );
957
+ var factory = createProviderToolFactory({
958
+ id: "anthropic.text_editor_20250728",
959
+ inputSchema: textEditor_20250728InputSchema
960
+ });
961
+ var textEditor_20250728 = (args = {}) => {
962
+ return factory(args);
963
+ };
964
+ var webSearch_20250305ArgsSchema = lazySchema(
965
+ () => zodSchema(
966
+ object({
967
+ maxUses: number().optional(),
968
+ allowedDomains: array(string()).optional(),
969
+ blockedDomains: array(string()).optional(),
970
+ userLocation: object({
971
+ type: literal("approximate"),
972
+ city: string().optional(),
973
+ region: string().optional(),
974
+ country: string().optional(),
975
+ timezone: string().optional()
976
+ }).optional()
977
+ })
978
+ )
979
+ );
980
+ var webSearch_20250305OutputSchema = lazySchema(
981
+ () => zodSchema(
982
+ array(
983
+ object({
984
+ url: string(),
985
+ title: string().nullable(),
986
+ pageAge: string().nullable(),
987
+ encryptedContent: string(),
988
+ type: literal("web_search_result")
989
+ })
990
+ )
991
+ )
992
+ );
993
+ var webSearch_20250305InputSchema = lazySchema(
994
+ () => zodSchema(
995
+ object({
996
+ query: string()
997
+ })
998
+ )
999
+ );
1000
+ var factory2 = createProviderToolFactoryWithOutputSchema({
1001
+ id: "anthropic.web_search_20250305",
1002
+ inputSchema: webSearch_20250305InputSchema,
1003
+ outputSchema: webSearch_20250305OutputSchema,
1004
+ supportsDeferredResults: true
1005
+ });
1006
+ var webSearch_20250305 = (args = {}) => {
1007
+ return factory2(args);
1008
+ };
1009
+ var webFetch_20250910ArgsSchema = lazySchema(
1010
+ () => zodSchema(
1011
+ object({
1012
+ maxUses: number().optional(),
1013
+ allowedDomains: array(string()).optional(),
1014
+ blockedDomains: array(string()).optional(),
1015
+ citations: object({ enabled: boolean() }).optional(),
1016
+ maxContentTokens: number().optional()
1017
+ })
1018
+ )
1019
+ );
1020
+ var webFetch_20250910OutputSchema = lazySchema(
1021
+ () => zodSchema(
1022
+ object({
1023
+ type: literal("web_fetch_result"),
1024
+ url: string(),
1025
+ content: object({
1026
+ type: literal("document"),
1027
+ title: string().nullable(),
1028
+ citations: object({ enabled: boolean() }).optional(),
1029
+ source: union([
1030
+ object({
1031
+ type: literal("base64"),
1032
+ mediaType: literal("application/pdf"),
1033
+ data: string()
1034
+ }),
1035
+ object({
1036
+ type: literal("text"),
1037
+ mediaType: literal("text/plain"),
1038
+ data: string()
1039
+ })
1040
+ ])
1041
+ }),
1042
+ retrievedAt: string().nullable()
1043
+ })
1044
+ )
1045
+ );
1046
+ var webFetch_20250910InputSchema = lazySchema(
1047
+ () => zodSchema(
1048
+ object({
1049
+ url: string()
1050
+ })
1051
+ )
1052
+ );
1053
+ var factory3 = createProviderToolFactoryWithOutputSchema({
1054
+ id: "anthropic.web_fetch_20250910",
1055
+ inputSchema: webFetch_20250910InputSchema,
1056
+ outputSchema: webFetch_20250910OutputSchema,
1057
+ supportsDeferredResults: true
1058
+ });
1059
+ var webFetch_20250910 = (args = {}) => {
1060
+ return factory3(args);
1061
+ };
1062
+ async function prepareTools({
1063
+ tools,
1064
+ toolChoice,
1065
+ disableParallelToolUse,
1066
+ cacheControlValidator,
1067
+ supportsStructuredOutput
1068
+ }) {
1069
+ var _a;
1070
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
1071
+ const toolWarnings = [];
1072
+ const betas = /* @__PURE__ */ new Set();
1073
+ const validator = cacheControlValidator || new CacheControlValidator();
1074
+ if (tools == null) {
1075
+ return { tools: void 0, toolChoice: void 0, toolWarnings, betas };
1076
+ }
1077
+ const anthropicTools2 = [];
1078
+ for (const tool of tools) {
1079
+ switch (tool.type) {
1080
+ case "function": {
1081
+ const cacheControl = validator.getCacheControl(tool.providerOptions, {
1082
+ type: "tool definition",
1083
+ canCache: true
1084
+ });
1085
+ const anthropicOptions = (_a = tool.providerOptions) == null ? void 0 : _a.anthropic;
1086
+ const deferLoading = anthropicOptions == null ? void 0 : anthropicOptions.deferLoading;
1087
+ const allowedCallers = anthropicOptions == null ? void 0 : anthropicOptions.allowedCallers;
1088
+ anthropicTools2.push({
1089
+ name: tool.name,
1090
+ description: tool.description,
1091
+ input_schema: tool.inputSchema,
1092
+ cache_control: cacheControl,
1093
+ ...supportsStructuredOutput === true && tool.strict != null ? { strict: tool.strict } : {},
1094
+ ...deferLoading != null ? { defer_loading: deferLoading } : {},
1095
+ ...allowedCallers != null ? { allowed_callers: allowedCallers } : {},
1096
+ ...tool.inputExamples != null ? {
1097
+ input_examples: tool.inputExamples.map(
1098
+ (example) => example.input
1099
+ )
1100
+ } : {}
1101
+ });
1102
+ if (supportsStructuredOutput === true) {
1103
+ betas.add("structured-outputs-2025-11-13");
1104
+ }
1105
+ if (tool.inputExamples != null || allowedCallers != null) {
1106
+ betas.add("advanced-tool-use-2025-11-20");
1107
+ }
1108
+ break;
1109
+ }
1110
+ case "provider": {
1111
+ switch (tool.id) {
1112
+ case "anthropic.code_execution_20250522": {
1113
+ betas.add("code-execution-2025-05-22");
1114
+ anthropicTools2.push({
1115
+ type: "code_execution_20250522",
1116
+ name: "code_execution",
1117
+ cache_control: void 0
1118
+ });
1119
+ break;
1120
+ }
1121
+ case "anthropic.code_execution_20250825": {
1122
+ betas.add("code-execution-2025-08-25");
1123
+ anthropicTools2.push({
1124
+ type: "code_execution_20250825",
1125
+ name: "code_execution"
1126
+ });
1127
+ break;
1128
+ }
1129
+ case "anthropic.computer_20250124": {
1130
+ betas.add("computer-use-2025-01-24");
1131
+ anthropicTools2.push({
1132
+ name: "computer",
1133
+ type: "computer_20250124",
1134
+ display_width_px: tool.args.displayWidthPx,
1135
+ display_height_px: tool.args.displayHeightPx,
1136
+ display_number: tool.args.displayNumber,
1137
+ cache_control: void 0
1138
+ });
1139
+ break;
1140
+ }
1141
+ case "anthropic.computer_20251124": {
1142
+ betas.add("computer-use-2025-11-24");
1143
+ anthropicTools2.push({
1144
+ name: "computer",
1145
+ type: "computer_20251124",
1146
+ display_width_px: tool.args.displayWidthPx,
1147
+ display_height_px: tool.args.displayHeightPx,
1148
+ display_number: tool.args.displayNumber,
1149
+ enable_zoom: tool.args.enableZoom,
1150
+ cache_control: void 0
1151
+ });
1152
+ break;
1153
+ }
1154
+ case "anthropic.computer_20241022": {
1155
+ betas.add("computer-use-2024-10-22");
1156
+ anthropicTools2.push({
1157
+ name: "computer",
1158
+ type: "computer_20241022",
1159
+ display_width_px: tool.args.displayWidthPx,
1160
+ display_height_px: tool.args.displayHeightPx,
1161
+ display_number: tool.args.displayNumber,
1162
+ cache_control: void 0
1163
+ });
1164
+ break;
1165
+ }
1166
+ case "anthropic.text_editor_20250124": {
1167
+ betas.add("computer-use-2025-01-24");
1168
+ anthropicTools2.push({
1169
+ name: "str_replace_editor",
1170
+ type: "text_editor_20250124",
1171
+ cache_control: void 0
1172
+ });
1173
+ break;
1174
+ }
1175
+ case "anthropic.text_editor_20241022": {
1176
+ betas.add("computer-use-2024-10-22");
1177
+ anthropicTools2.push({
1178
+ name: "str_replace_editor",
1179
+ type: "text_editor_20241022",
1180
+ cache_control: void 0
1181
+ });
1182
+ break;
1183
+ }
1184
+ case "anthropic.text_editor_20250429": {
1185
+ betas.add("computer-use-2025-01-24");
1186
+ anthropicTools2.push({
1187
+ name: "str_replace_based_edit_tool",
1188
+ type: "text_editor_20250429",
1189
+ cache_control: void 0
1190
+ });
1191
+ break;
1192
+ }
1193
+ case "anthropic.text_editor_20250728": {
1194
+ const args = await validateTypes({
1195
+ value: tool.args,
1196
+ schema: textEditor_20250728ArgsSchema
1197
+ });
1198
+ anthropicTools2.push({
1199
+ name: "str_replace_based_edit_tool",
1200
+ type: "text_editor_20250728",
1201
+ max_characters: args.maxCharacters,
1202
+ cache_control: void 0
1203
+ });
1204
+ break;
1205
+ }
1206
+ case "anthropic.bash_20250124": {
1207
+ betas.add("computer-use-2025-01-24");
1208
+ anthropicTools2.push({
1209
+ name: "bash",
1210
+ type: "bash_20250124",
1211
+ cache_control: void 0
1212
+ });
1213
+ break;
1214
+ }
1215
+ case "anthropic.bash_20241022": {
1216
+ betas.add("computer-use-2024-10-22");
1217
+ anthropicTools2.push({
1218
+ name: "bash",
1219
+ type: "bash_20241022",
1220
+ cache_control: void 0
1221
+ });
1222
+ break;
1223
+ }
1224
+ case "anthropic.memory_20250818": {
1225
+ betas.add("context-management-2025-06-27");
1226
+ anthropicTools2.push({
1227
+ name: "memory",
1228
+ type: "memory_20250818"
1229
+ });
1230
+ break;
1231
+ }
1232
+ case "anthropic.web_fetch_20250910": {
1233
+ betas.add("web-fetch-2025-09-10");
1234
+ const args = await validateTypes({
1235
+ value: tool.args,
1236
+ schema: webFetch_20250910ArgsSchema
1237
+ });
1238
+ anthropicTools2.push({
1239
+ type: "web_fetch_20250910",
1240
+ name: "web_fetch",
1241
+ max_uses: args.maxUses,
1242
+ allowed_domains: args.allowedDomains,
1243
+ blocked_domains: args.blockedDomains,
1244
+ citations: args.citations,
1245
+ max_content_tokens: args.maxContentTokens,
1246
+ cache_control: void 0
1247
+ });
1248
+ break;
1249
+ }
1250
+ case "anthropic.web_search_20250305": {
1251
+ const args = await validateTypes({
1252
+ value: tool.args,
1253
+ schema: webSearch_20250305ArgsSchema
1254
+ });
1255
+ anthropicTools2.push({
1256
+ type: "web_search_20250305",
1257
+ name: "web_search",
1258
+ max_uses: args.maxUses,
1259
+ allowed_domains: args.allowedDomains,
1260
+ blocked_domains: args.blockedDomains,
1261
+ user_location: args.userLocation,
1262
+ cache_control: void 0
1263
+ });
1264
+ break;
1265
+ }
1266
+ case "anthropic.tool_search_regex_20251119": {
1267
+ betas.add("advanced-tool-use-2025-11-20");
1268
+ anthropicTools2.push({
1269
+ type: "tool_search_tool_regex_20251119",
1270
+ name: "tool_search_tool_regex"
1271
+ });
1272
+ break;
1273
+ }
1274
+ case "anthropic.tool_search_bm25_20251119": {
1275
+ betas.add("advanced-tool-use-2025-11-20");
1276
+ anthropicTools2.push({
1277
+ type: "tool_search_tool_bm25_20251119",
1278
+ name: "tool_search_tool_bm25"
1279
+ });
1280
+ break;
1281
+ }
1282
+ default: {
1283
+ toolWarnings.push({
1284
+ type: "unsupported",
1285
+ feature: `provider-defined tool ${tool.id}`
1286
+ });
1287
+ break;
1288
+ }
1289
+ }
1290
+ break;
1291
+ }
1292
+ default: {
1293
+ toolWarnings.push({
1294
+ type: "unsupported",
1295
+ feature: `tool ${tool}`
1296
+ });
1297
+ break;
1298
+ }
1299
+ }
1300
+ }
1301
+ if (toolChoice == null) {
1302
+ return {
1303
+ tools: anthropicTools2,
1304
+ toolChoice: disableParallelToolUse ? { type: "auto", disable_parallel_tool_use: disableParallelToolUse } : void 0,
1305
+ toolWarnings,
1306
+ betas
1307
+ };
1308
+ }
1309
+ const type = toolChoice.type;
1310
+ switch (type) {
1311
+ case "auto":
1312
+ return {
1313
+ tools: anthropicTools2,
1314
+ toolChoice: {
1315
+ type: "auto",
1316
+ disable_parallel_tool_use: disableParallelToolUse
1317
+ },
1318
+ toolWarnings,
1319
+ betas
1320
+ };
1321
+ case "required":
1322
+ return {
1323
+ tools: anthropicTools2,
1324
+ toolChoice: {
1325
+ type: "any",
1326
+ disable_parallel_tool_use: disableParallelToolUse
1327
+ },
1328
+ toolWarnings,
1329
+ betas
1330
+ };
1331
+ case "none":
1332
+ return { tools: void 0, toolChoice: void 0, toolWarnings, betas };
1333
+ case "tool":
1334
+ return {
1335
+ tools: anthropicTools2,
1336
+ toolChoice: {
1337
+ type: "tool",
1338
+ name: toolChoice.toolName,
1339
+ disable_parallel_tool_use: disableParallelToolUse
1340
+ },
1341
+ toolWarnings,
1342
+ betas
1343
+ };
1344
+ default: {
1345
+ const _exhaustiveCheck = type;
1346
+ throw new UnsupportedFunctionalityError({
1347
+ functionality: `tool choice type: ${_exhaustiveCheck}`
1348
+ });
1349
+ }
1350
+ }
1351
+ }
1352
+ function convertAnthropicMessagesUsage({
1353
+ usage,
1354
+ rawUsage
1355
+ }) {
1356
+ var _a, _b;
1357
+ const cacheCreationTokens = (_a = usage.cache_creation_input_tokens) != null ? _a : 0;
1358
+ const cacheReadTokens = (_b = usage.cache_read_input_tokens) != null ? _b : 0;
1359
+ let inputTokens;
1360
+ let outputTokens;
1361
+ if (usage.iterations && usage.iterations.length > 0) {
1362
+ const totals = usage.iterations.reduce(
1363
+ (acc, iter) => ({
1364
+ input: acc.input + iter.input_tokens,
1365
+ output: acc.output + iter.output_tokens
1366
+ }),
1367
+ { input: 0, output: 0 }
1368
+ );
1369
+ inputTokens = totals.input;
1370
+ outputTokens = totals.output;
1371
+ } else {
1372
+ inputTokens = usage.input_tokens;
1373
+ outputTokens = usage.output_tokens;
1374
+ }
1375
+ return {
1376
+ inputTokens: {
1377
+ total: inputTokens + cacheCreationTokens + cacheReadTokens,
1378
+ noCache: inputTokens,
1379
+ cacheRead: cacheReadTokens,
1380
+ cacheWrite: cacheCreationTokens
1381
+ },
1382
+ outputTokens: {
1383
+ total: outputTokens,
1384
+ text: void 0,
1385
+ reasoning: void 0
1386
+ },
1387
+ raw: rawUsage != null ? rawUsage : usage
1388
+ };
1389
+ }
1390
+ var codeExecution_20250522OutputSchema = lazySchema(
1391
+ () => zodSchema(
1392
+ object({
1393
+ type: literal("code_execution_result"),
1394
+ stdout: string(),
1395
+ stderr: string(),
1396
+ return_code: number(),
1397
+ content: array(
1398
+ object({
1399
+ type: literal("code_execution_output"),
1400
+ file_id: string()
1401
+ })
1402
+ ).optional().default([])
1403
+ })
1404
+ )
1405
+ );
1406
+ var codeExecution_20250522InputSchema = lazySchema(
1407
+ () => zodSchema(
1408
+ object({
1409
+ code: string()
1410
+ })
1411
+ )
1412
+ );
1413
+ var factory4 = createProviderToolFactoryWithOutputSchema({
1414
+ id: "anthropic.code_execution_20250522",
1415
+ inputSchema: codeExecution_20250522InputSchema,
1416
+ outputSchema: codeExecution_20250522OutputSchema
1417
+ });
1418
+ var codeExecution_20250522 = (args = {}) => {
1419
+ return factory4(args);
1420
+ };
1421
+ var codeExecution_20250825OutputSchema = lazySchema(
1422
+ () => zodSchema(
1423
+ discriminatedUnion("type", [
1424
+ object({
1425
+ type: literal("code_execution_result"),
1426
+ stdout: string(),
1427
+ stderr: string(),
1428
+ return_code: number(),
1429
+ content: array(
1430
+ object({
1431
+ type: literal("code_execution_output"),
1432
+ file_id: string()
1433
+ })
1434
+ ).optional().default([])
1435
+ }),
1436
+ object({
1437
+ type: literal("bash_code_execution_result"),
1438
+ content: array(
1439
+ object({
1440
+ type: literal("bash_code_execution_output"),
1441
+ file_id: string()
1442
+ })
1443
+ ),
1444
+ stdout: string(),
1445
+ stderr: string(),
1446
+ return_code: number()
1447
+ }),
1448
+ object({
1449
+ type: literal("bash_code_execution_tool_result_error"),
1450
+ error_code: string()
1451
+ }),
1452
+ object({
1453
+ type: literal("text_editor_code_execution_tool_result_error"),
1454
+ error_code: string()
1455
+ }),
1456
+ object({
1457
+ type: literal("text_editor_code_execution_view_result"),
1458
+ content: string(),
1459
+ file_type: string(),
1460
+ num_lines: number().nullable(),
1461
+ start_line: number().nullable(),
1462
+ total_lines: number().nullable()
1463
+ }),
1464
+ object({
1465
+ type: literal("text_editor_code_execution_create_result"),
1466
+ is_file_update: boolean()
1467
+ }),
1468
+ object({
1469
+ type: literal("text_editor_code_execution_str_replace_result"),
1470
+ lines: array(string()).nullable(),
1471
+ new_lines: number().nullable(),
1472
+ new_start: number().nullable(),
1473
+ old_lines: number().nullable(),
1474
+ old_start: number().nullable()
1475
+ })
1476
+ ])
1477
+ )
1478
+ );
1479
+ var codeExecution_20250825InputSchema = lazySchema(
1480
+ () => zodSchema(
1481
+ discriminatedUnion("type", [
1482
+ // Programmatic tool calling format (mapped from { code } by AI SDK)
1483
+ object({
1484
+ type: literal("programmatic-tool-call"),
1485
+ code: string()
1486
+ }),
1487
+ object({
1488
+ type: literal("bash_code_execution"),
1489
+ command: string()
1490
+ }),
1491
+ discriminatedUnion("command", [
1492
+ object({
1493
+ type: literal("text_editor_code_execution"),
1494
+ command: literal("view"),
1495
+ path: string()
1496
+ }),
1497
+ object({
1498
+ type: literal("text_editor_code_execution"),
1499
+ command: literal("create"),
1500
+ path: string(),
1501
+ file_text: string().nullish()
1502
+ }),
1503
+ object({
1504
+ type: literal("text_editor_code_execution"),
1505
+ command: literal("str_replace"),
1506
+ path: string(),
1507
+ old_str: string(),
1508
+ new_str: string()
1509
+ })
1510
+ ])
1511
+ ])
1512
+ )
1513
+ );
1514
+ var factory5 = createProviderToolFactoryWithOutputSchema({
1515
+ id: "anthropic.code_execution_20250825",
1516
+ inputSchema: codeExecution_20250825InputSchema,
1517
+ outputSchema: codeExecution_20250825OutputSchema,
1518
+ // Programmatic tool calling: tool results may be deferred to a later turn
1519
+ // when code execution triggers a client-executed tool that needs to be
1520
+ // resolved before the code execution result can be returned.
1521
+ supportsDeferredResults: true
1522
+ });
1523
+ var codeExecution_20250825 = (args = {}) => {
1524
+ return factory5(args);
1525
+ };
1526
+ var toolSearchRegex_20251119OutputSchema = lazySchema(
1527
+ () => zodSchema(
1528
+ array(
1529
+ object({
1530
+ type: literal("tool_reference"),
1531
+ toolName: string()
1532
+ })
1533
+ )
1534
+ )
1535
+ );
1536
+ var toolSearchRegex_20251119InputSchema = lazySchema(
1537
+ () => zodSchema(
1538
+ object({
1539
+ /**
1540
+ * A regex pattern to search for tools.
1541
+ * Uses Python re.search() syntax. Maximum 200 characters.
1542
+ *
1543
+ * Examples:
1544
+ * - "weather" - matches tool names/descriptions containing "weather"
1545
+ * - "get_.*_data" - matches tools like get_user_data, get_weather_data
1546
+ * - "database.*query|query.*database" - OR patterns for flexibility
1547
+ * - "(?i)slack" - case-insensitive search
1548
+ */
1549
+ pattern: string(),
1550
+ /**
1551
+ * Maximum number of tools to return. Optional.
1552
+ */
1553
+ limit: number().optional()
1554
+ })
1555
+ )
1556
+ );
1557
+ var factory6 = createProviderToolFactoryWithOutputSchema({
1558
+ id: "anthropic.tool_search_regex_20251119",
1559
+ inputSchema: toolSearchRegex_20251119InputSchema,
1560
+ outputSchema: toolSearchRegex_20251119OutputSchema,
1561
+ supportsDeferredResults: true
1562
+ });
1563
+ var toolSearchRegex_20251119 = (args = {}) => {
1564
+ return factory6(args);
1565
+ };
1566
+ function convertToString(data) {
1567
+ if (typeof data === "string") {
1568
+ return Buffer.from(data, "base64").toString("utf-8");
1569
+ }
1570
+ if (data instanceof Uint8Array) {
1571
+ return new TextDecoder().decode(data);
1572
+ }
1573
+ if (data instanceof URL) {
1574
+ throw new UnsupportedFunctionalityError({
1575
+ functionality: "URL-based text documents are not supported for citations"
1576
+ });
1577
+ }
1578
+ throw new UnsupportedFunctionalityError({
1579
+ functionality: `unsupported data type for text documents: ${typeof data}`
1580
+ });
1581
+ }
1582
+ function isUrlData(data) {
1583
+ return data instanceof URL || isUrlString(data);
1584
+ }
1585
+ function isUrlString(data) {
1586
+ return typeof data === "string" && /^https?:\/\//i.test(data);
1587
+ }
1588
+ function getUrlString(data) {
1589
+ return data instanceof URL ? data.toString() : data;
1590
+ }
1591
+ async function convertToAnthropicMessagesPrompt({
1592
+ prompt,
1593
+ sendReasoning,
1594
+ warnings,
1595
+ cacheControlValidator,
1596
+ toolNameMapping
1597
+ }) {
1598
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
1599
+ const betas = /* @__PURE__ */ new Set();
1600
+ const blocks = groupIntoBlocks(prompt);
1601
+ const validator = cacheControlValidator || new CacheControlValidator();
1602
+ let system = void 0;
1603
+ const messages = [];
1604
+ async function shouldEnableCitations(providerMetadata) {
1605
+ var _a2, _b2;
1606
+ const anthropicOptions = await parseProviderOptions({
1607
+ provider: "anthropic",
1608
+ providerOptions: providerMetadata,
1609
+ schema: anthropicFilePartProviderOptions
1610
+ });
1611
+ return (_b2 = (_a2 = anthropicOptions == null ? void 0 : anthropicOptions.citations) == null ? void 0 : _a2.enabled) != null ? _b2 : false;
1612
+ }
1613
+ async function getDocumentMetadata(providerMetadata) {
1614
+ const anthropicOptions = await parseProviderOptions({
1615
+ provider: "anthropic",
1616
+ providerOptions: providerMetadata,
1617
+ schema: anthropicFilePartProviderOptions
1618
+ });
1619
+ return {
1620
+ title: anthropicOptions == null ? void 0 : anthropicOptions.title,
1621
+ context: anthropicOptions == null ? void 0 : anthropicOptions.context
1622
+ };
1623
+ }
1624
+ for (let i = 0; i < blocks.length; i++) {
1625
+ const block = blocks[i];
1626
+ const isLastBlock = i === blocks.length - 1;
1627
+ const type = block.type;
1628
+ switch (type) {
1629
+ case "system": {
1630
+ if (system != null) {
1631
+ throw new UnsupportedFunctionalityError({
1632
+ functionality: "Multiple system messages that are separated by user/assistant messages"
1633
+ });
1634
+ }
1635
+ system = block.messages.map(({ content, providerOptions }) => ({
1636
+ type: "text",
1637
+ text: content,
1638
+ cache_control: validator.getCacheControl(providerOptions, {
1639
+ type: "system message",
1640
+ canCache: true
1641
+ })
1642
+ }));
1643
+ break;
1644
+ }
1645
+ case "user": {
1646
+ const anthropicContent = [];
1647
+ for (const message of block.messages) {
1648
+ const { role, content } = message;
1649
+ switch (role) {
1650
+ case "user": {
1651
+ for (let j = 0; j < content.length; j++) {
1652
+ const part = content[j];
1653
+ const isLastPart = j === content.length - 1;
1654
+ const cacheControl = (_a = validator.getCacheControl(part.providerOptions, {
1655
+ type: "user message part",
1656
+ canCache: true
1657
+ })) != null ? _a : isLastPart ? validator.getCacheControl(message.providerOptions, {
1658
+ type: "user message",
1659
+ canCache: true
1660
+ }) : void 0;
1661
+ switch (part.type) {
1662
+ case "text": {
1663
+ anthropicContent.push({
1664
+ type: "text",
1665
+ text: part.text,
1666
+ cache_control: cacheControl
1667
+ });
1668
+ break;
1669
+ }
1670
+ case "file": {
1671
+ if (part.mediaType.startsWith("image/")) {
1672
+ anthropicContent.push({
1673
+ type: "image",
1674
+ source: isUrlData(part.data) ? {
1675
+ type: "url",
1676
+ url: getUrlString(part.data)
1677
+ } : {
1678
+ type: "base64",
1679
+ media_type: part.mediaType === "image/*" ? "image/jpeg" : part.mediaType,
1680
+ data: convertToBase64(part.data)
1681
+ },
1682
+ cache_control: cacheControl
1683
+ });
1684
+ } else if (part.mediaType === "application/pdf") {
1685
+ betas.add("pdfs-2024-09-25");
1686
+ const enableCitations = await shouldEnableCitations(
1687
+ part.providerOptions
1688
+ );
1689
+ const metadata = await getDocumentMetadata(
1690
+ part.providerOptions
1691
+ );
1692
+ anthropicContent.push({
1693
+ type: "document",
1694
+ source: isUrlData(part.data) ? {
1695
+ type: "url",
1696
+ url: getUrlString(part.data)
1697
+ } : {
1698
+ type: "base64",
1699
+ media_type: "application/pdf",
1700
+ data: convertToBase64(part.data)
1701
+ },
1702
+ title: (_b = metadata.title) != null ? _b : part.filename,
1703
+ ...metadata.context && { context: metadata.context },
1704
+ ...enableCitations && {
1705
+ citations: { enabled: true }
1706
+ },
1707
+ cache_control: cacheControl
1708
+ });
1709
+ } else if (part.mediaType === "text/plain") {
1710
+ const enableCitations = await shouldEnableCitations(
1711
+ part.providerOptions
1712
+ );
1713
+ const metadata = await getDocumentMetadata(
1714
+ part.providerOptions
1715
+ );
1716
+ anthropicContent.push({
1717
+ type: "document",
1718
+ source: isUrlData(part.data) ? {
1719
+ type: "url",
1720
+ url: getUrlString(part.data)
1721
+ } : {
1722
+ type: "text",
1723
+ media_type: "text/plain",
1724
+ data: convertToString(part.data)
1725
+ },
1726
+ title: (_c = metadata.title) != null ? _c : part.filename,
1727
+ ...metadata.context && { context: metadata.context },
1728
+ ...enableCitations && {
1729
+ citations: { enabled: true }
1730
+ },
1731
+ cache_control: cacheControl
1732
+ });
1733
+ } else {
1734
+ throw new UnsupportedFunctionalityError({
1735
+ functionality: `media type: ${part.mediaType}`
1736
+ });
1737
+ }
1738
+ break;
1739
+ }
1740
+ }
1741
+ }
1742
+ break;
1743
+ }
1744
+ case "tool": {
1745
+ for (let i2 = 0; i2 < content.length; i2++) {
1746
+ const part = content[i2];
1747
+ if (part.type === "tool-approval-response") {
1748
+ continue;
1749
+ }
1750
+ const isLastPart = i2 === content.length - 1;
1751
+ const cacheControl = (_d = validator.getCacheControl(part.providerOptions, {
1752
+ type: "tool result part",
1753
+ canCache: true
1754
+ })) != null ? _d : isLastPart ? validator.getCacheControl(message.providerOptions, {
1755
+ type: "tool result message",
1756
+ canCache: true
1757
+ }) : void 0;
1758
+ const output = part.output;
1759
+ let contentValue;
1760
+ switch (output.type) {
1761
+ case "content":
1762
+ contentValue = output.value.map((contentPart) => {
1763
+ var _a2;
1764
+ switch (contentPart.type) {
1765
+ case "text":
1766
+ return {
1767
+ type: "text",
1768
+ text: contentPart.text
1769
+ };
1770
+ case "image-data": {
1771
+ return {
1772
+ type: "image",
1773
+ source: {
1774
+ type: "base64",
1775
+ media_type: contentPart.mediaType,
1776
+ data: contentPart.data
1777
+ }
1778
+ };
1779
+ }
1780
+ case "image-url": {
1781
+ return {
1782
+ type: "image",
1783
+ source: {
1784
+ type: "url",
1785
+ url: contentPart.url
1786
+ }
1787
+ };
1788
+ }
1789
+ case "file-url": {
1790
+ return {
1791
+ type: "document",
1792
+ source: {
1793
+ type: "url",
1794
+ url: contentPart.url
1795
+ }
1796
+ };
1797
+ }
1798
+ case "file-data": {
1799
+ if (contentPart.mediaType === "application/pdf") {
1800
+ betas.add("pdfs-2024-09-25");
1801
+ return {
1802
+ type: "document",
1803
+ source: {
1804
+ type: "base64",
1805
+ media_type: contentPart.mediaType,
1806
+ data: contentPart.data
1807
+ }
1808
+ };
1809
+ }
1810
+ warnings.push({
1811
+ type: "other",
1812
+ message: `unsupported tool content part type: ${contentPart.type} with media type: ${contentPart.mediaType}`
1813
+ });
1814
+ return void 0;
1815
+ }
1816
+ case "custom": {
1817
+ const anthropicOptions = (_a2 = contentPart.providerOptions) == null ? void 0 : _a2.anthropic;
1818
+ if ((anthropicOptions == null ? void 0 : anthropicOptions.type) === "tool-reference") {
1819
+ return {
1820
+ type: "tool_reference",
1821
+ tool_name: anthropicOptions.toolName
1822
+ };
1823
+ }
1824
+ warnings.push({
1825
+ type: "other",
1826
+ message: `unsupported custom tool content part`
1827
+ });
1828
+ return void 0;
1829
+ }
1830
+ default: {
1831
+ warnings.push({
1832
+ type: "other",
1833
+ message: `unsupported tool content part type: ${contentPart.type}`
1834
+ });
1835
+ return void 0;
1836
+ }
1837
+ }
1838
+ }).filter(isNonNullable);
1839
+ break;
1840
+ case "text":
1841
+ case "error-text":
1842
+ contentValue = output.value;
1843
+ break;
1844
+ case "execution-denied":
1845
+ contentValue = (_e = output.reason) != null ? _e : "Tool execution denied.";
1846
+ break;
1847
+ case "json":
1848
+ case "error-json":
1849
+ default:
1850
+ contentValue = JSON.stringify(output.value);
1851
+ break;
1852
+ }
1853
+ anthropicContent.push({
1854
+ type: "tool_result",
1855
+ tool_use_id: part.toolCallId,
1856
+ content: contentValue,
1857
+ is_error: output.type === "error-text" || output.type === "error-json" ? true : void 0,
1858
+ cache_control: cacheControl
1859
+ });
1860
+ }
1861
+ break;
1862
+ }
1863
+ default: {
1864
+ const _exhaustiveCheck = role;
1865
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
1866
+ }
1867
+ }
1868
+ }
1869
+ messages.push({ role: "user", content: anthropicContent });
1870
+ break;
1871
+ }
1872
+ case "assistant": {
1873
+ const anthropicContent = [];
1874
+ const mcpToolUseIds = /* @__PURE__ */ new Set();
1875
+ for (let j = 0; j < block.messages.length; j++) {
1876
+ const message = block.messages[j];
1877
+ const isLastMessage = j === block.messages.length - 1;
1878
+ const { content } = message;
1879
+ for (let k = 0; k < content.length; k++) {
1880
+ const part = content[k];
1881
+ const isLastContentPart = k === content.length - 1;
1882
+ const cacheControl = (_f = validator.getCacheControl(part.providerOptions, {
1883
+ type: "assistant message part",
1884
+ canCache: true
1885
+ })) != null ? _f : isLastContentPart ? validator.getCacheControl(message.providerOptions, {
1886
+ type: "assistant message",
1887
+ canCache: true
1888
+ }) : void 0;
1889
+ switch (part.type) {
1890
+ case "text": {
1891
+ const textMetadata = (_g = part.providerOptions) == null ? void 0 : _g.anthropic;
1892
+ if ((textMetadata == null ? void 0 : textMetadata.type) === "compaction") {
1893
+ anthropicContent.push({
1894
+ type: "compaction",
1895
+ content: part.text,
1896
+ cache_control: cacheControl
1897
+ });
1898
+ } else {
1899
+ anthropicContent.push({
1900
+ type: "text",
1901
+ text: (
1902
+ // trim the last text part if it's the last message in the block
1903
+ // because Anthropic does not allow trailing whitespace
1904
+ // in pre-filled assistant responses
1905
+ isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text
1906
+ ),
1907
+ cache_control: cacheControl
1908
+ });
1909
+ }
1910
+ break;
1911
+ }
1912
+ case "reasoning": {
1913
+ if (sendReasoning) {
1914
+ const reasoningMetadata = await parseProviderOptions({
1915
+ provider: "anthropic",
1916
+ providerOptions: part.providerOptions,
1917
+ schema: anthropicReasoningMetadataSchema
1918
+ });
1919
+ if (reasoningMetadata != null) {
1920
+ if (reasoningMetadata.signature != null) {
1921
+ validator.getCacheControl(part.providerOptions, {
1922
+ type: "thinking block",
1923
+ canCache: false
1924
+ });
1925
+ anthropicContent.push({
1926
+ type: "thinking",
1927
+ thinking: part.text,
1928
+ signature: reasoningMetadata.signature
1929
+ });
1930
+ } else if (reasoningMetadata.redactedData != null) {
1931
+ validator.getCacheControl(part.providerOptions, {
1932
+ type: "redacted thinking block",
1933
+ canCache: false
1934
+ });
1935
+ anthropicContent.push({
1936
+ type: "redacted_thinking",
1937
+ data: reasoningMetadata.redactedData
1938
+ });
1939
+ } else {
1940
+ warnings.push({
1941
+ type: "other",
1942
+ message: "unsupported reasoning metadata"
1943
+ });
1944
+ }
1945
+ } else {
1946
+ warnings.push({
1947
+ type: "other",
1948
+ message: "unsupported reasoning metadata"
1949
+ });
1950
+ }
1951
+ } else {
1952
+ warnings.push({
1953
+ type: "other",
1954
+ message: "sending reasoning content is disabled for this model"
1955
+ });
1956
+ }
1957
+ break;
1958
+ }
1959
+ case "tool-call": {
1960
+ if (part.providerExecuted) {
1961
+ const providerToolName = toolNameMapping.toProviderToolName(
1962
+ part.toolName
1963
+ );
1964
+ const isMcpToolUse = ((_i = (_h = part.providerOptions) == null ? void 0 : _h.anthropic) == null ? void 0 : _i.type) === "mcp-tool-use";
1965
+ if (isMcpToolUse) {
1966
+ mcpToolUseIds.add(part.toolCallId);
1967
+ const serverName = (_k = (_j = part.providerOptions) == null ? void 0 : _j.anthropic) == null ? void 0 : _k.serverName;
1968
+ if (serverName == null || typeof serverName !== "string") {
1969
+ warnings.push({
1970
+ type: "other",
1971
+ message: "mcp tool use server name is required and must be a string"
1972
+ });
1973
+ break;
1974
+ }
1975
+ anthropicContent.push({
1976
+ type: "mcp_tool_use",
1977
+ id: part.toolCallId,
1978
+ name: part.toolName,
1979
+ input: part.input,
1980
+ server_name: serverName,
1981
+ cache_control: cacheControl
1982
+ });
1983
+ } else if (
1984
+ // code execution 20250825:
1985
+ providerToolName === "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")
1986
+ ) {
1987
+ anthropicContent.push({
1988
+ type: "server_tool_use",
1989
+ id: part.toolCallId,
1990
+ name: part.input.type,
1991
+ // map back to subtool name
1992
+ input: part.input,
1993
+ cache_control: cacheControl
1994
+ });
1995
+ } else if (
1996
+ // code execution 20250825 programmatic tool calling:
1997
+ // Strip the fake 'programmatic-tool-call' type before sending to Anthropic
1998
+ providerToolName === "code_execution" && part.input != null && typeof part.input === "object" && "type" in part.input && part.input.type === "programmatic-tool-call"
1999
+ ) {
2000
+ const { type: _, ...inputWithoutType } = part.input;
2001
+ anthropicContent.push({
2002
+ type: "server_tool_use",
2003
+ id: part.toolCallId,
2004
+ name: "code_execution",
2005
+ input: inputWithoutType,
2006
+ cache_control: cacheControl
2007
+ });
2008
+ } else {
2009
+ if (providerToolName === "code_execution" || // code execution 20250522
2010
+ providerToolName === "web_fetch" || providerToolName === "web_search") {
2011
+ anthropicContent.push({
2012
+ type: "server_tool_use",
2013
+ id: part.toolCallId,
2014
+ name: providerToolName,
2015
+ input: part.input,
2016
+ cache_control: cacheControl
2017
+ });
2018
+ } else if (providerToolName === "tool_search_tool_regex" || providerToolName === "tool_search_tool_bm25") {
2019
+ anthropicContent.push({
2020
+ type: "server_tool_use",
2021
+ id: part.toolCallId,
2022
+ name: providerToolName,
2023
+ input: part.input,
2024
+ cache_control: cacheControl
2025
+ });
2026
+ } else {
2027
+ warnings.push({
2028
+ type: "other",
2029
+ message: `provider executed tool call for tool ${part.toolName} is not supported`
2030
+ });
2031
+ }
2032
+ }
2033
+ break;
2034
+ }
2035
+ const callerOptions = (_l = part.providerOptions) == null ? void 0 : _l.anthropic;
2036
+ const caller = (callerOptions == null ? void 0 : callerOptions.caller) ? callerOptions.caller.type === "code_execution_20250825" && callerOptions.caller.toolId ? {
2037
+ type: "code_execution_20250825",
2038
+ tool_id: callerOptions.caller.toolId
2039
+ } : callerOptions.caller.type === "direct" ? { type: "direct" } : void 0 : void 0;
2040
+ anthropicContent.push({
2041
+ type: "tool_use",
2042
+ id: part.toolCallId,
2043
+ name: part.toolName,
2044
+ input: part.input,
2045
+ ...caller && { caller },
2046
+ cache_control: cacheControl
2047
+ });
2048
+ break;
2049
+ }
2050
+ case "tool-result": {
2051
+ const providerToolName = toolNameMapping.toProviderToolName(
2052
+ part.toolName
2053
+ );
2054
+ if (mcpToolUseIds.has(part.toolCallId)) {
2055
+ const output = part.output;
2056
+ if (output.type !== "json" && output.type !== "error-json") {
2057
+ warnings.push({
2058
+ type: "other",
2059
+ message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
2060
+ });
2061
+ break;
2062
+ }
2063
+ anthropicContent.push({
2064
+ type: "mcp_tool_result",
2065
+ tool_use_id: part.toolCallId,
2066
+ is_error: output.type === "error-json",
2067
+ content: output.value,
2068
+ cache_control: cacheControl
2069
+ });
2070
+ } else if (providerToolName === "code_execution") {
2071
+ const output = part.output;
2072
+ if (output.type === "error-text" || output.type === "error-json") {
2073
+ let errorInfo = {};
2074
+ try {
2075
+ if (typeof output.value === "string") {
2076
+ errorInfo = JSON.parse(output.value);
2077
+ } else if (typeof output.value === "object" && output.value !== null) {
2078
+ errorInfo = output.value;
2079
+ }
2080
+ } catch (e) {
2081
+ }
2082
+ if (errorInfo.type === "code_execution_tool_result_error") {
2083
+ anthropicContent.push({
2084
+ type: "code_execution_tool_result",
2085
+ tool_use_id: part.toolCallId,
2086
+ content: {
2087
+ type: "code_execution_tool_result_error",
2088
+ error_code: (_m = errorInfo.errorCode) != null ? _m : "unknown"
2089
+ },
2090
+ cache_control: cacheControl
2091
+ });
2092
+ } else {
2093
+ anthropicContent.push({
2094
+ type: "bash_code_execution_tool_result",
2095
+ tool_use_id: part.toolCallId,
2096
+ cache_control: cacheControl,
2097
+ content: {
2098
+ type: "bash_code_execution_tool_result_error",
2099
+ error_code: (_n = errorInfo.errorCode) != null ? _n : "unknown"
2100
+ }
2101
+ });
2102
+ }
2103
+ break;
2104
+ }
2105
+ if (output.type !== "json") {
2106
+ warnings.push({
2107
+ type: "other",
2108
+ message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
2109
+ });
2110
+ break;
2111
+ }
2112
+ if (output.value == null || typeof output.value !== "object" || !("type" in output.value) || typeof output.value.type !== "string") {
2113
+ warnings.push({
2114
+ type: "other",
2115
+ message: `provider executed tool result output value is not a valid code execution result for tool ${part.toolName}`
2116
+ });
2117
+ break;
2118
+ }
2119
+ if (output.value.type === "code_execution_result") {
2120
+ const codeExecutionOutput = await validateTypes({
2121
+ value: output.value,
2122
+ schema: codeExecution_20250522OutputSchema
2123
+ });
2124
+ anthropicContent.push({
2125
+ type: "code_execution_tool_result",
2126
+ tool_use_id: part.toolCallId,
2127
+ content: {
2128
+ type: codeExecutionOutput.type,
2129
+ stdout: codeExecutionOutput.stdout,
2130
+ stderr: codeExecutionOutput.stderr,
2131
+ return_code: codeExecutionOutput.return_code,
2132
+ content: (_o = codeExecutionOutput.content) != null ? _o : []
2133
+ },
2134
+ cache_control: cacheControl
2135
+ });
2136
+ } else {
2137
+ const codeExecutionOutput = await validateTypes({
2138
+ value: output.value,
2139
+ schema: codeExecution_20250825OutputSchema
2140
+ });
2141
+ if (codeExecutionOutput.type === "code_execution_result") {
2142
+ anthropicContent.push({
2143
+ type: "code_execution_tool_result",
2144
+ tool_use_id: part.toolCallId,
2145
+ content: {
2146
+ type: codeExecutionOutput.type,
2147
+ stdout: codeExecutionOutput.stdout,
2148
+ stderr: codeExecutionOutput.stderr,
2149
+ return_code: codeExecutionOutput.return_code,
2150
+ content: (_p = codeExecutionOutput.content) != null ? _p : []
2151
+ },
2152
+ cache_control: cacheControl
2153
+ });
2154
+ } else if (codeExecutionOutput.type === "bash_code_execution_result" || codeExecutionOutput.type === "bash_code_execution_tool_result_error") {
2155
+ anthropicContent.push({
2156
+ type: "bash_code_execution_tool_result",
2157
+ tool_use_id: part.toolCallId,
2158
+ cache_control: cacheControl,
2159
+ content: codeExecutionOutput
2160
+ });
2161
+ } else {
2162
+ anthropicContent.push({
2163
+ type: "text_editor_code_execution_tool_result",
2164
+ tool_use_id: part.toolCallId,
2165
+ cache_control: cacheControl,
2166
+ content: codeExecutionOutput
2167
+ });
2168
+ }
2169
+ }
2170
+ break;
2171
+ }
2172
+ if (providerToolName === "web_fetch") {
2173
+ const output = part.output;
2174
+ if (output.type === "error-json") {
2175
+ let errorValue = {};
2176
+ try {
2177
+ if (typeof output.value === "string") {
2178
+ errorValue = JSON.parse(output.value);
2179
+ } else if (typeof output.value === "object" && output.value !== null) {
2180
+ errorValue = output.value;
2181
+ }
2182
+ } catch (e) {
2183
+ const extractedErrorCode = (_q = output.value) == null ? void 0 : _q.errorCode;
2184
+ errorValue = {
2185
+ errorCode: typeof extractedErrorCode === "string" ? extractedErrorCode : "unknown"
2186
+ };
2187
+ }
2188
+ anthropicContent.push({
2189
+ type: "web_fetch_tool_result",
2190
+ tool_use_id: part.toolCallId,
2191
+ content: {
2192
+ type: "web_fetch_tool_result_error",
2193
+ error_code: (_r = errorValue.errorCode) != null ? _r : "unknown"
2194
+ },
2195
+ cache_control: cacheControl
2196
+ });
2197
+ break;
2198
+ }
2199
+ if (output.type !== "json") {
2200
+ warnings.push({
2201
+ type: "other",
2202
+ message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
2203
+ });
2204
+ break;
2205
+ }
2206
+ const webFetchOutput = await validateTypes({
2207
+ value: output.value,
2208
+ schema: webFetch_20250910OutputSchema
2209
+ });
2210
+ anthropicContent.push({
2211
+ type: "web_fetch_tool_result",
2212
+ tool_use_id: part.toolCallId,
2213
+ content: {
2214
+ type: "web_fetch_result",
2215
+ url: webFetchOutput.url,
2216
+ retrieved_at: webFetchOutput.retrievedAt,
2217
+ content: {
2218
+ type: "document",
2219
+ title: webFetchOutput.content.title,
2220
+ citations: webFetchOutput.content.citations,
2221
+ source: {
2222
+ type: webFetchOutput.content.source.type,
2223
+ media_type: webFetchOutput.content.source.mediaType,
2224
+ data: webFetchOutput.content.source.data
2225
+ }
2226
+ }
2227
+ },
2228
+ cache_control: cacheControl
2229
+ });
2230
+ break;
2231
+ }
2232
+ if (providerToolName === "web_search") {
2233
+ const output = part.output;
2234
+ if (output.type !== "json") {
2235
+ warnings.push({
2236
+ type: "other",
2237
+ message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
2238
+ });
2239
+ break;
2240
+ }
2241
+ const webSearchOutput = await validateTypes({
2242
+ value: output.value,
2243
+ schema: webSearch_20250305OutputSchema
2244
+ });
2245
+ anthropicContent.push({
2246
+ type: "web_search_tool_result",
2247
+ tool_use_id: part.toolCallId,
2248
+ content: webSearchOutput.map((result) => ({
2249
+ url: result.url,
2250
+ title: result.title,
2251
+ page_age: result.pageAge,
2252
+ encrypted_content: result.encryptedContent,
2253
+ type: result.type
2254
+ })),
2255
+ cache_control: cacheControl
2256
+ });
2257
+ break;
2258
+ }
2259
+ if (providerToolName === "tool_search_tool_regex" || providerToolName === "tool_search_tool_bm25") {
2260
+ const output = part.output;
2261
+ if (output.type !== "json") {
2262
+ warnings.push({
2263
+ type: "other",
2264
+ message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
2265
+ });
2266
+ break;
2267
+ }
2268
+ const toolSearchOutput = await validateTypes({
2269
+ value: output.value,
2270
+ schema: toolSearchRegex_20251119OutputSchema
2271
+ });
2272
+ const toolReferences = toolSearchOutput.map((ref) => ({
2273
+ type: "tool_reference",
2274
+ tool_name: ref.toolName
2275
+ }));
2276
+ anthropicContent.push({
2277
+ type: "tool_search_tool_result",
2278
+ tool_use_id: part.toolCallId,
2279
+ content: {
2280
+ type: "tool_search_tool_search_result",
2281
+ tool_references: toolReferences
2282
+ },
2283
+ cache_control: cacheControl
2284
+ });
2285
+ break;
2286
+ }
2287
+ warnings.push({
2288
+ type: "other",
2289
+ message: `provider executed tool result for tool ${part.toolName} is not supported`
2290
+ });
2291
+ break;
2292
+ }
2293
+ }
2294
+ }
2295
+ }
2296
+ messages.push({ role: "assistant", content: anthropicContent });
2297
+ break;
2298
+ }
2299
+ default: {
2300
+ const _exhaustiveCheck = type;
2301
+ throw new Error(`content type: ${_exhaustiveCheck}`);
2302
+ }
2303
+ }
2304
+ }
2305
+ return {
2306
+ prompt: { system, messages },
2307
+ betas
2308
+ };
2309
+ }
2310
+ function groupIntoBlocks(prompt) {
2311
+ const blocks = [];
2312
+ let currentBlock = void 0;
2313
+ for (const message of prompt) {
2314
+ const { role } = message;
2315
+ switch (role) {
2316
+ case "system": {
2317
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "system") {
2318
+ currentBlock = { type: "system", messages: [] };
2319
+ blocks.push(currentBlock);
2320
+ }
2321
+ currentBlock.messages.push(message);
2322
+ break;
2323
+ }
2324
+ case "assistant": {
2325
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "assistant") {
2326
+ currentBlock = { type: "assistant", messages: [] };
2327
+ blocks.push(currentBlock);
2328
+ }
2329
+ currentBlock.messages.push(message);
2330
+ break;
2331
+ }
2332
+ case "user": {
2333
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
2334
+ currentBlock = { type: "user", messages: [] };
2335
+ blocks.push(currentBlock);
2336
+ }
2337
+ currentBlock.messages.push(message);
2338
+ break;
2339
+ }
2340
+ case "tool": {
2341
+ if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
2342
+ currentBlock = { type: "user", messages: [] };
2343
+ blocks.push(currentBlock);
2344
+ }
2345
+ currentBlock.messages.push(message);
2346
+ break;
2347
+ }
2348
+ default: {
2349
+ const _exhaustiveCheck = role;
2350
+ throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
2351
+ }
2352
+ }
2353
+ }
2354
+ return blocks;
2355
+ }
2356
+ function mapAnthropicStopReason({
2357
+ finishReason,
2358
+ isJsonResponseFromTool
2359
+ }) {
2360
+ switch (finishReason) {
2361
+ case "pause_turn":
2362
+ case "end_turn":
2363
+ case "stop_sequence":
2364
+ return "stop";
2365
+ case "refusal":
2366
+ return "content-filter";
2367
+ case "tool_use":
2368
+ return isJsonResponseFromTool ? "stop" : "tool-calls";
2369
+ case "max_tokens":
2370
+ case "model_context_window_exceeded":
2371
+ return "length";
2372
+ case "compaction":
2373
+ return "other";
2374
+ default:
2375
+ return "other";
2376
+ }
2377
+ }
2378
+ function createCitationSource(citation, citationDocuments, generateId3) {
2379
+ var _a;
2380
+ if (citation.type === "web_search_result_location") {
2381
+ return {
2382
+ type: "source",
2383
+ sourceType: "url",
2384
+ id: generateId3(),
2385
+ url: citation.url,
2386
+ title: citation.title,
2387
+ providerMetadata: {
2388
+ anthropic: {
2389
+ citedText: citation.cited_text,
2390
+ encryptedIndex: citation.encrypted_index
2391
+ }
2392
+ }
2393
+ };
2394
+ }
2395
+ if (citation.type !== "page_location" && citation.type !== "char_location") {
2396
+ return;
2397
+ }
2398
+ const documentInfo = citationDocuments[citation.document_index];
2399
+ if (!documentInfo) {
2400
+ return;
2401
+ }
2402
+ return {
2403
+ type: "source",
2404
+ sourceType: "document",
2405
+ id: generateId3(),
2406
+ mediaType: documentInfo.mediaType,
2407
+ title: (_a = citation.document_title) != null ? _a : documentInfo.title,
2408
+ filename: documentInfo.filename,
2409
+ providerMetadata: {
2410
+ anthropic: citation.type === "page_location" ? {
2411
+ citedText: citation.cited_text,
2412
+ startPageNumber: citation.start_page_number,
2413
+ endPageNumber: citation.end_page_number
2414
+ } : {
2415
+ citedText: citation.cited_text,
2416
+ startCharIndex: citation.start_char_index,
2417
+ endCharIndex: citation.end_char_index
2418
+ }
2419
+ }
2420
+ };
2421
+ }
2422
+ var AnthropicMessagesLanguageModel = class {
2423
+ constructor(modelId, config) {
2424
+ this.specificationVersion = "v3";
2425
+ var _a;
2426
+ this.modelId = modelId;
2427
+ this.config = config;
2428
+ this.generateId = (_a = config.generateId) != null ? _a : generateId;
2429
+ }
2430
+ supportsUrl(url) {
2431
+ return url.protocol === "https:";
2432
+ }
2433
+ get provider() {
2434
+ return this.config.provider;
2435
+ }
2436
+ /**
2437
+ * Extracts the dynamic provider name from the config.provider string.
2438
+ * e.g., 'my-custom-anthropic.messages' -> 'my-custom-anthropic'
2439
+ */
2440
+ get providerOptionsName() {
2441
+ const provider = this.config.provider;
2442
+ const dotIndex = provider.indexOf(".");
2443
+ return dotIndex === -1 ? provider : provider.substring(0, dotIndex);
2444
+ }
2445
+ get supportedUrls() {
2446
+ var _a, _b, _c;
2447
+ return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
2448
+ }
2449
+ async getArgs({
2450
+ userSuppliedBetas,
2451
+ prompt,
2452
+ maxOutputTokens,
2453
+ temperature,
2454
+ topP,
2455
+ topK,
2456
+ frequencyPenalty,
2457
+ presencePenalty,
2458
+ stopSequences,
2459
+ responseFormat,
2460
+ seed,
2461
+ tools,
2462
+ toolChoice,
2463
+ providerOptions,
2464
+ stream
2465
+ }) {
2466
+ var _a, _b, _c, _d, _e, _f;
2467
+ const warnings = [];
2468
+ if (frequencyPenalty != null) {
2469
+ warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
2470
+ }
2471
+ if (presencePenalty != null) {
2472
+ warnings.push({ type: "unsupported", feature: "presencePenalty" });
2473
+ }
2474
+ if (seed != null) {
2475
+ warnings.push({ type: "unsupported", feature: "seed" });
2476
+ }
2477
+ if (temperature != null && temperature > 1) {
2478
+ warnings.push({
2479
+ type: "unsupported",
2480
+ feature: "temperature",
2481
+ details: `${temperature} exceeds anthropic maximum of 1.0. clamped to 1.0`
2482
+ });
2483
+ temperature = 1;
2484
+ } else if (temperature != null && temperature < 0) {
2485
+ warnings.push({
2486
+ type: "unsupported",
2487
+ feature: "temperature",
2488
+ details: `${temperature} is below anthropic minimum of 0. clamped to 0`
2489
+ });
2490
+ temperature = 0;
2491
+ }
2492
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
2493
+ if (responseFormat.schema == null) {
2494
+ warnings.push({
2495
+ type: "unsupported",
2496
+ feature: "responseFormat",
2497
+ details: "JSON response format requires a schema. The response format is ignored."
2498
+ });
2499
+ }
2500
+ }
2501
+ const providerOptionsName = this.providerOptionsName;
2502
+ const canonicalOptions = await parseProviderOptions({
2503
+ provider: "anthropic",
2504
+ providerOptions,
2505
+ schema: anthropicLanguageModelOptions
2506
+ });
2507
+ const customProviderOptions = providerOptionsName !== "anthropic" ? await parseProviderOptions({
2508
+ provider: providerOptionsName,
2509
+ providerOptions,
2510
+ schema: anthropicLanguageModelOptions
2511
+ }) : null;
2512
+ const usedCustomProviderKey = customProviderOptions != null;
2513
+ const anthropicOptions = Object.assign(
2514
+ {},
2515
+ canonicalOptions != null ? canonicalOptions : {},
2516
+ customProviderOptions != null ? customProviderOptions : {}
2517
+ );
2518
+ const {
2519
+ maxOutputTokens: maxOutputTokensForModel,
2520
+ supportsStructuredOutput: modelSupportsStructuredOutput,
2521
+ isKnownModel
2522
+ } = getModelCapabilities(this.modelId);
2523
+ const supportsStructuredOutput = ((_a = this.config.supportsNativeStructuredOutput) != null ? _a : true) && modelSupportsStructuredOutput;
2524
+ const structureOutputMode = (_b = anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _b : "auto";
2525
+ const useStructuredOutput = structureOutputMode === "outputFormat" || structureOutputMode === "auto" && supportsStructuredOutput;
2526
+ const jsonResponseTool = (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !useStructuredOutput ? {
2527
+ type: "function",
2528
+ name: "json",
2529
+ description: "Respond with a JSON object.",
2530
+ inputSchema: responseFormat.schema
2531
+ } : void 0;
2532
+ const contextManagement = anthropicOptions == null ? void 0 : anthropicOptions.contextManagement;
2533
+ const cacheControlValidator = new CacheControlValidator();
2534
+ const toolNameMapping = createToolNameMapping({
2535
+ tools,
2536
+ providerToolNames: {
2537
+ "anthropic.code_execution_20250522": "code_execution",
2538
+ "anthropic.code_execution_20250825": "code_execution",
2539
+ "anthropic.computer_20241022": "computer",
2540
+ "anthropic.computer_20250124": "computer",
2541
+ "anthropic.text_editor_20241022": "str_replace_editor",
2542
+ "anthropic.text_editor_20250124": "str_replace_editor",
2543
+ "anthropic.text_editor_20250429": "str_replace_based_edit_tool",
2544
+ "anthropic.text_editor_20250728": "str_replace_based_edit_tool",
2545
+ "anthropic.bash_20241022": "bash",
2546
+ "anthropic.bash_20250124": "bash",
2547
+ "anthropic.memory_20250818": "memory",
2548
+ "anthropic.web_search_20250305": "web_search",
2549
+ "anthropic.web_fetch_20250910": "web_fetch",
2550
+ "anthropic.tool_search_regex_20251119": "tool_search_tool_regex",
2551
+ "anthropic.tool_search_bm25_20251119": "tool_search_tool_bm25"
2552
+ }
2553
+ });
2554
+ const { prompt: messagesPrompt, betas } = await convertToAnthropicMessagesPrompt({
2555
+ prompt,
2556
+ sendReasoning: (_c = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _c : true,
2557
+ warnings,
2558
+ cacheControlValidator,
2559
+ toolNameMapping
2560
+ });
2561
+ const thinkingType = (_d = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _d.type;
2562
+ const isThinking = thinkingType === "enabled" || thinkingType === "adaptive";
2563
+ let thinkingBudget = thinkingType === "enabled" ? (_e = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _e.budgetTokens : void 0;
2564
+ const maxTokens = maxOutputTokens != null ? maxOutputTokens : maxOutputTokensForModel;
2565
+ const baseArgs = {
2566
+ // model id:
2567
+ model: this.modelId,
2568
+ // standardized settings:
2569
+ max_tokens: maxTokens,
2570
+ temperature,
2571
+ top_k: topK,
2572
+ top_p: topP,
2573
+ stop_sequences: stopSequences,
2574
+ // provider specific settings:
2575
+ ...isThinking && {
2576
+ thinking: {
2577
+ type: thinkingType,
2578
+ ...thinkingBudget != null && { budget_tokens: thinkingBudget }
2579
+ }
2580
+ },
2581
+ ...(anthropicOptions == null ? void 0 : anthropicOptions.effort) && {
2582
+ output_config: { effort: anthropicOptions.effort }
2583
+ },
2584
+ ...(anthropicOptions == null ? void 0 : anthropicOptions.speed) && {
2585
+ speed: anthropicOptions.speed
2586
+ },
2587
+ // structured output:
2588
+ ...useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && {
2589
+ output_format: {
2590
+ type: "json_schema",
2591
+ schema: responseFormat.schema
2592
+ }
2593
+ },
2594
+ // mcp servers:
2595
+ ...(anthropicOptions == null ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0 && {
2596
+ mcp_servers: anthropicOptions.mcpServers.map((server) => ({
2597
+ type: server.type,
2598
+ name: server.name,
2599
+ url: server.url,
2600
+ authorization_token: server.authorizationToken,
2601
+ tool_configuration: server.toolConfiguration ? {
2602
+ allowed_tools: server.toolConfiguration.allowedTools,
2603
+ enabled: server.toolConfiguration.enabled
2604
+ } : void 0
2605
+ }))
2606
+ },
2607
+ // container: For programmatic tool calling (just an ID string) or agent skills (object with id and skills)
2608
+ ...(anthropicOptions == null ? void 0 : anthropicOptions.container) && {
2609
+ container: anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0 ? (
2610
+ // Object format when skills are provided (agent skills feature)
2611
+ {
2612
+ id: anthropicOptions.container.id,
2613
+ skills: anthropicOptions.container.skills.map((skill) => ({
2614
+ type: skill.type,
2615
+ skill_id: skill.skillId,
2616
+ version: skill.version
2617
+ }))
2618
+ }
2619
+ ) : (
2620
+ // String format for container ID only (programmatic tool calling)
2621
+ anthropicOptions.container.id
2622
+ )
2623
+ },
2624
+ // prompt:
2625
+ system: messagesPrompt.system,
2626
+ messages: messagesPrompt.messages,
2627
+ ...contextManagement && {
2628
+ context_management: {
2629
+ edits: contextManagement.edits.map((edit) => {
2630
+ const strategy = edit.type;
2631
+ switch (strategy) {
2632
+ case "clear_tool_uses_20250919":
2633
+ return {
2634
+ type: edit.type,
2635
+ ...edit.trigger !== void 0 && {
2636
+ trigger: edit.trigger
2637
+ },
2638
+ ...edit.keep !== void 0 && { keep: edit.keep },
2639
+ ...edit.clearAtLeast !== void 0 && {
2640
+ clear_at_least: edit.clearAtLeast
2641
+ },
2642
+ ...edit.clearToolInputs !== void 0 && {
2643
+ clear_tool_inputs: edit.clearToolInputs
2644
+ },
2645
+ ...edit.excludeTools !== void 0 && {
2646
+ exclude_tools: edit.excludeTools
2647
+ }
2648
+ };
2649
+ case "clear_thinking_20251015":
2650
+ return {
2651
+ type: edit.type,
2652
+ ...edit.keep !== void 0 && { keep: edit.keep }
2653
+ };
2654
+ case "compact_20260112":
2655
+ return {
2656
+ type: edit.type,
2657
+ ...edit.trigger !== void 0 && {
2658
+ trigger: edit.trigger
2659
+ },
2660
+ ...edit.pauseAfterCompaction !== void 0 && {
2661
+ pause_after_compaction: edit.pauseAfterCompaction
2662
+ },
2663
+ ...edit.instructions !== void 0 && {
2664
+ instructions: edit.instructions
2665
+ }
2666
+ };
2667
+ default:
2668
+ warnings.push({
2669
+ type: "other",
2670
+ message: `Unknown context management strategy: ${strategy}`
2671
+ });
2672
+ return void 0;
2673
+ }
2674
+ }).filter((edit) => edit !== void 0)
2675
+ }
2676
+ }
2677
+ };
2678
+ if (isThinking) {
2679
+ if (thinkingType === "enabled" && thinkingBudget == null) {
2680
+ warnings.push({
2681
+ type: "compatibility",
2682
+ feature: "extended thinking",
2683
+ details: "thinking budget is required when thinking is enabled. using default budget of 1024 tokens."
2684
+ });
2685
+ baseArgs.thinking = {
2686
+ type: "enabled",
2687
+ budget_tokens: 1024
2688
+ };
2689
+ thinkingBudget = 1024;
2690
+ }
2691
+ if (baseArgs.temperature != null) {
2692
+ baseArgs.temperature = void 0;
2693
+ warnings.push({
2694
+ type: "unsupported",
2695
+ feature: "temperature",
2696
+ details: "temperature is not supported when thinking is enabled"
2697
+ });
2698
+ }
2699
+ if (topK != null) {
2700
+ baseArgs.top_k = void 0;
2701
+ warnings.push({
2702
+ type: "unsupported",
2703
+ feature: "topK",
2704
+ details: "topK is not supported when thinking is enabled"
2705
+ });
2706
+ }
2707
+ if (topP != null) {
2708
+ baseArgs.top_p = void 0;
2709
+ warnings.push({
2710
+ type: "unsupported",
2711
+ feature: "topP",
2712
+ details: "topP is not supported when thinking is enabled"
2713
+ });
2714
+ }
2715
+ baseArgs.max_tokens = maxTokens + (thinkingBudget != null ? thinkingBudget : 0);
2716
+ } else {
2717
+ if (topP != null && temperature != null) {
2718
+ warnings.push({
2719
+ type: "unsupported",
2720
+ feature: "topP",
2721
+ details: `topP is not supported when temperature is set. topP is ignored.`
2722
+ });
2723
+ baseArgs.top_p = void 0;
2724
+ }
2725
+ }
2726
+ if (isKnownModel && baseArgs.max_tokens > maxOutputTokensForModel) {
2727
+ if (maxOutputTokens != null) {
2728
+ warnings.push({
2729
+ type: "unsupported",
2730
+ feature: "maxOutputTokens",
2731
+ details: `${baseArgs.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${maxOutputTokensForModel} max output tokens. The max output tokens have been limited to ${maxOutputTokensForModel}.`
2732
+ });
2733
+ }
2734
+ baseArgs.max_tokens = maxOutputTokensForModel;
2735
+ }
2736
+ if ((anthropicOptions == null ? void 0 : anthropicOptions.mcpServers) && anthropicOptions.mcpServers.length > 0) {
2737
+ betas.add("mcp-client-2025-04-04");
2738
+ }
2739
+ if (contextManagement) {
2740
+ betas.add("context-management-2025-06-27");
2741
+ if (contextManagement.edits.some((e) => e.type === "compact_20260112")) {
2742
+ betas.add("compact-2026-01-12");
2743
+ }
2744
+ }
2745
+ if ((anthropicOptions == null ? void 0 : anthropicOptions.container) && anthropicOptions.container.skills && anthropicOptions.container.skills.length > 0) {
2746
+ betas.add("code-execution-2025-08-25");
2747
+ betas.add("skills-2025-10-02");
2748
+ betas.add("files-api-2025-04-14");
2749
+ if (!(tools == null ? void 0 : tools.some(
2750
+ (tool) => tool.type === "provider" && tool.id === "anthropic.code_execution_20250825"
2751
+ ))) {
2752
+ warnings.push({
2753
+ type: "other",
2754
+ message: "code execution tool is required when using skills"
2755
+ });
2756
+ }
2757
+ }
2758
+ if (anthropicOptions == null ? void 0 : anthropicOptions.effort) {
2759
+ betas.add("effort-2025-11-24");
2760
+ }
2761
+ if ((anthropicOptions == null ? void 0 : anthropicOptions.speed) === "fast") {
2762
+ betas.add("fast-mode-2026-02-01");
2763
+ }
2764
+ if (stream && ((_f = anthropicOptions == null ? void 0 : anthropicOptions.toolStreaming) != null ? _f : true)) {
2765
+ betas.add("fine-grained-tool-streaming-2025-05-14");
2766
+ }
2767
+ const usingNativeOutputFormat = useStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null;
2768
+ if (usingNativeOutputFormat) {
2769
+ betas.add("structured-outputs-2025-11-13");
2770
+ }
2771
+ const {
2772
+ tools: anthropicTools2,
2773
+ toolChoice: anthropicToolChoice,
2774
+ toolWarnings,
2775
+ betas: toolsBetas
2776
+ } = await prepareTools(
2777
+ jsonResponseTool != null ? {
2778
+ tools: [...tools != null ? tools : [], jsonResponseTool],
2779
+ toolChoice: { type: "required" },
2780
+ disableParallelToolUse: true,
2781
+ cacheControlValidator,
2782
+ supportsStructuredOutput: false
2783
+ } : {
2784
+ tools: tools != null ? tools : [],
2785
+ toolChoice,
2786
+ disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse,
2787
+ cacheControlValidator,
2788
+ supportsStructuredOutput
2789
+ }
2790
+ );
2791
+ const cacheWarnings = cacheControlValidator.getWarnings();
2792
+ return {
2793
+ args: {
2794
+ ...baseArgs,
2795
+ tools: anthropicTools2,
2796
+ tool_choice: anthropicToolChoice,
2797
+ stream: stream === true ? true : void 0
2798
+ // do not send when not streaming
2799
+ },
2800
+ warnings: [...warnings, ...toolWarnings, ...cacheWarnings],
2801
+ betas: /* @__PURE__ */ new Set([...betas, ...toolsBetas, ...userSuppliedBetas]),
2802
+ usesJsonResponseTool: jsonResponseTool != null,
2803
+ toolNameMapping,
2804
+ providerOptionsName,
2805
+ usedCustomProviderKey
2806
+ };
2807
+ }
2808
+ async getHeaders({
2809
+ betas,
2810
+ headers
2811
+ }) {
2812
+ return combineHeaders(
2813
+ await resolve(this.config.headers),
2814
+ headers,
2815
+ betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {}
2816
+ );
2817
+ }
2818
+ async getBetasFromHeaders(requestHeaders) {
2819
+ var _a, _b;
2820
+ const configHeaders = await resolve(this.config.headers);
2821
+ const configBetaHeader = (_a = configHeaders["anthropic-beta"]) != null ? _a : "";
2822
+ const requestBetaHeader = (_b = requestHeaders == null ? void 0 : requestHeaders["anthropic-beta"]) != null ? _b : "";
2823
+ return new Set(
2824
+ [
2825
+ ...configBetaHeader.toLowerCase().split(","),
2826
+ ...requestBetaHeader.toLowerCase().split(",")
2827
+ ].map((beta) => beta.trim()).filter((beta) => beta !== "")
2828
+ );
2829
+ }
2830
+ buildRequestUrl(isStreaming) {
2831
+ var _a, _b, _c;
2832
+ return (_c = (_b = (_a = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;
2833
+ }
2834
+ transformRequestBody(args) {
2835
+ var _a, _b, _c;
2836
+ return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;
2837
+ }
2838
+ extractCitationDocuments(prompt) {
2839
+ const isCitationPart = (part) => {
2840
+ var _a, _b;
2841
+ if (part.type !== "file") {
2842
+ return false;
2843
+ }
2844
+ if (part.mediaType !== "application/pdf" && part.mediaType !== "text/plain") {
2845
+ return false;
2846
+ }
2847
+ const anthropic2 = (_a = part.providerOptions) == null ? void 0 : _a.anthropic;
2848
+ const citationsConfig = anthropic2 == null ? void 0 : anthropic2.citations;
2849
+ return (_b = citationsConfig == null ? void 0 : citationsConfig.enabled) != null ? _b : false;
2850
+ };
2851
+ return prompt.filter((message) => message.role === "user").flatMap((message) => message.content).filter(isCitationPart).map((part) => {
2852
+ var _a;
2853
+ const filePart = part;
2854
+ return {
2855
+ title: (_a = filePart.filename) != null ? _a : "Untitled Document",
2856
+ filename: filePart.filename,
2857
+ mediaType: filePart.mediaType
2858
+ };
2859
+ });
2860
+ }
2861
+ async doGenerate(options) {
2862
+ var _a, _b, _c, _d, _e, _f;
2863
+ const {
2864
+ args,
2865
+ warnings,
2866
+ betas,
2867
+ usesJsonResponseTool,
2868
+ toolNameMapping,
2869
+ providerOptionsName,
2870
+ usedCustomProviderKey
2871
+ } = await this.getArgs({
2872
+ ...options,
2873
+ stream: false,
2874
+ userSuppliedBetas: await this.getBetasFromHeaders(options.headers)
2875
+ });
2876
+ const citationDocuments = [
2877
+ ...this.extractCitationDocuments(options.prompt)
2878
+ ];
2879
+ const {
2880
+ responseHeaders,
2881
+ value: response,
2882
+ rawValue: rawResponse
2883
+ } = await postJsonToApi({
2884
+ url: this.buildRequestUrl(false),
2885
+ headers: await this.getHeaders({ betas, headers: options.headers }),
2886
+ body: this.transformRequestBody(args),
2887
+ failedResponseHandler: anthropicFailedResponseHandler,
2888
+ successfulResponseHandler: createJsonResponseHandler(
2889
+ anthropicMessagesResponseSchema
2890
+ ),
2891
+ abortSignal: options.abortSignal,
2892
+ fetch: this.config.fetch
2893
+ });
2894
+ const content = [];
2895
+ const mcpToolCalls = {};
2896
+ const serverToolCalls = {};
2897
+ let isJsonResponseFromTool = false;
2898
+ for (const part of response.content) {
2899
+ switch (part.type) {
2900
+ case "text": {
2901
+ if (!usesJsonResponseTool) {
2902
+ content.push({ type: "text", text: part.text });
2903
+ if (part.citations) {
2904
+ for (const citation of part.citations) {
2905
+ const source = createCitationSource(
2906
+ citation,
2907
+ citationDocuments,
2908
+ this.generateId
2909
+ );
2910
+ if (source) {
2911
+ content.push(source);
2912
+ }
2913
+ }
2914
+ }
2915
+ }
2916
+ break;
2917
+ }
2918
+ case "thinking": {
2919
+ content.push({
2920
+ type: "reasoning",
2921
+ text: part.thinking,
2922
+ providerMetadata: {
2923
+ anthropic: {
2924
+ signature: part.signature
2925
+ }
2926
+ }
2927
+ });
2928
+ break;
2929
+ }
2930
+ case "redacted_thinking": {
2931
+ content.push({
2932
+ type: "reasoning",
2933
+ text: "",
2934
+ providerMetadata: {
2935
+ anthropic: {
2936
+ redactedData: part.data
2937
+ }
2938
+ }
2939
+ });
2940
+ break;
2941
+ }
2942
+ case "compaction": {
2943
+ content.push({
2944
+ type: "text",
2945
+ text: part.content,
2946
+ providerMetadata: {
2947
+ anthropic: {
2948
+ type: "compaction"
2949
+ }
2950
+ }
2951
+ });
2952
+ break;
2953
+ }
2954
+ case "tool_use": {
2955
+ const isJsonResponseTool = usesJsonResponseTool && part.name === "json";
2956
+ if (isJsonResponseTool) {
2957
+ isJsonResponseFromTool = true;
2958
+ content.push({
2959
+ type: "text",
2960
+ text: JSON.stringify(part.input)
2961
+ });
2962
+ } else {
2963
+ const caller = part.caller;
2964
+ const callerInfo = caller ? {
2965
+ type: caller.type,
2966
+ toolId: "tool_id" in caller ? caller.tool_id : void 0
2967
+ } : void 0;
2968
+ content.push({
2969
+ type: "tool-call",
2970
+ toolCallId: part.id,
2971
+ toolName: part.name,
2972
+ input: JSON.stringify(part.input),
2973
+ ...callerInfo && {
2974
+ providerMetadata: {
2975
+ anthropic: {
2976
+ caller: callerInfo
2977
+ }
2978
+ }
2979
+ }
2980
+ });
2981
+ }
2982
+ break;
2983
+ }
2984
+ case "server_tool_use": {
2985
+ if (part.name === "text_editor_code_execution" || part.name === "bash_code_execution") {
2986
+ content.push({
2987
+ type: "tool-call",
2988
+ toolCallId: part.id,
2989
+ toolName: toolNameMapping.toCustomToolName("code_execution"),
2990
+ input: JSON.stringify({ type: part.name, ...part.input }),
2991
+ providerExecuted: true
2992
+ });
2993
+ } else if (part.name === "web_search" || part.name === "code_execution" || part.name === "web_fetch") {
2994
+ const inputToSerialize = part.name === "code_execution" && part.input != null && typeof part.input === "object" && "code" in part.input && !("type" in part.input) ? { type: "programmatic-tool-call", ...part.input } : part.input;
2995
+ content.push({
2996
+ type: "tool-call",
2997
+ toolCallId: part.id,
2998
+ toolName: toolNameMapping.toCustomToolName(part.name),
2999
+ input: JSON.stringify(inputToSerialize),
3000
+ providerExecuted: true
3001
+ });
3002
+ } else if (part.name === "tool_search_tool_regex" || part.name === "tool_search_tool_bm25") {
3003
+ serverToolCalls[part.id] = part.name;
3004
+ content.push({
3005
+ type: "tool-call",
3006
+ toolCallId: part.id,
3007
+ toolName: toolNameMapping.toCustomToolName(part.name),
3008
+ input: JSON.stringify(part.input),
3009
+ providerExecuted: true
3010
+ });
3011
+ }
3012
+ break;
3013
+ }
3014
+ case "mcp_tool_use": {
3015
+ mcpToolCalls[part.id] = {
3016
+ type: "tool-call",
3017
+ toolCallId: part.id,
3018
+ toolName: part.name,
3019
+ input: JSON.stringify(part.input),
3020
+ providerExecuted: true,
3021
+ dynamic: true,
3022
+ providerMetadata: {
3023
+ anthropic: {
3024
+ type: "mcp-tool-use",
3025
+ serverName: part.server_name
3026
+ }
3027
+ }
3028
+ };
3029
+ content.push(mcpToolCalls[part.id]);
3030
+ break;
3031
+ }
3032
+ case "mcp_tool_result": {
3033
+ content.push({
3034
+ type: "tool-result",
3035
+ toolCallId: part.tool_use_id,
3036
+ toolName: mcpToolCalls[part.tool_use_id].toolName,
3037
+ isError: part.is_error,
3038
+ result: part.content,
3039
+ dynamic: true,
3040
+ providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata
3041
+ });
3042
+ break;
3043
+ }
3044
+ case "web_fetch_tool_result": {
3045
+ if (part.content.type === "web_fetch_result") {
3046
+ citationDocuments.push({
3047
+ title: (_a = part.content.content.title) != null ? _a : part.content.url,
3048
+ mediaType: part.content.content.source.media_type
3049
+ });
3050
+ content.push({
3051
+ type: "tool-result",
3052
+ toolCallId: part.tool_use_id,
3053
+ toolName: toolNameMapping.toCustomToolName("web_fetch"),
3054
+ result: {
3055
+ type: "web_fetch_result",
3056
+ url: part.content.url,
3057
+ retrievedAt: part.content.retrieved_at,
3058
+ content: {
3059
+ type: part.content.content.type,
3060
+ title: part.content.content.title,
3061
+ citations: part.content.content.citations,
3062
+ source: {
3063
+ type: part.content.content.source.type,
3064
+ mediaType: part.content.content.source.media_type,
3065
+ data: part.content.content.source.data
3066
+ }
3067
+ }
3068
+ }
3069
+ });
3070
+ } else if (part.content.type === "web_fetch_tool_result_error") {
3071
+ content.push({
3072
+ type: "tool-result",
3073
+ toolCallId: part.tool_use_id,
3074
+ toolName: toolNameMapping.toCustomToolName("web_fetch"),
3075
+ isError: true,
3076
+ result: {
3077
+ type: "web_fetch_tool_result_error",
3078
+ errorCode: part.content.error_code
3079
+ }
3080
+ });
3081
+ }
3082
+ break;
3083
+ }
3084
+ case "web_search_tool_result": {
3085
+ if (Array.isArray(part.content)) {
3086
+ content.push({
3087
+ type: "tool-result",
3088
+ toolCallId: part.tool_use_id,
3089
+ toolName: toolNameMapping.toCustomToolName("web_search"),
3090
+ result: part.content.map((result) => {
3091
+ var _a2;
3092
+ return {
3093
+ url: result.url,
3094
+ title: result.title,
3095
+ pageAge: (_a2 = result.page_age) != null ? _a2 : null,
3096
+ encryptedContent: result.encrypted_content,
3097
+ type: result.type
3098
+ };
3099
+ })
3100
+ });
3101
+ for (const result of part.content) {
3102
+ content.push({
3103
+ type: "source",
3104
+ sourceType: "url",
3105
+ id: this.generateId(),
3106
+ url: result.url,
3107
+ title: result.title,
3108
+ providerMetadata: {
3109
+ anthropic: {
3110
+ pageAge: (_b = result.page_age) != null ? _b : null
3111
+ }
3112
+ }
3113
+ });
3114
+ }
3115
+ } else {
3116
+ content.push({
3117
+ type: "tool-result",
3118
+ toolCallId: part.tool_use_id,
3119
+ toolName: toolNameMapping.toCustomToolName("web_search"),
3120
+ isError: true,
3121
+ result: {
3122
+ type: "web_search_tool_result_error",
3123
+ errorCode: part.content.error_code
3124
+ }
3125
+ });
3126
+ }
3127
+ break;
3128
+ }
3129
+ // code execution 20250522:
3130
+ case "code_execution_tool_result": {
3131
+ if (part.content.type === "code_execution_result") {
3132
+ content.push({
3133
+ type: "tool-result",
3134
+ toolCallId: part.tool_use_id,
3135
+ toolName: toolNameMapping.toCustomToolName("code_execution"),
3136
+ result: {
3137
+ type: part.content.type,
3138
+ stdout: part.content.stdout,
3139
+ stderr: part.content.stderr,
3140
+ return_code: part.content.return_code,
3141
+ content: (_c = part.content.content) != null ? _c : []
3142
+ }
3143
+ });
3144
+ } else if (part.content.type === "code_execution_tool_result_error") {
3145
+ content.push({
3146
+ type: "tool-result",
3147
+ toolCallId: part.tool_use_id,
3148
+ toolName: toolNameMapping.toCustomToolName("code_execution"),
3149
+ isError: true,
3150
+ result: {
3151
+ type: "code_execution_tool_result_error",
3152
+ errorCode: part.content.error_code
3153
+ }
3154
+ });
3155
+ }
3156
+ break;
3157
+ }
3158
+ // code execution 20250825:
3159
+ case "bash_code_execution_tool_result":
3160
+ case "text_editor_code_execution_tool_result": {
3161
+ content.push({
3162
+ type: "tool-result",
3163
+ toolCallId: part.tool_use_id,
3164
+ toolName: toolNameMapping.toCustomToolName("code_execution"),
3165
+ result: part.content
3166
+ });
3167
+ break;
3168
+ }
3169
+ // tool search tool results:
3170
+ case "tool_search_tool_result": {
3171
+ let providerToolName = serverToolCalls[part.tool_use_id];
3172
+ if (providerToolName == null) {
3173
+ const bm25CustomName = toolNameMapping.toCustomToolName(
3174
+ "tool_search_tool_bm25"
3175
+ );
3176
+ const regexCustomName = toolNameMapping.toCustomToolName(
3177
+ "tool_search_tool_regex"
3178
+ );
3179
+ if (bm25CustomName !== "tool_search_tool_bm25") {
3180
+ providerToolName = "tool_search_tool_bm25";
3181
+ } else if (regexCustomName !== "tool_search_tool_regex") {
3182
+ providerToolName = "tool_search_tool_regex";
3183
+ } else {
3184
+ providerToolName = "tool_search_tool_regex";
3185
+ }
3186
+ }
3187
+ if (part.content.type === "tool_search_tool_search_result") {
3188
+ content.push({
3189
+ type: "tool-result",
3190
+ toolCallId: part.tool_use_id,
3191
+ toolName: toolNameMapping.toCustomToolName(providerToolName),
3192
+ result: part.content.tool_references.map((ref) => ({
3193
+ type: ref.type,
3194
+ toolName: ref.tool_name
3195
+ }))
3196
+ });
3197
+ } else {
3198
+ content.push({
3199
+ type: "tool-result",
3200
+ toolCallId: part.tool_use_id,
3201
+ toolName: toolNameMapping.toCustomToolName(providerToolName),
3202
+ isError: true,
3203
+ result: {
3204
+ type: "tool_search_tool_result_error",
3205
+ errorCode: part.content.error_code
3206
+ }
3207
+ });
3208
+ }
3209
+ break;
3210
+ }
3211
+ }
3212
+ }
3213
+ return {
3214
+ content,
3215
+ finishReason: {
3216
+ unified: mapAnthropicStopReason({
3217
+ finishReason: response.stop_reason,
3218
+ isJsonResponseFromTool
3219
+ }),
3220
+ raw: (_d = response.stop_reason) != null ? _d : void 0
3221
+ },
3222
+ usage: convertAnthropicMessagesUsage({ usage: response.usage }),
3223
+ request: { body: args },
3224
+ response: {
3225
+ id: (_e = response.id) != null ? _e : void 0,
3226
+ modelId: (_f = response.model) != null ? _f : void 0,
3227
+ headers: responseHeaders,
3228
+ body: rawResponse
3229
+ },
3230
+ warnings,
3231
+ providerMetadata: (() => {
3232
+ var _a2, _b2, _c2, _d2, _e2;
3233
+ const anthropicMetadata = {
3234
+ usage: response.usage,
3235
+ cacheCreationInputTokens: (_a2 = response.usage.cache_creation_input_tokens) != null ? _a2 : null,
3236
+ stopSequence: (_b2 = response.stop_sequence) != null ? _b2 : null,
3237
+ iterations: response.usage.iterations ? response.usage.iterations.map((iter) => ({
3238
+ type: iter.type,
3239
+ inputTokens: iter.input_tokens,
3240
+ outputTokens: iter.output_tokens
3241
+ })) : null,
3242
+ container: response.container ? {
3243
+ expiresAt: response.container.expires_at,
3244
+ id: response.container.id,
3245
+ skills: (_d2 = (_c2 = response.container.skills) == null ? void 0 : _c2.map((skill) => ({
3246
+ type: skill.type,
3247
+ skillId: skill.skill_id,
3248
+ version: skill.version
3249
+ }))) != null ? _d2 : null
3250
+ } : null,
3251
+ contextManagement: (_e2 = mapAnthropicResponseContextManagement(
3252
+ response.context_management
3253
+ )) != null ? _e2 : null
3254
+ };
3255
+ const providerMetadata = {
3256
+ anthropic: anthropicMetadata
3257
+ };
3258
+ if (usedCustomProviderKey && providerOptionsName !== "anthropic") {
3259
+ providerMetadata[providerOptionsName] = anthropicMetadata;
3260
+ }
3261
+ return providerMetadata;
3262
+ })()
3263
+ };
3264
+ }
3265
+ async doStream(options) {
3266
+ var _a, _b;
3267
+ const {
3268
+ args: body,
3269
+ warnings,
3270
+ betas,
3271
+ usesJsonResponseTool,
3272
+ toolNameMapping,
3273
+ providerOptionsName,
3274
+ usedCustomProviderKey
3275
+ } = await this.getArgs({
3276
+ ...options,
3277
+ stream: true,
3278
+ userSuppliedBetas: await this.getBetasFromHeaders(options.headers)
3279
+ });
3280
+ const citationDocuments = [
3281
+ ...this.extractCitationDocuments(options.prompt)
3282
+ ];
3283
+ const url = this.buildRequestUrl(true);
3284
+ const { responseHeaders, value: response } = await postJsonToApi({
3285
+ url,
3286
+ headers: await this.getHeaders({ betas, headers: options.headers }),
3287
+ body: this.transformRequestBody(body),
3288
+ failedResponseHandler: anthropicFailedResponseHandler,
3289
+ successfulResponseHandler: createEventSourceResponseHandler(
3290
+ anthropicMessagesChunkSchema
3291
+ ),
3292
+ abortSignal: options.abortSignal,
3293
+ fetch: this.config.fetch
3294
+ });
3295
+ let finishReason = {
3296
+ unified: "other",
3297
+ raw: void 0
3298
+ };
3299
+ const usage = {
3300
+ input_tokens: 0,
3301
+ output_tokens: 0,
3302
+ cache_creation_input_tokens: 0,
3303
+ cache_read_input_tokens: 0,
3304
+ iterations: null
3305
+ };
3306
+ const contentBlocks = {};
3307
+ const mcpToolCalls = {};
3308
+ const serverToolCalls = {};
3309
+ let contextManagement = null;
3310
+ let rawUsage = void 0;
3311
+ let cacheCreationInputTokens = null;
3312
+ let stopSequence = null;
3313
+ let container = null;
3314
+ let isJsonResponseFromTool = false;
3315
+ let blockType = void 0;
3316
+ const generateId3 = this.generateId;
3317
+ const transformedStream = response.pipeThrough(
3318
+ new TransformStream({
3319
+ start(controller) {
3320
+ controller.enqueue({ type: "stream-start", warnings });
3321
+ },
3322
+ transform(chunk, controller) {
3323
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
3324
+ if (options.includeRawChunks) {
3325
+ controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
3326
+ }
3327
+ if (!chunk.success) {
3328
+ controller.enqueue({ type: "error", error: chunk.error });
3329
+ return;
3330
+ }
3331
+ const value = chunk.value;
3332
+ switch (value.type) {
3333
+ case "ping": {
3334
+ return;
3335
+ }
3336
+ case "content_block_start": {
3337
+ const part = value.content_block;
3338
+ const contentBlockType = part.type;
3339
+ blockType = contentBlockType;
3340
+ switch (contentBlockType) {
3341
+ case "text": {
3342
+ if (usesJsonResponseTool) {
3343
+ return;
3344
+ }
3345
+ contentBlocks[value.index] = { type: "text" };
3346
+ controller.enqueue({
3347
+ type: "text-start",
3348
+ id: String(value.index)
3349
+ });
3350
+ return;
3351
+ }
3352
+ case "thinking": {
3353
+ contentBlocks[value.index] = { type: "reasoning" };
3354
+ controller.enqueue({
3355
+ type: "reasoning-start",
3356
+ id: String(value.index)
3357
+ });
3358
+ return;
3359
+ }
3360
+ case "redacted_thinking": {
3361
+ contentBlocks[value.index] = { type: "reasoning" };
3362
+ controller.enqueue({
3363
+ type: "reasoning-start",
3364
+ id: String(value.index),
3365
+ providerMetadata: {
3366
+ anthropic: {
3367
+ redactedData: part.data
3368
+ }
3369
+ }
3370
+ });
3371
+ return;
3372
+ }
3373
+ case "compaction": {
3374
+ contentBlocks[value.index] = { type: "text" };
3375
+ controller.enqueue({
3376
+ type: "text-start",
3377
+ id: String(value.index),
3378
+ providerMetadata: {
3379
+ anthropic: {
3380
+ type: "compaction"
3381
+ }
3382
+ }
3383
+ });
3384
+ return;
3385
+ }
3386
+ case "tool_use": {
3387
+ const isJsonResponseTool = usesJsonResponseTool && part.name === "json";
3388
+ if (isJsonResponseTool) {
3389
+ isJsonResponseFromTool = true;
3390
+ contentBlocks[value.index] = { type: "text" };
3391
+ controller.enqueue({
3392
+ type: "text-start",
3393
+ id: String(value.index)
3394
+ });
3395
+ } else {
3396
+ const caller = part.caller;
3397
+ const callerInfo = caller ? {
3398
+ type: caller.type,
3399
+ toolId: "tool_id" in caller ? caller.tool_id : void 0
3400
+ } : void 0;
3401
+ const hasNonEmptyInput = part.input && Object.keys(part.input).length > 0;
3402
+ const initialInput = hasNonEmptyInput ? JSON.stringify(part.input) : "";
3403
+ contentBlocks[value.index] = {
3404
+ type: "tool-call",
3405
+ toolCallId: part.id,
3406
+ toolName: part.name,
3407
+ input: initialInput,
3408
+ firstDelta: initialInput.length === 0,
3409
+ ...callerInfo && { caller: callerInfo }
3410
+ };
3411
+ controller.enqueue({
3412
+ type: "tool-input-start",
3413
+ id: part.id,
3414
+ toolName: part.name
3415
+ });
3416
+ }
3417
+ return;
3418
+ }
3419
+ case "server_tool_use": {
3420
+ if ([
3421
+ "web_fetch",
3422
+ "web_search",
3423
+ // code execution 20250825:
3424
+ "code_execution",
3425
+ // code execution 20250825 text editor:
3426
+ "text_editor_code_execution",
3427
+ // code execution 20250825 bash:
3428
+ "bash_code_execution"
3429
+ ].includes(part.name)) {
3430
+ const providerToolName = part.name === "text_editor_code_execution" || part.name === "bash_code_execution" ? "code_execution" : part.name;
3431
+ const customToolName = toolNameMapping.toCustomToolName(providerToolName);
3432
+ contentBlocks[value.index] = {
3433
+ type: "tool-call",
3434
+ toolCallId: part.id,
3435
+ toolName: customToolName,
3436
+ input: "",
3437
+ providerExecuted: true,
3438
+ firstDelta: true,
3439
+ providerToolName: part.name
3440
+ };
3441
+ controller.enqueue({
3442
+ type: "tool-input-start",
3443
+ id: part.id,
3444
+ toolName: customToolName,
3445
+ providerExecuted: true
3446
+ });
3447
+ } else if (part.name === "tool_search_tool_regex" || part.name === "tool_search_tool_bm25") {
3448
+ serverToolCalls[part.id] = part.name;
3449
+ const customToolName = toolNameMapping.toCustomToolName(
3450
+ part.name
3451
+ );
3452
+ contentBlocks[value.index] = {
3453
+ type: "tool-call",
3454
+ toolCallId: part.id,
3455
+ toolName: customToolName,
3456
+ input: "",
3457
+ providerExecuted: true,
3458
+ firstDelta: true,
3459
+ providerToolName: part.name
3460
+ };
3461
+ controller.enqueue({
3462
+ type: "tool-input-start",
3463
+ id: part.id,
3464
+ toolName: customToolName,
3465
+ providerExecuted: true
3466
+ });
3467
+ }
3468
+ return;
3469
+ }
3470
+ case "web_fetch_tool_result": {
3471
+ if (part.content.type === "web_fetch_result") {
3472
+ citationDocuments.push({
3473
+ title: (_a2 = part.content.content.title) != null ? _a2 : part.content.url,
3474
+ mediaType: part.content.content.source.media_type
3475
+ });
3476
+ controller.enqueue({
3477
+ type: "tool-result",
3478
+ toolCallId: part.tool_use_id,
3479
+ toolName: toolNameMapping.toCustomToolName("web_fetch"),
3480
+ result: {
3481
+ type: "web_fetch_result",
3482
+ url: part.content.url,
3483
+ retrievedAt: part.content.retrieved_at,
3484
+ content: {
3485
+ type: part.content.content.type,
3486
+ title: part.content.content.title,
3487
+ citations: part.content.content.citations,
3488
+ source: {
3489
+ type: part.content.content.source.type,
3490
+ mediaType: part.content.content.source.media_type,
3491
+ data: part.content.content.source.data
3492
+ }
3493
+ }
3494
+ }
3495
+ });
3496
+ } else if (part.content.type === "web_fetch_tool_result_error") {
3497
+ controller.enqueue({
3498
+ type: "tool-result",
3499
+ toolCallId: part.tool_use_id,
3500
+ toolName: toolNameMapping.toCustomToolName("web_fetch"),
3501
+ isError: true,
3502
+ result: {
3503
+ type: "web_fetch_tool_result_error",
3504
+ errorCode: part.content.error_code
3505
+ }
3506
+ });
3507
+ }
3508
+ return;
3509
+ }
3510
+ case "web_search_tool_result": {
3511
+ if (Array.isArray(part.content)) {
3512
+ controller.enqueue({
3513
+ type: "tool-result",
3514
+ toolCallId: part.tool_use_id,
3515
+ toolName: toolNameMapping.toCustomToolName("web_search"),
3516
+ result: part.content.map((result) => {
3517
+ var _a3;
3518
+ return {
3519
+ url: result.url,
3520
+ title: result.title,
3521
+ pageAge: (_a3 = result.page_age) != null ? _a3 : null,
3522
+ encryptedContent: result.encrypted_content,
3523
+ type: result.type
3524
+ };
3525
+ })
3526
+ });
3527
+ for (const result of part.content) {
3528
+ controller.enqueue({
3529
+ type: "source",
3530
+ sourceType: "url",
3531
+ id: generateId3(),
3532
+ url: result.url,
3533
+ title: result.title,
3534
+ providerMetadata: {
3535
+ anthropic: {
3536
+ pageAge: (_b2 = result.page_age) != null ? _b2 : null
3537
+ }
3538
+ }
3539
+ });
3540
+ }
3541
+ } else {
3542
+ controller.enqueue({
3543
+ type: "tool-result",
3544
+ toolCallId: part.tool_use_id,
3545
+ toolName: toolNameMapping.toCustomToolName("web_search"),
3546
+ isError: true,
3547
+ result: {
3548
+ type: "web_search_tool_result_error",
3549
+ errorCode: part.content.error_code
3550
+ }
3551
+ });
3552
+ }
3553
+ return;
3554
+ }
3555
+ // code execution 20250522:
3556
+ case "code_execution_tool_result": {
3557
+ if (part.content.type === "code_execution_result") {
3558
+ controller.enqueue({
3559
+ type: "tool-result",
3560
+ toolCallId: part.tool_use_id,
3561
+ toolName: toolNameMapping.toCustomToolName("code_execution"),
3562
+ result: {
3563
+ type: part.content.type,
3564
+ stdout: part.content.stdout,
3565
+ stderr: part.content.stderr,
3566
+ return_code: part.content.return_code,
3567
+ content: (_c = part.content.content) != null ? _c : []
3568
+ }
3569
+ });
3570
+ } else if (part.content.type === "code_execution_tool_result_error") {
3571
+ controller.enqueue({
3572
+ type: "tool-result",
3573
+ toolCallId: part.tool_use_id,
3574
+ toolName: toolNameMapping.toCustomToolName("code_execution"),
3575
+ isError: true,
3576
+ result: {
3577
+ type: "code_execution_tool_result_error",
3578
+ errorCode: part.content.error_code
3579
+ }
3580
+ });
3581
+ }
3582
+ return;
3583
+ }
3584
+ // code execution 20250825:
3585
+ case "bash_code_execution_tool_result":
3586
+ case "text_editor_code_execution_tool_result": {
3587
+ controller.enqueue({
3588
+ type: "tool-result",
3589
+ toolCallId: part.tool_use_id,
3590
+ toolName: toolNameMapping.toCustomToolName("code_execution"),
3591
+ result: part.content
3592
+ });
3593
+ return;
3594
+ }
3595
+ // tool search tool results:
3596
+ case "tool_search_tool_result": {
3597
+ let providerToolName = serverToolCalls[part.tool_use_id];
3598
+ if (providerToolName == null) {
3599
+ const bm25CustomName = toolNameMapping.toCustomToolName(
3600
+ "tool_search_tool_bm25"
3601
+ );
3602
+ const regexCustomName = toolNameMapping.toCustomToolName(
3603
+ "tool_search_tool_regex"
3604
+ );
3605
+ if (bm25CustomName !== "tool_search_tool_bm25") {
3606
+ providerToolName = "tool_search_tool_bm25";
3607
+ } else if (regexCustomName !== "tool_search_tool_regex") {
3608
+ providerToolName = "tool_search_tool_regex";
3609
+ } else {
3610
+ providerToolName = "tool_search_tool_regex";
3611
+ }
3612
+ }
3613
+ if (part.content.type === "tool_search_tool_search_result") {
3614
+ controller.enqueue({
3615
+ type: "tool-result",
3616
+ toolCallId: part.tool_use_id,
3617
+ toolName: toolNameMapping.toCustomToolName(providerToolName),
3618
+ result: part.content.tool_references.map((ref) => ({
3619
+ type: ref.type,
3620
+ toolName: ref.tool_name
3621
+ }))
3622
+ });
3623
+ } else {
3624
+ controller.enqueue({
3625
+ type: "tool-result",
3626
+ toolCallId: part.tool_use_id,
3627
+ toolName: toolNameMapping.toCustomToolName(providerToolName),
3628
+ isError: true,
3629
+ result: {
3630
+ type: "tool_search_tool_result_error",
3631
+ errorCode: part.content.error_code
3632
+ }
3633
+ });
3634
+ }
3635
+ return;
3636
+ }
3637
+ case "mcp_tool_use": {
3638
+ mcpToolCalls[part.id] = {
3639
+ type: "tool-call",
3640
+ toolCallId: part.id,
3641
+ toolName: part.name,
3642
+ input: JSON.stringify(part.input),
3643
+ providerExecuted: true,
3644
+ dynamic: true,
3645
+ providerMetadata: {
3646
+ anthropic: {
3647
+ type: "mcp-tool-use",
3648
+ serverName: part.server_name
3649
+ }
3650
+ }
3651
+ };
3652
+ controller.enqueue(mcpToolCalls[part.id]);
3653
+ return;
3654
+ }
3655
+ case "mcp_tool_result": {
3656
+ controller.enqueue({
3657
+ type: "tool-result",
3658
+ toolCallId: part.tool_use_id,
3659
+ toolName: mcpToolCalls[part.tool_use_id].toolName,
3660
+ isError: part.is_error,
3661
+ result: part.content,
3662
+ dynamic: true,
3663
+ providerMetadata: mcpToolCalls[part.tool_use_id].providerMetadata
3664
+ });
3665
+ return;
3666
+ }
3667
+ default: {
3668
+ const _exhaustiveCheck = contentBlockType;
3669
+ throw new Error(
3670
+ `Unsupported content block type: ${_exhaustiveCheck}`
3671
+ );
3672
+ }
3673
+ }
3674
+ }
3675
+ case "content_block_stop": {
3676
+ if (contentBlocks[value.index] != null) {
3677
+ const contentBlock = contentBlocks[value.index];
3678
+ switch (contentBlock.type) {
3679
+ case "text": {
3680
+ controller.enqueue({
3681
+ type: "text-end",
3682
+ id: String(value.index)
3683
+ });
3684
+ break;
3685
+ }
3686
+ case "reasoning": {
3687
+ controller.enqueue({
3688
+ type: "reasoning-end",
3689
+ id: String(value.index)
3690
+ });
3691
+ break;
3692
+ }
3693
+ case "tool-call":
3694
+ const isJsonResponseTool = usesJsonResponseTool && contentBlock.toolName === "json";
3695
+ if (!isJsonResponseTool) {
3696
+ controller.enqueue({
3697
+ type: "tool-input-end",
3698
+ id: contentBlock.toolCallId
3699
+ });
3700
+ let finalInput = contentBlock.input === "" ? "{}" : contentBlock.input;
3701
+ if (contentBlock.providerToolName === "code_execution") {
3702
+ try {
3703
+ const parsed = JSON.parse(finalInput);
3704
+ if (parsed != null && typeof parsed === "object" && "code" in parsed && !("type" in parsed)) {
3705
+ finalInput = JSON.stringify({
3706
+ type: "programmatic-tool-call",
3707
+ ...parsed
3708
+ });
3709
+ }
3710
+ } catch (e) {
3711
+ }
3712
+ }
3713
+ controller.enqueue({
3714
+ type: "tool-call",
3715
+ toolCallId: contentBlock.toolCallId,
3716
+ toolName: contentBlock.toolName,
3717
+ input: finalInput,
3718
+ providerExecuted: contentBlock.providerExecuted,
3719
+ ...contentBlock.caller && {
3720
+ providerMetadata: {
3721
+ anthropic: {
3722
+ caller: contentBlock.caller
3723
+ }
3724
+ }
3725
+ }
3726
+ });
3727
+ }
3728
+ break;
3729
+ }
3730
+ delete contentBlocks[value.index];
3731
+ }
3732
+ blockType = void 0;
3733
+ return;
3734
+ }
3735
+ case "content_block_delta": {
3736
+ const deltaType = value.delta.type;
3737
+ switch (deltaType) {
3738
+ case "text_delta": {
3739
+ if (usesJsonResponseTool) {
3740
+ return;
3741
+ }
3742
+ controller.enqueue({
3743
+ type: "text-delta",
3744
+ id: String(value.index),
3745
+ delta: value.delta.text
3746
+ });
3747
+ return;
3748
+ }
3749
+ case "thinking_delta": {
3750
+ controller.enqueue({
3751
+ type: "reasoning-delta",
3752
+ id: String(value.index),
3753
+ delta: value.delta.thinking
3754
+ });
3755
+ return;
3756
+ }
3757
+ case "signature_delta": {
3758
+ if (blockType === "thinking") {
3759
+ controller.enqueue({
3760
+ type: "reasoning-delta",
3761
+ id: String(value.index),
3762
+ delta: "",
3763
+ providerMetadata: {
3764
+ anthropic: {
3765
+ signature: value.delta.signature
3766
+ }
3767
+ }
3768
+ });
3769
+ }
3770
+ return;
3771
+ }
3772
+ case "compaction_delta": {
3773
+ if (value.delta.content != null) {
3774
+ controller.enqueue({
3775
+ type: "text-delta",
3776
+ id: String(value.index),
3777
+ delta: value.delta.content
3778
+ });
3779
+ }
3780
+ return;
3781
+ }
3782
+ case "input_json_delta": {
3783
+ const contentBlock = contentBlocks[value.index];
3784
+ let delta = value.delta.partial_json;
3785
+ if (delta.length === 0) {
3786
+ return;
3787
+ }
3788
+ if (isJsonResponseFromTool) {
3789
+ if ((contentBlock == null ? void 0 : contentBlock.type) !== "text") {
3790
+ return;
3791
+ }
3792
+ controller.enqueue({
3793
+ type: "text-delta",
3794
+ id: String(value.index),
3795
+ delta
3796
+ });
3797
+ } else {
3798
+ if ((contentBlock == null ? void 0 : contentBlock.type) !== "tool-call") {
3799
+ return;
3800
+ }
3801
+ if (contentBlock.firstDelta && (contentBlock.providerToolName === "bash_code_execution" || contentBlock.providerToolName === "text_editor_code_execution")) {
3802
+ delta = `{"type": "${contentBlock.providerToolName}",${delta.substring(1)}`;
3803
+ }
3804
+ controller.enqueue({
3805
+ type: "tool-input-delta",
3806
+ id: contentBlock.toolCallId,
3807
+ delta
3808
+ });
3809
+ contentBlock.input += delta;
3810
+ contentBlock.firstDelta = false;
3811
+ }
3812
+ return;
3813
+ }
3814
+ case "citations_delta": {
3815
+ const citation = value.delta.citation;
3816
+ const source = createCitationSource(
3817
+ citation,
3818
+ citationDocuments,
3819
+ generateId3
3820
+ );
3821
+ if (source) {
3822
+ controller.enqueue(source);
3823
+ }
3824
+ return;
3825
+ }
3826
+ default: {
3827
+ const _exhaustiveCheck = deltaType;
3828
+ throw new Error(
3829
+ `Unsupported delta type: ${_exhaustiveCheck}`
3830
+ );
3831
+ }
3832
+ }
3833
+ }
3834
+ case "message_start": {
3835
+ usage.input_tokens = value.message.usage.input_tokens;
3836
+ usage.cache_read_input_tokens = (_d = value.message.usage.cache_read_input_tokens) != null ? _d : 0;
3837
+ usage.cache_creation_input_tokens = (_e = value.message.usage.cache_creation_input_tokens) != null ? _e : 0;
3838
+ rawUsage = {
3839
+ ...value.message.usage
3840
+ };
3841
+ cacheCreationInputTokens = (_f = value.message.usage.cache_creation_input_tokens) != null ? _f : null;
3842
+ if (value.message.container != null) {
3843
+ container = {
3844
+ expiresAt: value.message.container.expires_at,
3845
+ id: value.message.container.id,
3846
+ skills: null
3847
+ };
3848
+ }
3849
+ if (value.message.stop_reason != null) {
3850
+ finishReason = {
3851
+ unified: mapAnthropicStopReason({
3852
+ finishReason: value.message.stop_reason,
3853
+ isJsonResponseFromTool
3854
+ }),
3855
+ raw: value.message.stop_reason
3856
+ };
3857
+ }
3858
+ controller.enqueue({
3859
+ type: "response-metadata",
3860
+ id: (_g = value.message.id) != null ? _g : void 0,
3861
+ modelId: (_h = value.message.model) != null ? _h : void 0
3862
+ });
3863
+ if (value.message.content != null) {
3864
+ for (let contentIndex = 0; contentIndex < value.message.content.length; contentIndex++) {
3865
+ const part = value.message.content[contentIndex];
3866
+ if (part.type === "tool_use") {
3867
+ const caller = part.caller;
3868
+ const callerInfo = caller ? {
3869
+ type: caller.type,
3870
+ toolId: "tool_id" in caller ? caller.tool_id : void 0
3871
+ } : void 0;
3872
+ controller.enqueue({
3873
+ type: "tool-input-start",
3874
+ id: part.id,
3875
+ toolName: part.name
3876
+ });
3877
+ const inputStr = JSON.stringify((_i = part.input) != null ? _i : {});
3878
+ controller.enqueue({
3879
+ type: "tool-input-delta",
3880
+ id: part.id,
3881
+ delta: inputStr
3882
+ });
3883
+ controller.enqueue({
3884
+ type: "tool-input-end",
3885
+ id: part.id
3886
+ });
3887
+ controller.enqueue({
3888
+ type: "tool-call",
3889
+ toolCallId: part.id,
3890
+ toolName: part.name,
3891
+ input: inputStr,
3892
+ ...callerInfo && {
3893
+ providerMetadata: {
3894
+ anthropic: {
3895
+ caller: callerInfo
3896
+ }
3897
+ }
3898
+ }
3899
+ });
3900
+ }
3901
+ }
3902
+ }
3903
+ return;
3904
+ }
3905
+ case "message_delta": {
3906
+ if (value.usage.input_tokens != null && usage.input_tokens !== value.usage.input_tokens) {
3907
+ usage.input_tokens = value.usage.input_tokens;
3908
+ }
3909
+ usage.output_tokens = value.usage.output_tokens;
3910
+ if (value.usage.cache_read_input_tokens != null) {
3911
+ usage.cache_read_input_tokens = value.usage.cache_read_input_tokens;
3912
+ }
3913
+ if (value.usage.cache_creation_input_tokens != null) {
3914
+ usage.cache_creation_input_tokens = value.usage.cache_creation_input_tokens;
3915
+ cacheCreationInputTokens = value.usage.cache_creation_input_tokens;
3916
+ }
3917
+ if (value.usage.iterations != null) {
3918
+ usage.iterations = value.usage.iterations;
3919
+ }
3920
+ finishReason = {
3921
+ unified: mapAnthropicStopReason({
3922
+ finishReason: value.delta.stop_reason,
3923
+ isJsonResponseFromTool
3924
+ }),
3925
+ raw: (_j = value.delta.stop_reason) != null ? _j : void 0
3926
+ };
3927
+ stopSequence = (_k = value.delta.stop_sequence) != null ? _k : null;
3928
+ container = value.delta.container != null ? {
3929
+ expiresAt: value.delta.container.expires_at,
3930
+ id: value.delta.container.id,
3931
+ skills: (_m = (_l = value.delta.container.skills) == null ? void 0 : _l.map((skill) => ({
3932
+ type: skill.type,
3933
+ skillId: skill.skill_id,
3934
+ version: skill.version
3935
+ }))) != null ? _m : null
3936
+ } : null;
3937
+ if (value.context_management) {
3938
+ contextManagement = mapAnthropicResponseContextManagement(
3939
+ value.context_management
3940
+ );
3941
+ }
3942
+ rawUsage = {
3943
+ ...rawUsage,
3944
+ ...value.usage
3945
+ };
3946
+ return;
3947
+ }
3948
+ case "message_stop": {
3949
+ const anthropicMetadata = {
3950
+ usage: rawUsage != null ? rawUsage : null,
3951
+ cacheCreationInputTokens,
3952
+ stopSequence,
3953
+ iterations: usage.iterations ? usage.iterations.map((iter) => ({
3954
+ type: iter.type,
3955
+ inputTokens: iter.input_tokens,
3956
+ outputTokens: iter.output_tokens
3957
+ })) : null,
3958
+ container,
3959
+ contextManagement
3960
+ };
3961
+ const providerMetadata = {
3962
+ anthropic: anthropicMetadata
3963
+ };
3964
+ if (usedCustomProviderKey && providerOptionsName !== "anthropic") {
3965
+ providerMetadata[providerOptionsName] = anthropicMetadata;
3966
+ }
3967
+ controller.enqueue({
3968
+ type: "finish",
3969
+ finishReason,
3970
+ usage: convertAnthropicMessagesUsage({ usage, rawUsage }),
3971
+ providerMetadata
3972
+ });
3973
+ return;
3974
+ }
3975
+ case "error": {
3976
+ controller.enqueue({ type: "error", error: value.error });
3977
+ return;
3978
+ }
3979
+ default: {
3980
+ const _exhaustiveCheck = value;
3981
+ throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);
3982
+ }
3983
+ }
3984
+ }
3985
+ })
3986
+ );
3987
+ const [streamForFirstChunk, streamForConsumer] = transformedStream.tee();
3988
+ const firstChunkReader = streamForFirstChunk.getReader();
3989
+ try {
3990
+ await firstChunkReader.read();
3991
+ let result = await firstChunkReader.read();
3992
+ if (((_a = result.value) == null ? void 0 : _a.type) === "raw") {
3993
+ result = await firstChunkReader.read();
3994
+ }
3995
+ if (((_b = result.value) == null ? void 0 : _b.type) === "error") {
3996
+ const error = result.value.error;
3997
+ throw new APICallError({
3998
+ message: error.message,
3999
+ url,
4000
+ requestBodyValues: body,
4001
+ statusCode: error.type === "overloaded_error" ? 529 : 500,
4002
+ responseHeaders,
4003
+ responseBody: JSON.stringify(error),
4004
+ isRetryable: error.type === "overloaded_error"
4005
+ });
4006
+ }
4007
+ } finally {
4008
+ firstChunkReader.cancel().catch(() => {
4009
+ });
4010
+ firstChunkReader.releaseLock();
4011
+ }
4012
+ return {
4013
+ stream: streamForConsumer,
4014
+ request: { body },
4015
+ response: { headers: responseHeaders }
4016
+ };
4017
+ }
4018
+ };
4019
+ function getModelCapabilities(modelId) {
4020
+ if (modelId.includes("claude-sonnet-4-6") || modelId.includes("claude-opus-4-6")) {
4021
+ return {
4022
+ maxOutputTokens: 128e3,
4023
+ supportsStructuredOutput: true,
4024
+ isKnownModel: true
4025
+ };
4026
+ } else if (modelId.includes("claude-sonnet-4-5") || modelId.includes("claude-opus-4-5") || modelId.includes("claude-haiku-4-5")) {
4027
+ return {
4028
+ maxOutputTokens: 64e3,
4029
+ supportsStructuredOutput: true,
4030
+ isKnownModel: true
4031
+ };
4032
+ } else if (modelId.includes("claude-opus-4-1")) {
4033
+ return {
4034
+ maxOutputTokens: 32e3,
4035
+ supportsStructuredOutput: true,
4036
+ isKnownModel: true
4037
+ };
4038
+ } else if (modelId.includes("claude-sonnet-4-") || modelId.includes("claude-3-7-sonnet")) {
4039
+ return {
4040
+ maxOutputTokens: 64e3,
4041
+ supportsStructuredOutput: false,
4042
+ isKnownModel: true
4043
+ };
4044
+ } else if (modelId.includes("claude-opus-4-")) {
4045
+ return {
4046
+ maxOutputTokens: 32e3,
4047
+ supportsStructuredOutput: false,
4048
+ isKnownModel: true
4049
+ };
4050
+ } else if (modelId.includes("claude-3-5-haiku")) {
4051
+ return {
4052
+ maxOutputTokens: 8192,
4053
+ supportsStructuredOutput: false,
4054
+ isKnownModel: true
4055
+ };
4056
+ } else if (modelId.includes("claude-3-haiku")) {
4057
+ return {
4058
+ maxOutputTokens: 4096,
4059
+ supportsStructuredOutput: false,
4060
+ isKnownModel: true
4061
+ };
4062
+ } else {
4063
+ return {
4064
+ maxOutputTokens: 4096,
4065
+ supportsStructuredOutput: false,
4066
+ isKnownModel: false
4067
+ };
4068
+ }
4069
+ }
4070
+ function mapAnthropicResponseContextManagement(contextManagement) {
4071
+ return contextManagement ? {
4072
+ appliedEdits: contextManagement.applied_edits.map((edit) => {
4073
+ const strategy = edit.type;
4074
+ switch (strategy) {
4075
+ case "clear_tool_uses_20250919":
4076
+ return {
4077
+ type: edit.type,
4078
+ clearedToolUses: edit.cleared_tool_uses,
4079
+ clearedInputTokens: edit.cleared_input_tokens
4080
+ };
4081
+ case "clear_thinking_20251015":
4082
+ return {
4083
+ type: edit.type,
4084
+ clearedThinkingTurns: edit.cleared_thinking_turns,
4085
+ clearedInputTokens: edit.cleared_input_tokens
4086
+ };
4087
+ case "compact_20260112":
4088
+ return {
4089
+ type: edit.type
4090
+ };
4091
+ }
4092
+ }).filter((edit) => edit !== void 0)
4093
+ } : null;
4094
+ }
4095
+ var bash_20241022InputSchema = lazySchema(
4096
+ () => zodSchema(
4097
+ object({
4098
+ command: string(),
4099
+ restart: boolean().optional()
4100
+ })
4101
+ )
4102
+ );
4103
+ var bash_20241022 = createProviderToolFactory({
4104
+ id: "anthropic.bash_20241022",
4105
+ inputSchema: bash_20241022InputSchema
4106
+ });
4107
+ var bash_20250124InputSchema = lazySchema(
4108
+ () => zodSchema(
4109
+ object({
4110
+ command: string(),
4111
+ restart: boolean().optional()
4112
+ })
4113
+ )
4114
+ );
4115
+ var bash_20250124 = createProviderToolFactory({
4116
+ id: "anthropic.bash_20250124",
4117
+ inputSchema: bash_20250124InputSchema
4118
+ });
4119
+ var computer_20241022InputSchema = lazySchema(
4120
+ () => zodSchema(
4121
+ object({
4122
+ action: _enum([
4123
+ "key",
4124
+ "type",
4125
+ "mouse_move",
4126
+ "left_click",
4127
+ "left_click_drag",
4128
+ "right_click",
4129
+ "middle_click",
4130
+ "double_click",
4131
+ "screenshot",
4132
+ "cursor_position"
4133
+ ]),
4134
+ coordinate: array(number().int()).optional(),
4135
+ text: string().optional()
4136
+ })
4137
+ )
4138
+ );
4139
+ var computer_20241022 = createProviderToolFactory({
4140
+ id: "anthropic.computer_20241022",
4141
+ inputSchema: computer_20241022InputSchema
4142
+ });
4143
+ var computer_20250124InputSchema = lazySchema(
4144
+ () => zodSchema(
4145
+ object({
4146
+ action: _enum([
4147
+ "key",
4148
+ "hold_key",
4149
+ "type",
4150
+ "cursor_position",
4151
+ "mouse_move",
4152
+ "left_mouse_down",
4153
+ "left_mouse_up",
4154
+ "left_click",
4155
+ "left_click_drag",
4156
+ "right_click",
4157
+ "middle_click",
4158
+ "double_click",
4159
+ "triple_click",
4160
+ "scroll",
4161
+ "wait",
4162
+ "screenshot"
4163
+ ]),
4164
+ coordinate: tuple([number().int(), number().int()]).optional(),
4165
+ duration: number().optional(),
4166
+ scroll_amount: number().optional(),
4167
+ scroll_direction: _enum(["up", "down", "left", "right"]).optional(),
4168
+ start_coordinate: tuple([number().int(), number().int()]).optional(),
4169
+ text: string().optional()
4170
+ })
4171
+ )
4172
+ );
4173
+ var computer_20250124 = createProviderToolFactory({
4174
+ id: "anthropic.computer_20250124",
4175
+ inputSchema: computer_20250124InputSchema
4176
+ });
4177
+ var computer_20251124InputSchema = lazySchema(
4178
+ () => zodSchema(
4179
+ object({
4180
+ action: _enum([
4181
+ "key",
4182
+ "hold_key",
4183
+ "type",
4184
+ "cursor_position",
4185
+ "mouse_move",
4186
+ "left_mouse_down",
4187
+ "left_mouse_up",
4188
+ "left_click",
4189
+ "left_click_drag",
4190
+ "right_click",
4191
+ "middle_click",
4192
+ "double_click",
4193
+ "triple_click",
4194
+ "scroll",
4195
+ "wait",
4196
+ "screenshot",
4197
+ "zoom"
4198
+ ]),
4199
+ coordinate: tuple([number().int(), number().int()]).optional(),
4200
+ duration: number().optional(),
4201
+ region: tuple([
4202
+ number().int(),
4203
+ number().int(),
4204
+ number().int(),
4205
+ number().int()
4206
+ ]).optional(),
4207
+ scroll_amount: number().optional(),
4208
+ scroll_direction: _enum(["up", "down", "left", "right"]).optional(),
4209
+ start_coordinate: tuple([number().int(), number().int()]).optional(),
4210
+ text: string().optional()
4211
+ })
4212
+ )
4213
+ );
4214
+ var computer_20251124 = createProviderToolFactory({
4215
+ id: "anthropic.computer_20251124",
4216
+ inputSchema: computer_20251124InputSchema
4217
+ });
4218
+ var memory_20250818InputSchema = lazySchema(
4219
+ () => zodSchema(
4220
+ discriminatedUnion("command", [
4221
+ object({
4222
+ command: literal("view"),
4223
+ path: string(),
4224
+ view_range: tuple([number(), number()]).optional()
4225
+ }),
4226
+ object({
4227
+ command: literal("create"),
4228
+ path: string(),
4229
+ file_text: string()
4230
+ }),
4231
+ object({
4232
+ command: literal("str_replace"),
4233
+ path: string(),
4234
+ old_str: string(),
4235
+ new_str: string()
4236
+ }),
4237
+ object({
4238
+ command: literal("insert"),
4239
+ path: string(),
4240
+ insert_line: number(),
4241
+ insert_text: string()
4242
+ }),
4243
+ object({
4244
+ command: literal("delete"),
4245
+ path: string()
4246
+ }),
4247
+ object({
4248
+ command: literal("rename"),
4249
+ old_path: string(),
4250
+ new_path: string()
4251
+ })
4252
+ ])
4253
+ )
4254
+ );
4255
+ var memory_20250818 = createProviderToolFactory({
4256
+ id: "anthropic.memory_20250818",
4257
+ inputSchema: memory_20250818InputSchema
4258
+ });
4259
+ var textEditor_20241022InputSchema = lazySchema(
4260
+ () => zodSchema(
4261
+ object({
4262
+ command: _enum(["view", "create", "str_replace", "insert", "undo_edit"]),
4263
+ path: string(),
4264
+ file_text: string().optional(),
4265
+ insert_line: number().int().optional(),
4266
+ new_str: string().optional(),
4267
+ insert_text: string().optional(),
4268
+ old_str: string().optional(),
4269
+ view_range: array(number().int()).optional()
4270
+ })
4271
+ )
4272
+ );
4273
+ var textEditor_20241022 = createProviderToolFactory({
4274
+ id: "anthropic.text_editor_20241022",
4275
+ inputSchema: textEditor_20241022InputSchema
4276
+ });
4277
+ var textEditor_20250124InputSchema = lazySchema(
4278
+ () => zodSchema(
4279
+ object({
4280
+ command: _enum(["view", "create", "str_replace", "insert", "undo_edit"]),
4281
+ path: string(),
4282
+ file_text: string().optional(),
4283
+ insert_line: number().int().optional(),
4284
+ new_str: string().optional(),
4285
+ insert_text: string().optional(),
4286
+ old_str: string().optional(),
4287
+ view_range: array(number().int()).optional()
4288
+ })
4289
+ )
4290
+ );
4291
+ var textEditor_20250124 = createProviderToolFactory({
4292
+ id: "anthropic.text_editor_20250124",
4293
+ inputSchema: textEditor_20250124InputSchema
4294
+ });
4295
+ var textEditor_20250429InputSchema = lazySchema(
4296
+ () => zodSchema(
4297
+ object({
4298
+ command: _enum(["view", "create", "str_replace", "insert"]),
4299
+ path: string(),
4300
+ file_text: string().optional(),
4301
+ insert_line: number().int().optional(),
4302
+ new_str: string().optional(),
4303
+ insert_text: string().optional(),
4304
+ old_str: string().optional(),
4305
+ view_range: array(number().int()).optional()
4306
+ })
4307
+ )
4308
+ );
4309
+ var textEditor_20250429 = createProviderToolFactory({
4310
+ id: "anthropic.text_editor_20250429",
4311
+ inputSchema: textEditor_20250429InputSchema
4312
+ });
4313
+ var toolSearchBm25_20251119OutputSchema = lazySchema(
4314
+ () => zodSchema(
4315
+ array(
4316
+ object({
4317
+ type: literal("tool_reference"),
4318
+ toolName: string()
4319
+ })
4320
+ )
4321
+ )
4322
+ );
4323
+ var toolSearchBm25_20251119InputSchema = lazySchema(
4324
+ () => zodSchema(
4325
+ object({
4326
+ /**
4327
+ * A natural language query to search for tools.
4328
+ * Claude will use BM25 text search to find relevant tools.
4329
+ */
4330
+ query: string(),
4331
+ /**
4332
+ * Maximum number of tools to return. Optional.
4333
+ */
4334
+ limit: number().optional()
4335
+ })
4336
+ )
4337
+ );
4338
+ var factory7 = createProviderToolFactoryWithOutputSchema({
4339
+ id: "anthropic.tool_search_bm25_20251119",
4340
+ inputSchema: toolSearchBm25_20251119InputSchema,
4341
+ outputSchema: toolSearchBm25_20251119OutputSchema,
4342
+ supportsDeferredResults: true
4343
+ });
4344
+ var toolSearchBm25_20251119 = (args = {}) => {
4345
+ return factory7(args);
4346
+ };
4347
+ var anthropicTools = {
4348
+ /**
4349
+ * The bash tool enables Claude to execute shell commands in a persistent bash session,
4350
+ * allowing system operations, script execution, and command-line automation.
4351
+ *
4352
+ * Image results are supported.
4353
+ */
4354
+ bash_20241022,
4355
+ /**
4356
+ * The bash tool enables Claude to execute shell commands in a persistent bash session,
4357
+ * allowing system operations, script execution, and command-line automation.
4358
+ *
4359
+ * Image results are supported.
4360
+ */
4361
+ bash_20250124,
4362
+ /**
4363
+ * Claude can analyze data, create visualizations, perform complex calculations,
4364
+ * run system commands, create and edit files, and process uploaded files directly within
4365
+ * the API conversation.
4366
+ *
4367
+ * The code execution tool allows Claude to run Bash commands and manipulate files,
4368
+ * including writing code, in a secure, sandboxed environment.
4369
+ */
4370
+ codeExecution_20250522,
4371
+ /**
4372
+ * Claude can analyze data, create visualizations, perform complex calculations,
4373
+ * run system commands, create and edit files, and process uploaded files directly within
4374
+ * the API conversation.
4375
+ *
4376
+ * The code execution tool allows Claude to run both Python and Bash commands and manipulate files,
4377
+ * including writing code, in a secure, sandboxed environment.
4378
+ *
4379
+ * This is the latest version with enhanced Bash support and file operations.
4380
+ */
4381
+ codeExecution_20250825,
4382
+ /**
4383
+ * Claude can interact with computer environments through the computer use tool, which
4384
+ * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
4385
+ *
4386
+ * Image results are supported.
4387
+ *
4388
+ * @param displayWidthPx - The width of the display being controlled by the model in pixels.
4389
+ * @param displayHeightPx - The height of the display being controlled by the model in pixels.
4390
+ * @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.
4391
+ */
4392
+ computer_20241022,
4393
+ /**
4394
+ * Claude can interact with computer environments through the computer use tool, which
4395
+ * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
4396
+ *
4397
+ * Image results are supported.
4398
+ *
4399
+ * @param displayWidthPx - The width of the display being controlled by the model in pixels.
4400
+ * @param displayHeightPx - The height of the display being controlled by the model in pixels.
4401
+ * @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.
4402
+ */
4403
+ computer_20250124,
4404
+ /**
4405
+ * Claude can interact with computer environments through the computer use tool, which
4406
+ * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
4407
+ *
4408
+ * This version adds the zoom action for detailed screen region inspection.
4409
+ *
4410
+ * Image results are supported.
4411
+ *
4412
+ * Supported models: Claude Opus 4.5
4413
+ *
4414
+ * @param displayWidthPx - The width of the display being controlled by the model in pixels.
4415
+ * @param displayHeightPx - The height of the display being controlled by the model in pixels.
4416
+ * @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.
4417
+ * @param enableZoom - Enable zoom action. Set to true to allow Claude to zoom into specific screen regions. Default: false.
4418
+ */
4419
+ computer_20251124,
4420
+ /**
4421
+ * The memory tool enables Claude to store and retrieve information across conversations through a memory file directory.
4422
+ * Claude can create, read, update, and delete files that persist between sessions,
4423
+ * allowing it to build knowledge over time without keeping everything in the context window.
4424
+ * The memory tool operates client-side—you control where and how the data is stored through your own infrastructure.
4425
+ *
4426
+ * Supported models: Claude Sonnet 4.5, Claude Sonnet 4, Claude Opus 4.1, Claude Opus 4.
4427
+ */
4428
+ memory_20250818,
4429
+ /**
4430
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files,
4431
+ * helping you debug, fix, and improve your code or other text documents. This allows Claude
4432
+ * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
4433
+ *
4434
+ * Supported models: Claude Sonnet 3.5
4435
+ */
4436
+ textEditor_20241022,
4437
+ /**
4438
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files,
4439
+ * helping you debug, fix, and improve your code or other text documents. This allows Claude
4440
+ * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
4441
+ *
4442
+ * Supported models: Claude Sonnet 3.7
4443
+ */
4444
+ textEditor_20250124,
4445
+ /**
4446
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files,
4447
+ * helping you debug, fix, and improve your code or other text documents. This allows Claude
4448
+ * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
4449
+ *
4450
+ * Note: This version does not support the "undo_edit" command.
4451
+ *
4452
+ * @deprecated Use textEditor_20250728 instead
4453
+ */
4454
+ textEditor_20250429,
4455
+ /**
4456
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files,
4457
+ * helping you debug, fix, and improve your code or other text documents. This allows Claude
4458
+ * to directly interact with your files, providing hands-on assistance rather than just suggesting changes.
4459
+ *
4460
+ * Note: This version does not support the "undo_edit" command and adds optional max_characters parameter.
4461
+ *
4462
+ * Supported models: Claude Sonnet 4, Opus 4, and Opus 4.1
4463
+ *
4464
+ * @param maxCharacters - Optional maximum number of characters to view in the file
4465
+ */
4466
+ textEditor_20250728,
4467
+ /**
4468
+ * Creates a web fetch tool that gives Claude direct access to real-time web content.
4469
+ *
4470
+ * @param maxUses - The max_uses parameter limits the number of web fetches performed
4471
+ * @param allowedDomains - Only fetch from these domains
4472
+ * @param blockedDomains - Never fetch from these domains
4473
+ * @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.
4474
+ * @param maxContentTokens - The max_content_tokens parameter limits the amount of content that will be included in the context.
4475
+ */
4476
+ webFetch_20250910,
4477
+ /**
4478
+ * Creates a web search tool that gives Claude direct access to real-time web content.
4479
+ *
4480
+ * @param maxUses - Maximum number of web searches Claude can perform during the conversation.
4481
+ * @param allowedDomains - Optional list of domains that Claude is allowed to search.
4482
+ * @param blockedDomains - Optional list of domains that Claude should avoid when searching.
4483
+ * @param userLocation - Optional user location information to provide geographically relevant search results.
4484
+ */
4485
+ webSearch_20250305,
4486
+ /**
4487
+ * Creates a tool search tool that uses regex patterns to find tools.
4488
+ *
4489
+ * The tool search tool enables Claude to work with hundreds or thousands of tools
4490
+ * by dynamically discovering and loading them on-demand. Instead of loading all
4491
+ * tool definitions into the context window upfront, Claude searches your tool
4492
+ * catalog and loads only the tools it needs.
4493
+ *
4494
+ * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools
4495
+ * to mark them for deferred loading.
4496
+ *
4497
+ * Supported models: Claude Opus 4.5, Claude Sonnet 4.5
4498
+ */
4499
+ toolSearchRegex_20251119,
4500
+ /**
4501
+ * Creates a tool search tool that uses BM25 (natural language) to find tools.
4502
+ *
4503
+ * The tool search tool enables Claude to work with hundreds or thousands of tools
4504
+ * by dynamically discovering and loading them on-demand. Instead of loading all
4505
+ * tool definitions into the context window upfront, Claude searches your tool
4506
+ * catalog and loads only the tools it needs.
4507
+ *
4508
+ * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools
4509
+ * to mark them for deferred loading.
4510
+ *
4511
+ * Supported models: Claude Opus 4.5, Claude Sonnet 4.5
4512
+ */
4513
+ toolSearchBm25_20251119
4514
+ };
4515
+ function createAnthropic(options = {}) {
4516
+ var _a, _b;
4517
+ const baseURL = (_a = withoutTrailingSlash(
4518
+ loadOptionalSetting({
4519
+ settingValue: options.baseURL,
4520
+ environmentVariableName: "ANTHROPIC_BASE_URL"
4521
+ })
4522
+ )) != null ? _a : "https://api.anthropic.com/v1";
4523
+ const providerName = (_b = options.name) != null ? _b : "anthropic.messages";
4524
+ if (options.apiKey && options.authToken) {
4525
+ throw new InvalidArgumentError({
4526
+ argument: "apiKey/authToken",
4527
+ message: "Both apiKey and authToken were provided. Please use only one authentication method."
4528
+ });
4529
+ }
4530
+ const getHeaders = () => {
4531
+ const authHeaders = options.authToken ? { Authorization: `Bearer ${options.authToken}` } : {
4532
+ "x-api-key": loadApiKey({
4533
+ apiKey: options.apiKey,
4534
+ environmentVariableName: "ANTHROPIC_API_KEY",
4535
+ description: "Anthropic"
4536
+ })
4537
+ };
4538
+ return withUserAgentSuffix(
4539
+ {
4540
+ "anthropic-version": "2023-06-01",
4541
+ ...authHeaders,
4542
+ ...options.headers
4543
+ },
4544
+ `ai-sdk/anthropic/${VERSION}`
4545
+ );
4546
+ };
4547
+ const createChatModel = (modelId) => {
4548
+ var _a2;
4549
+ return new AnthropicMessagesLanguageModel(modelId, {
4550
+ provider: providerName,
4551
+ baseURL,
4552
+ headers: getHeaders,
4553
+ fetch: options.fetch,
4554
+ generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
4555
+ supportedUrls: () => ({
4556
+ "image/*": [/^https?:\/\/.*$/],
4557
+ "application/pdf": [/^https?:\/\/.*$/]
4558
+ })
4559
+ });
4560
+ };
4561
+ const provider = function(modelId) {
4562
+ if (new.target) {
4563
+ throw new Error(
4564
+ "The Anthropic model function cannot be called with the new keyword."
4565
+ );
4566
+ }
4567
+ return createChatModel(modelId);
4568
+ };
4569
+ provider.specificationVersion = "v3";
4570
+ provider.languageModel = createChatModel;
4571
+ provider.chat = createChatModel;
4572
+ provider.messages = createChatModel;
4573
+ provider.embeddingModel = (modelId) => {
4574
+ throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
4575
+ };
4576
+ provider.textEmbeddingModel = provider.embeddingModel;
4577
+ provider.imageModel = (modelId) => {
4578
+ throw new NoSuchModelError({ modelId, modelType: "imageModel" });
4579
+ };
4580
+ provider.tools = anthropicTools;
4581
+ return provider;
4582
+ }
4583
+ createAnthropic();
4584
+ export {
4585
+ VERSION,
4586
+ createAnthropic
4587
+ };