@mastra/server 0.20.1-alpha.3 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/{chunk-TMU7NSW7.js → chunk-HKW2536J.js} +5852 -2557
  3. package/dist/chunk-HKW2536J.js.map +1 -0
  4. package/dist/{chunk-AFJBHPHA.cjs → chunk-KJJA7GPJ.cjs} +6308 -2994
  5. package/dist/chunk-KJJA7GPJ.cjs.map +1 -0
  6. package/dist/server/handlers/agent-builder.cjs +16 -16
  7. package/dist/server/handlers/agent-builder.js +1 -1
  8. package/dist/server/handlers.cjs +2 -2
  9. package/dist/server/handlers.js +1 -1
  10. package/package.json +6 -6
  11. package/dist/chunk-44GFD2TF.js +0 -419
  12. package/dist/chunk-44GFD2TF.js.map +0 -1
  13. package/dist/chunk-75KU7JB6.cjs +0 -588
  14. package/dist/chunk-75KU7JB6.cjs.map +0 -1
  15. package/dist/chunk-77TGJGDW.cjs +0 -1279
  16. package/dist/chunk-77TGJGDW.cjs.map +0 -1
  17. package/dist/chunk-AFJBHPHA.cjs.map +0 -1
  18. package/dist/chunk-CHDN4NEY.js +0 -1277
  19. package/dist/chunk-CHDN4NEY.js.map +0 -1
  20. package/dist/chunk-EAIAF7Z6.js +0 -571
  21. package/dist/chunk-EAIAF7Z6.js.map +0 -1
  22. package/dist/chunk-TMU7NSW7.js.map +0 -1
  23. package/dist/chunk-WO2SYFUI.js +0 -5945
  24. package/dist/chunk-WO2SYFUI.js.map +0 -1
  25. package/dist/chunk-XCR65STK.cjs +0 -433
  26. package/dist/chunk-XCR65STK.cjs.map +0 -1
  27. package/dist/chunk-YWACVZRO.cjs +0 -5985
  28. package/dist/chunk-YWACVZRO.cjs.map +0 -1
  29. package/dist/dist-36GPHJSB.cjs +0 -2014
  30. package/dist/dist-36GPHJSB.cjs.map +0 -1
  31. package/dist/dist-3WEYC4YO.js +0 -2007
  32. package/dist/dist-3WEYC4YO.js.map +0 -1
  33. package/dist/dist-7MBYKZSM.js +0 -846
  34. package/dist/dist-7MBYKZSM.js.map +0 -1
  35. package/dist/dist-FGYSUA65.cjs +0 -935
  36. package/dist/dist-FGYSUA65.cjs.map +0 -1
  37. package/dist/dist-FNKPY5I5.cjs +0 -1412
  38. package/dist/dist-FNKPY5I5.cjs.map +0 -1
  39. package/dist/dist-H5ZHQKYG.js +0 -3
  40. package/dist/dist-H5ZHQKYG.js.map +0 -1
  41. package/dist/dist-HBUYSRRO.cjs +0 -850
  42. package/dist/dist-HBUYSRRO.cjs.map +0 -1
  43. package/dist/dist-IUCBLZK6.js +0 -1409
  44. package/dist/dist-IUCBLZK6.js.map +0 -1
  45. package/dist/dist-M4HXCUXC.cjs +0 -20
  46. package/dist/dist-M4HXCUXC.cjs.map +0 -1
  47. package/dist/dist-P32YPL35.js +0 -932
  48. package/dist/dist-P32YPL35.js.map +0 -1
@@ -1,2007 +0,0 @@
1
- import { createJsonErrorResponseHandler, createProviderDefinedToolFactoryWithOutputSchema, createProviderDefinedToolFactory, withoutTrailingSlash, generateId, loadApiKey, parseProviderOptions, combineHeaders, resolve, postJsonToApi, createJsonResponseHandler, createEventSourceResponseHandler, convertToBase64 } from './chunk-EAIAF7Z6.js';
2
- import { UnsupportedFunctionalityError, NoSuchModelError } from './chunk-44GFD2TF.js';
3
- import z6, { z } from 'zod/v4';
4
-
5
- var anthropicErrorDataSchema = z.object({
6
- type: z.literal("error"),
7
- error: z.object({
8
- type: z.string(),
9
- message: z.string()
10
- })
11
- });
12
- var anthropicFailedResponseHandler = createJsonErrorResponseHandler({
13
- errorSchema: anthropicErrorDataSchema,
14
- errorToMessage: (data) => data.error.message
15
- });
16
- var anthropicFilePartProviderOptions = z.object({
17
- /**
18
- * Citation configuration for this document.
19
- * When enabled, this document will generate citations in the response.
20
- */
21
- citations: z.object({
22
- /**
23
- * Enable citations for this document
24
- */
25
- enabled: z.boolean()
26
- }).optional(),
27
- /**
28
- * Custom title for the document.
29
- * If not provided, the filename will be used.
30
- */
31
- title: z.string().optional(),
32
- /**
33
- * Context about the document that will be passed to the model
34
- * but not used towards cited content.
35
- * Useful for storing document metadata as text or stringified JSON.
36
- */
37
- context: z.string().optional()
38
- });
39
- var anthropicProviderOptions = z.object({
40
- sendReasoning: z.boolean().optional(),
41
- thinking: z.object({
42
- type: z.union([z.literal("enabled"), z.literal("disabled")]),
43
- budgetTokens: z.number().optional()
44
- }).optional(),
45
- /**
46
- * Whether to disable parallel function calling during tool use. Default is false.
47
- * When set to true, Claude will use at most one tool per response.
48
- */
49
- disableParallelToolUse: z.boolean().optional()
50
- });
51
- function getCacheControl(providerMetadata) {
52
- var _a;
53
- const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic;
54
- const cacheControlValue = (_a = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a : anthropic2 == null ? void 0 : anthropic2.cache_control;
55
- return cacheControlValue;
56
- }
57
- var webSearch_20250305ArgsSchema = z.object({
58
- /**
59
- * Maximum number of web searches Claude can perform during the conversation.
60
- */
61
- maxUses: z.number().optional(),
62
- /**
63
- * Optional list of domains that Claude is allowed to search.
64
- */
65
- allowedDomains: z.array(z.string()).optional(),
66
- /**
67
- * Optional list of domains that Claude should avoid when searching.
68
- */
69
- blockedDomains: z.array(z.string()).optional(),
70
- /**
71
- * Optional user location information to provide geographically relevant search results.
72
- */
73
- userLocation: z.object({
74
- type: z.literal("approximate"),
75
- city: z.string().optional(),
76
- region: z.string().optional(),
77
- country: z.string().optional(),
78
- timezone: z.string().optional()
79
- }).optional()
80
- });
81
- var webSearch_20250305OutputSchema = z.array(
82
- z.object({
83
- url: z.string(),
84
- title: z.string(),
85
- pageAge: z.string().nullable(),
86
- encryptedContent: z.string(),
87
- type: z.string()
88
- })
89
- );
90
- var factory = createProviderDefinedToolFactoryWithOutputSchema({
91
- id: "anthropic.web_search_20250305",
92
- name: "web_search",
93
- inputSchema: z.object({
94
- query: z.string()
95
- }),
96
- outputSchema: webSearch_20250305OutputSchema
97
- });
98
- var webSearch_20250305 = (args = {}) => {
99
- return factory(args);
100
- };
101
- function isWebSearchTool(tool) {
102
- return typeof tool === "object" && tool !== null && "type" in tool && tool.type === "web_search_20250305";
103
- }
104
- function prepareTools({
105
- tools,
106
- toolChoice,
107
- disableParallelToolUse
108
- }) {
109
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
110
- const toolWarnings = [];
111
- const betas = /* @__PURE__ */ new Set();
112
- if (tools == null) {
113
- return { tools: void 0, toolChoice: void 0, toolWarnings, betas };
114
- }
115
- const anthropicTools2 = [];
116
- for (const tool of tools) {
117
- if (isWebSearchTool(tool)) {
118
- anthropicTools2.push(tool);
119
- continue;
120
- }
121
- switch (tool.type) {
122
- case "function":
123
- const cacheControl = getCacheControl(tool.providerOptions);
124
- anthropicTools2.push({
125
- name: tool.name,
126
- description: tool.description,
127
- input_schema: tool.inputSchema,
128
- cache_control: cacheControl
129
- });
130
- break;
131
- case "provider-defined":
132
- switch (tool.id) {
133
- case "anthropic.computer_20250124":
134
- betas.add("computer-use-2025-01-24");
135
- anthropicTools2.push({
136
- name: "computer",
137
- type: "computer_20250124",
138
- display_width_px: tool.args.displayWidthPx,
139
- display_height_px: tool.args.displayHeightPx,
140
- display_number: tool.args.displayNumber
141
- });
142
- break;
143
- case "anthropic.computer_20241022":
144
- betas.add("computer-use-2024-10-22");
145
- anthropicTools2.push({
146
- name: "computer",
147
- type: "computer_20241022",
148
- display_width_px: tool.args.displayWidthPx,
149
- display_height_px: tool.args.displayHeightPx,
150
- display_number: tool.args.displayNumber
151
- });
152
- break;
153
- case "anthropic.text_editor_20250124":
154
- betas.add("computer-use-2025-01-24");
155
- anthropicTools2.push({
156
- name: "str_replace_editor",
157
- type: "text_editor_20250124"
158
- });
159
- break;
160
- case "anthropic.text_editor_20241022":
161
- betas.add("computer-use-2024-10-22");
162
- anthropicTools2.push({
163
- name: "str_replace_editor",
164
- type: "text_editor_20241022"
165
- });
166
- break;
167
- case "anthropic.text_editor_20250429":
168
- betas.add("computer-use-2025-01-24");
169
- anthropicTools2.push({
170
- name: "str_replace_based_edit_tool",
171
- type: "text_editor_20250429"
172
- });
173
- break;
174
- case "anthropic.bash_20250124":
175
- betas.add("computer-use-2025-01-24");
176
- anthropicTools2.push({
177
- name: "bash",
178
- type: "bash_20250124"
179
- });
180
- break;
181
- case "anthropic.bash_20241022":
182
- betas.add("computer-use-2024-10-22");
183
- anthropicTools2.push({
184
- name: "bash",
185
- type: "bash_20241022"
186
- });
187
- break;
188
- case "anthropic.web_search_20250305": {
189
- const args = webSearch_20250305ArgsSchema.parse(tool.args);
190
- anthropicTools2.push({
191
- type: "web_search_20250305",
192
- name: "web_search",
193
- max_uses: args.maxUses,
194
- allowed_domains: args.allowedDomains,
195
- blocked_domains: args.blockedDomains,
196
- user_location: args.userLocation
197
- });
198
- break;
199
- }
200
- case "anthropic.code_execution_20250522": {
201
- betas.add("code-execution-2025-05-22");
202
- anthropicTools2.push({
203
- type: "code_execution_20250522",
204
- name: "code_execution"
205
- });
206
- break;
207
- }
208
- default:
209
- toolWarnings.push({ type: "unsupported-tool", tool });
210
- break;
211
- }
212
- break;
213
- default:
214
- toolWarnings.push({ type: "unsupported-tool", tool });
215
- break;
216
- }
217
- }
218
- if (toolChoice == null) {
219
- return {
220
- tools: anthropicTools2,
221
- toolChoice: disableParallelToolUse ? { type: "auto", disable_parallel_tool_use: disableParallelToolUse } : void 0,
222
- toolWarnings,
223
- betas
224
- };
225
- }
226
- const type = toolChoice.type;
227
- switch (type) {
228
- case "auto":
229
- return {
230
- tools: anthropicTools2,
231
- toolChoice: {
232
- type: "auto",
233
- disable_parallel_tool_use: disableParallelToolUse
234
- },
235
- toolWarnings,
236
- betas
237
- };
238
- case "required":
239
- return {
240
- tools: anthropicTools2,
241
- toolChoice: {
242
- type: "any",
243
- disable_parallel_tool_use: disableParallelToolUse
244
- },
245
- toolWarnings,
246
- betas
247
- };
248
- case "none":
249
- return { tools: void 0, toolChoice: void 0, toolWarnings, betas };
250
- case "tool":
251
- return {
252
- tools: anthropicTools2,
253
- toolChoice: {
254
- type: "tool",
255
- name: toolChoice.toolName,
256
- disable_parallel_tool_use: disableParallelToolUse
257
- },
258
- toolWarnings,
259
- betas
260
- };
261
- default: {
262
- const _exhaustiveCheck = type;
263
- throw new UnsupportedFunctionalityError({
264
- functionality: `tool choice type: ${_exhaustiveCheck}`
265
- });
266
- }
267
- }
268
- }
269
- var codeExecution_20250522OutputSchema = z.object({
270
- type: z.literal("code_execution_result"),
271
- stdout: z.string(),
272
- stderr: z.string(),
273
- return_code: z.number()
274
- });
275
- var factory2 = createProviderDefinedToolFactoryWithOutputSchema({
276
- id: "anthropic.code_execution_20250522",
277
- name: "code_execution",
278
- inputSchema: z.object({
279
- code: z.string()
280
- }),
281
- outputSchema: codeExecution_20250522OutputSchema
282
- });
283
- var codeExecution_20250522 = (args = {}) => {
284
- return factory2(args);
285
- };
286
- function convertToString(data) {
287
- if (typeof data === "string") {
288
- return Buffer.from(data, "base64").toString("utf-8");
289
- }
290
- if (data instanceof Uint8Array) {
291
- return new TextDecoder().decode(data);
292
- }
293
- if (data instanceof URL) {
294
- throw new UnsupportedFunctionalityError({
295
- functionality: "URL-based text documents are not supported for citations"
296
- });
297
- }
298
- throw new UnsupportedFunctionalityError({
299
- functionality: `unsupported data type for text documents: ${typeof data}`
300
- });
301
- }
302
- async function convertToAnthropicMessagesPrompt({
303
- prompt,
304
- sendReasoning,
305
- warnings
306
- }) {
307
- var _a, _b, _c, _d, _e;
308
- const betas = /* @__PURE__ */ new Set();
309
- const blocks = groupIntoBlocks(prompt);
310
- let system = void 0;
311
- const messages = [];
312
- async function shouldEnableCitations(providerMetadata) {
313
- var _a2, _b2;
314
- const anthropicOptions = await parseProviderOptions({
315
- provider: "anthropic",
316
- providerOptions: providerMetadata,
317
- schema: anthropicFilePartProviderOptions
318
- });
319
- return (_b2 = (_a2 = anthropicOptions == null ? void 0 : anthropicOptions.citations) == null ? void 0 : _a2.enabled) != null ? _b2 : false;
320
- }
321
- async function getDocumentMetadata(providerMetadata) {
322
- const anthropicOptions = await parseProviderOptions({
323
- provider: "anthropic",
324
- providerOptions: providerMetadata,
325
- schema: anthropicFilePartProviderOptions
326
- });
327
- return {
328
- title: anthropicOptions == null ? void 0 : anthropicOptions.title,
329
- context: anthropicOptions == null ? void 0 : anthropicOptions.context
330
- };
331
- }
332
- for (let i = 0; i < blocks.length; i++) {
333
- const block = blocks[i];
334
- const isLastBlock = i === blocks.length - 1;
335
- const type = block.type;
336
- switch (type) {
337
- case "system": {
338
- if (system != null) {
339
- throw new UnsupportedFunctionalityError({
340
- functionality: "Multiple system messages that are separated by user/assistant messages"
341
- });
342
- }
343
- system = block.messages.map(({ content, providerOptions }) => ({
344
- type: "text",
345
- text: content,
346
- cache_control: getCacheControl(providerOptions)
347
- }));
348
- break;
349
- }
350
- case "user": {
351
- const anthropicContent = [];
352
- for (const message of block.messages) {
353
- const { role, content } = message;
354
- switch (role) {
355
- case "user": {
356
- for (let j = 0; j < content.length; j++) {
357
- const part = content[j];
358
- const isLastPart = j === content.length - 1;
359
- const cacheControl = (_a = getCacheControl(part.providerOptions)) != null ? _a : isLastPart ? getCacheControl(message.providerOptions) : void 0;
360
- switch (part.type) {
361
- case "text": {
362
- anthropicContent.push({
363
- type: "text",
364
- text: part.text,
365
- cache_control: cacheControl
366
- });
367
- break;
368
- }
369
- case "file": {
370
- if (part.mediaType.startsWith("image/")) {
371
- anthropicContent.push({
372
- type: "image",
373
- source: part.data instanceof URL ? {
374
- type: "url",
375
- url: part.data.toString()
376
- } : {
377
- type: "base64",
378
- media_type: part.mediaType === "image/*" ? "image/jpeg" : part.mediaType,
379
- data: convertToBase64(part.data)
380
- },
381
- cache_control: cacheControl
382
- });
383
- } else if (part.mediaType === "application/pdf") {
384
- betas.add("pdfs-2024-09-25");
385
- const enableCitations = await shouldEnableCitations(
386
- part.providerOptions
387
- );
388
- const metadata = await getDocumentMetadata(
389
- part.providerOptions
390
- );
391
- anthropicContent.push({
392
- type: "document",
393
- source: part.data instanceof URL ? {
394
- type: "url",
395
- url: part.data.toString()
396
- } : {
397
- type: "base64",
398
- media_type: "application/pdf",
399
- data: convertToBase64(part.data)
400
- },
401
- title: (_b = metadata.title) != null ? _b : part.filename,
402
- ...metadata.context && { context: metadata.context },
403
- ...enableCitations && {
404
- citations: { enabled: true }
405
- },
406
- cache_control: cacheControl
407
- });
408
- } else if (part.mediaType === "text/plain") {
409
- const enableCitations = await shouldEnableCitations(
410
- part.providerOptions
411
- );
412
- const metadata = await getDocumentMetadata(
413
- part.providerOptions
414
- );
415
- anthropicContent.push({
416
- type: "document",
417
- source: part.data instanceof URL ? {
418
- type: "url",
419
- url: part.data.toString()
420
- } : {
421
- type: "text",
422
- media_type: "text/plain",
423
- data: convertToString(part.data)
424
- },
425
- title: (_c = metadata.title) != null ? _c : part.filename,
426
- ...metadata.context && { context: metadata.context },
427
- ...enableCitations && {
428
- citations: { enabled: true }
429
- },
430
- cache_control: cacheControl
431
- });
432
- } else {
433
- throw new UnsupportedFunctionalityError({
434
- functionality: `media type: ${part.mediaType}`
435
- });
436
- }
437
- break;
438
- }
439
- }
440
- }
441
- break;
442
- }
443
- case "tool": {
444
- for (let i2 = 0; i2 < content.length; i2++) {
445
- const part = content[i2];
446
- const isLastPart = i2 === content.length - 1;
447
- const cacheControl = (_d = getCacheControl(part.providerOptions)) != null ? _d : isLastPart ? getCacheControl(message.providerOptions) : void 0;
448
- const output = part.output;
449
- let contentValue;
450
- switch (output.type) {
451
- case "content":
452
- contentValue = output.value.map((contentPart) => {
453
- switch (contentPart.type) {
454
- case "text":
455
- return {
456
- type: "text",
457
- text: contentPart.text,
458
- cache_control: void 0
459
- };
460
- case "media": {
461
- if (contentPart.mediaType.startsWith("image/")) {
462
- return {
463
- type: "image",
464
- source: {
465
- type: "base64",
466
- media_type: contentPart.mediaType,
467
- data: contentPart.data
468
- },
469
- cache_control: void 0
470
- };
471
- }
472
- throw new UnsupportedFunctionalityError({
473
- functionality: `media type: ${contentPart.mediaType}`
474
- });
475
- }
476
- }
477
- });
478
- break;
479
- case "text":
480
- case "error-text":
481
- contentValue = output.value;
482
- break;
483
- case "json":
484
- case "error-json":
485
- default:
486
- contentValue = JSON.stringify(output.value);
487
- break;
488
- }
489
- anthropicContent.push({
490
- type: "tool_result",
491
- tool_use_id: part.toolCallId,
492
- content: contentValue,
493
- is_error: output.type === "error-text" || output.type === "error-json" ? true : void 0,
494
- cache_control: cacheControl
495
- });
496
- }
497
- break;
498
- }
499
- default: {
500
- const _exhaustiveCheck = role;
501
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
502
- }
503
- }
504
- }
505
- messages.push({ role: "user", content: anthropicContent });
506
- break;
507
- }
508
- case "assistant": {
509
- const anthropicContent = [];
510
- for (let j = 0; j < block.messages.length; j++) {
511
- const message = block.messages[j];
512
- const isLastMessage = j === block.messages.length - 1;
513
- const { content } = message;
514
- for (let k = 0; k < content.length; k++) {
515
- const part = content[k];
516
- const isLastContentPart = k === content.length - 1;
517
- const cacheControl = (_e = getCacheControl(part.providerOptions)) != null ? _e : isLastContentPart ? getCacheControl(message.providerOptions) : void 0;
518
- switch (part.type) {
519
- case "text": {
520
- anthropicContent.push({
521
- type: "text",
522
- text: (
523
- // trim the last text part if it's the last message in the block
524
- // because Anthropic does not allow trailing whitespace
525
- // in pre-filled assistant responses
526
- isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text
527
- ),
528
- cache_control: cacheControl
529
- });
530
- break;
531
- }
532
- case "reasoning": {
533
- if (sendReasoning) {
534
- const reasoningMetadata = await parseProviderOptions({
535
- provider: "anthropic",
536
- providerOptions: part.providerOptions,
537
- schema: anthropicReasoningMetadataSchema
538
- });
539
- if (reasoningMetadata != null) {
540
- if (reasoningMetadata.signature != null) {
541
- anthropicContent.push({
542
- type: "thinking",
543
- thinking: part.text,
544
- signature: reasoningMetadata.signature,
545
- cache_control: cacheControl
546
- });
547
- } else if (reasoningMetadata.redactedData != null) {
548
- anthropicContent.push({
549
- type: "redacted_thinking",
550
- data: reasoningMetadata.redactedData,
551
- cache_control: cacheControl
552
- });
553
- } else {
554
- warnings.push({
555
- type: "other",
556
- message: "unsupported reasoning metadata"
557
- });
558
- }
559
- } else {
560
- warnings.push({
561
- type: "other",
562
- message: "unsupported reasoning metadata"
563
- });
564
- }
565
- } else {
566
- warnings.push({
567
- type: "other",
568
- message: "sending reasoning content is disabled for this model"
569
- });
570
- }
571
- break;
572
- }
573
- case "tool-call": {
574
- if (part.providerExecuted) {
575
- if (part.toolName === "web_search") {
576
- anthropicContent.push({
577
- type: "server_tool_use",
578
- id: part.toolCallId,
579
- name: "web_search",
580
- input: part.input,
581
- cache_control: cacheControl
582
- });
583
- break;
584
- }
585
- if (part.toolName === "code_execution") {
586
- anthropicContent.push({
587
- type: "server_tool_use",
588
- id: part.toolCallId,
589
- name: "code_execution",
590
- input: part.input,
591
- cache_control: cacheControl
592
- });
593
- break;
594
- }
595
- warnings.push({
596
- type: "other",
597
- message: `provider executed tool call for tool ${part.toolName} is not supported`
598
- });
599
- break;
600
- }
601
- anthropicContent.push({
602
- type: "tool_use",
603
- id: part.toolCallId,
604
- name: part.toolName,
605
- input: part.input,
606
- cache_control: cacheControl
607
- });
608
- break;
609
- }
610
- case "tool-result": {
611
- if (part.toolName === "web_search") {
612
- const output = part.output;
613
- if (output.type !== "json") {
614
- warnings.push({
615
- type: "other",
616
- message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
617
- });
618
- break;
619
- }
620
- const webSearchOutput = webSearch_20250305OutputSchema.parse(
621
- output.value
622
- );
623
- anthropicContent.push({
624
- type: "web_search_tool_result",
625
- tool_use_id: part.toolCallId,
626
- content: webSearchOutput.map((result) => ({
627
- url: result.url,
628
- title: result.title,
629
- page_age: result.pageAge,
630
- encrypted_content: result.encryptedContent,
631
- type: result.type
632
- })),
633
- cache_control: cacheControl
634
- });
635
- break;
636
- }
637
- if (part.toolName === "code_execution") {
638
- const output = part.output;
639
- if (output.type !== "json") {
640
- warnings.push({
641
- type: "other",
642
- message: `provider executed tool result output type ${output.type} for tool ${part.toolName} is not supported`
643
- });
644
- break;
645
- }
646
- const codeExecutionOutput = codeExecution_20250522OutputSchema.parse(output.value);
647
- anthropicContent.push({
648
- type: "code_execution_tool_result",
649
- tool_use_id: part.toolCallId,
650
- content: {
651
- type: codeExecutionOutput.type,
652
- stdout: codeExecutionOutput.stdout,
653
- stderr: codeExecutionOutput.stderr,
654
- return_code: codeExecutionOutput.return_code
655
- },
656
- cache_control: cacheControl
657
- });
658
- break;
659
- }
660
- warnings.push({
661
- type: "other",
662
- message: `provider executed tool result for tool ${part.toolName} is not supported`
663
- });
664
- break;
665
- }
666
- }
667
- }
668
- }
669
- messages.push({ role: "assistant", content: anthropicContent });
670
- break;
671
- }
672
- default: {
673
- const _exhaustiveCheck = type;
674
- throw new Error(`content type: ${_exhaustiveCheck}`);
675
- }
676
- }
677
- }
678
- return {
679
- prompt: { system, messages },
680
- betas
681
- };
682
- }
683
- function groupIntoBlocks(prompt) {
684
- const blocks = [];
685
- let currentBlock = void 0;
686
- for (const message of prompt) {
687
- const { role } = message;
688
- switch (role) {
689
- case "system": {
690
- if ((currentBlock == null ? void 0 : currentBlock.type) !== "system") {
691
- currentBlock = { type: "system", messages: [] };
692
- blocks.push(currentBlock);
693
- }
694
- currentBlock.messages.push(message);
695
- break;
696
- }
697
- case "assistant": {
698
- if ((currentBlock == null ? void 0 : currentBlock.type) !== "assistant") {
699
- currentBlock = { type: "assistant", messages: [] };
700
- blocks.push(currentBlock);
701
- }
702
- currentBlock.messages.push(message);
703
- break;
704
- }
705
- case "user": {
706
- if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
707
- currentBlock = { type: "user", messages: [] };
708
- blocks.push(currentBlock);
709
- }
710
- currentBlock.messages.push(message);
711
- break;
712
- }
713
- case "tool": {
714
- if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") {
715
- currentBlock = { type: "user", messages: [] };
716
- blocks.push(currentBlock);
717
- }
718
- currentBlock.messages.push(message);
719
- break;
720
- }
721
- default: {
722
- const _exhaustiveCheck = role;
723
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
724
- }
725
- }
726
- }
727
- return blocks;
728
- }
729
- function mapAnthropicStopReason({
730
- finishReason,
731
- isJsonResponseFromTool
732
- }) {
733
- switch (finishReason) {
734
- case "end_turn":
735
- case "stop_sequence":
736
- return "stop";
737
- case "tool_use":
738
- return isJsonResponseFromTool ? "stop" : "tool-calls";
739
- case "max_tokens":
740
- return "length";
741
- default:
742
- return "unknown";
743
- }
744
- }
745
- var citationSchemas = {
746
- webSearchResult: z.object({
747
- type: z.literal("web_search_result_location"),
748
- cited_text: z.string(),
749
- url: z.string(),
750
- title: z.string(),
751
- encrypted_index: z.string()
752
- }),
753
- pageLocation: z.object({
754
- type: z.literal("page_location"),
755
- cited_text: z.string(),
756
- document_index: z.number(),
757
- document_title: z.string().nullable(),
758
- start_page_number: z.number(),
759
- end_page_number: z.number()
760
- }),
761
- charLocation: z.object({
762
- type: z.literal("char_location"),
763
- cited_text: z.string(),
764
- document_index: z.number(),
765
- document_title: z.string().nullable(),
766
- start_char_index: z.number(),
767
- end_char_index: z.number()
768
- })
769
- };
770
- var citationSchema = z.discriminatedUnion("type", [
771
- citationSchemas.webSearchResult,
772
- citationSchemas.pageLocation,
773
- citationSchemas.charLocation
774
- ]);
775
- z.discriminatedUnion("type", [
776
- citationSchemas.pageLocation,
777
- citationSchemas.charLocation
778
- ]);
779
- function processCitation(citation, citationDocuments, generateId3, onSource) {
780
- if (citation.type === "page_location" || citation.type === "char_location") {
781
- const source = createCitationSource(
782
- citation,
783
- citationDocuments,
784
- generateId3
785
- );
786
- if (source) {
787
- onSource(source);
788
- }
789
- }
790
- }
791
- function createCitationSource(citation, citationDocuments, generateId3) {
792
- var _a;
793
- const documentInfo = citationDocuments[citation.document_index];
794
- if (!documentInfo) {
795
- return null;
796
- }
797
- const providerMetadata = citation.type === "page_location" ? {
798
- citedText: citation.cited_text,
799
- startPageNumber: citation.start_page_number,
800
- endPageNumber: citation.end_page_number
801
- } : {
802
- citedText: citation.cited_text,
803
- startCharIndex: citation.start_char_index,
804
- endCharIndex: citation.end_char_index
805
- };
806
- return {
807
- type: "source",
808
- sourceType: "document",
809
- id: generateId3(),
810
- mediaType: documentInfo.mediaType,
811
- title: (_a = citation.document_title) != null ? _a : documentInfo.title,
812
- filename: documentInfo.filename,
813
- providerMetadata: {
814
- anthropic: providerMetadata
815
- }
816
- };
817
- }
818
- var AnthropicMessagesLanguageModel = class {
819
- constructor(modelId, config) {
820
- this.specificationVersion = "v2";
821
- var _a;
822
- this.modelId = modelId;
823
- this.config = config;
824
- this.generateId = (_a = config.generateId) != null ? _a : generateId;
825
- }
826
- supportsUrl(url) {
827
- return url.protocol === "https:";
828
- }
829
- get provider() {
830
- return this.config.provider;
831
- }
832
- get supportedUrls() {
833
- var _a, _b, _c;
834
- return (_c = (_b = (_a = this.config).supportedUrls) == null ? void 0 : _b.call(_a)) != null ? _c : {};
835
- }
836
- async getArgs({
837
- prompt,
838
- maxOutputTokens = 4096,
839
- // 4096: max model output tokens TODO update default in v5
840
- temperature,
841
- topP,
842
- topK,
843
- frequencyPenalty,
844
- presencePenalty,
845
- stopSequences,
846
- responseFormat,
847
- seed,
848
- tools,
849
- toolChoice,
850
- providerOptions
851
- }) {
852
- var _a, _b, _c;
853
- const warnings = [];
854
- if (frequencyPenalty != null) {
855
- warnings.push({
856
- type: "unsupported-setting",
857
- setting: "frequencyPenalty"
858
- });
859
- }
860
- if (presencePenalty != null) {
861
- warnings.push({
862
- type: "unsupported-setting",
863
- setting: "presencePenalty"
864
- });
865
- }
866
- if (seed != null) {
867
- warnings.push({
868
- type: "unsupported-setting",
869
- setting: "seed"
870
- });
871
- }
872
- if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
873
- if (responseFormat.schema == null) {
874
- warnings.push({
875
- type: "unsupported-setting",
876
- setting: "responseFormat",
877
- details: "JSON response format requires a schema. The response format is ignored."
878
- });
879
- } else if (tools != null) {
880
- warnings.push({
881
- type: "unsupported-setting",
882
- setting: "tools",
883
- details: "JSON response format does not support tools. The provided tools are ignored."
884
- });
885
- }
886
- }
887
- const jsonResponseTool = (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null ? {
888
- type: "function",
889
- name: "json",
890
- description: "Respond with a JSON object.",
891
- inputSchema: responseFormat.schema
892
- } : void 0;
893
- const anthropicOptions = await parseProviderOptions({
894
- provider: "anthropic",
895
- providerOptions,
896
- schema: anthropicProviderOptions
897
- });
898
- const { prompt: messagesPrompt, betas: messagesBetas } = await convertToAnthropicMessagesPrompt({
899
- prompt,
900
- sendReasoning: (_a = anthropicOptions == null ? void 0 : anthropicOptions.sendReasoning) != null ? _a : true,
901
- warnings
902
- });
903
- const isThinking = ((_b = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _b.type) === "enabled";
904
- const thinkingBudget = (_c = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _c.budgetTokens;
905
- const baseArgs = {
906
- // model id:
907
- model: this.modelId,
908
- // standardized settings:
909
- max_tokens: maxOutputTokens,
910
- temperature,
911
- top_k: topK,
912
- top_p: topP,
913
- stop_sequences: stopSequences,
914
- // provider specific settings:
915
- ...isThinking && {
916
- thinking: { type: "enabled", budget_tokens: thinkingBudget }
917
- },
918
- // prompt:
919
- system: messagesPrompt.system,
920
- messages: messagesPrompt.messages
921
- };
922
- if (isThinking) {
923
- if (thinkingBudget == null) {
924
- throw new UnsupportedFunctionalityError({
925
- functionality: "thinking requires a budget"
926
- });
927
- }
928
- if (baseArgs.temperature != null) {
929
- baseArgs.temperature = void 0;
930
- warnings.push({
931
- type: "unsupported-setting",
932
- setting: "temperature",
933
- details: "temperature is not supported when thinking is enabled"
934
- });
935
- }
936
- if (topK != null) {
937
- baseArgs.top_k = void 0;
938
- warnings.push({
939
- type: "unsupported-setting",
940
- setting: "topK",
941
- details: "topK is not supported when thinking is enabled"
942
- });
943
- }
944
- if (topP != null) {
945
- baseArgs.top_p = void 0;
946
- warnings.push({
947
- type: "unsupported-setting",
948
- setting: "topP",
949
- details: "topP is not supported when thinking is enabled"
950
- });
951
- }
952
- baseArgs.max_tokens = maxOutputTokens + thinkingBudget;
953
- }
954
- const {
955
- tools: anthropicTools2,
956
- toolChoice: anthropicToolChoice,
957
- toolWarnings,
958
- betas: toolsBetas
959
- } = prepareTools(
960
- jsonResponseTool != null ? {
961
- tools: [jsonResponseTool],
962
- toolChoice: { type: "tool", toolName: jsonResponseTool.name },
963
- disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse
964
- } : {
965
- tools: tools != null ? tools : [],
966
- toolChoice,
967
- disableParallelToolUse: anthropicOptions == null ? void 0 : anthropicOptions.disableParallelToolUse
968
- }
969
- );
970
- return {
971
- args: {
972
- ...baseArgs,
973
- tools: anthropicTools2,
974
- tool_choice: anthropicToolChoice
975
- },
976
- warnings: [...warnings, ...toolWarnings],
977
- betas: /* @__PURE__ */ new Set([...messagesBetas, ...toolsBetas]),
978
- usesJsonResponseTool: jsonResponseTool != null
979
- };
980
- }
981
- async getHeaders({
982
- betas,
983
- headers
984
- }) {
985
- return combineHeaders(
986
- await resolve(this.config.headers),
987
- betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {},
988
- headers
989
- );
990
- }
991
- buildRequestUrl(isStreaming) {
992
- var _a, _b, _c;
993
- return (_c = (_b = (_a = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`;
994
- }
995
- transformRequestBody(args) {
996
- var _a, _b, _c;
997
- return (_c = (_b = (_a = this.config).transformRequestBody) == null ? void 0 : _b.call(_a, args)) != null ? _c : args;
998
- }
999
- extractCitationDocuments(prompt) {
1000
- const isCitationPart = (part) => {
1001
- var _a, _b;
1002
- if (part.type !== "file") {
1003
- return false;
1004
- }
1005
- if (part.mediaType !== "application/pdf" && part.mediaType !== "text/plain") {
1006
- return false;
1007
- }
1008
- const anthropic2 = (_a = part.providerOptions) == null ? void 0 : _a.anthropic;
1009
- const citationsConfig = anthropic2 == null ? void 0 : anthropic2.citations;
1010
- return (_b = citationsConfig == null ? void 0 : citationsConfig.enabled) != null ? _b : false;
1011
- };
1012
- return prompt.filter((message) => message.role === "user").flatMap((message) => message.content).filter(isCitationPart).map((part) => {
1013
- var _a;
1014
- const filePart = part;
1015
- return {
1016
- title: (_a = filePart.filename) != null ? _a : "Untitled Document",
1017
- filename: filePart.filename,
1018
- mediaType: filePart.mediaType
1019
- };
1020
- });
1021
- }
1022
- async doGenerate(options) {
1023
- var _a, _b, _c, _d, _e;
1024
- const { args, warnings, betas, usesJsonResponseTool } = await this.getArgs(options);
1025
- const citationDocuments = this.extractCitationDocuments(options.prompt);
1026
- const {
1027
- responseHeaders,
1028
- value: response,
1029
- rawValue: rawResponse
1030
- } = await postJsonToApi({
1031
- url: this.buildRequestUrl(false),
1032
- headers: await this.getHeaders({ betas, headers: options.headers }),
1033
- body: this.transformRequestBody(args),
1034
- failedResponseHandler: anthropicFailedResponseHandler,
1035
- successfulResponseHandler: createJsonResponseHandler(
1036
- anthropicMessagesResponseSchema
1037
- ),
1038
- abortSignal: options.abortSignal,
1039
- fetch: this.config.fetch
1040
- });
1041
- const content = [];
1042
- for (const part of response.content) {
1043
- switch (part.type) {
1044
- case "text": {
1045
- if (!usesJsonResponseTool) {
1046
- content.push({ type: "text", text: part.text });
1047
- if (part.citations) {
1048
- for (const citation of part.citations) {
1049
- processCitation(
1050
- citation,
1051
- citationDocuments,
1052
- this.generateId,
1053
- (source) => content.push(source)
1054
- );
1055
- }
1056
- }
1057
- }
1058
- break;
1059
- }
1060
- case "thinking": {
1061
- content.push({
1062
- type: "reasoning",
1063
- text: part.thinking,
1064
- providerMetadata: {
1065
- anthropic: {
1066
- signature: part.signature
1067
- }
1068
- }
1069
- });
1070
- break;
1071
- }
1072
- case "redacted_thinking": {
1073
- content.push({
1074
- type: "reasoning",
1075
- text: "",
1076
- providerMetadata: {
1077
- anthropic: {
1078
- redactedData: part.data
1079
- }
1080
- }
1081
- });
1082
- break;
1083
- }
1084
- case "tool_use": {
1085
- content.push(
1086
- // when a json response tool is used, the tool call becomes the text:
1087
- usesJsonResponseTool ? {
1088
- type: "text",
1089
- text: JSON.stringify(part.input)
1090
- } : {
1091
- type: "tool-call",
1092
- toolCallId: part.id,
1093
- toolName: part.name,
1094
- input: JSON.stringify(part.input)
1095
- }
1096
- );
1097
- break;
1098
- }
1099
- case "server_tool_use": {
1100
- if (part.name === "web_search" || part.name === "code_execution") {
1101
- content.push({
1102
- type: "tool-call",
1103
- toolCallId: part.id,
1104
- toolName: part.name,
1105
- input: JSON.stringify(part.input),
1106
- providerExecuted: true
1107
- });
1108
- }
1109
- break;
1110
- }
1111
- case "web_search_tool_result": {
1112
- if (Array.isArray(part.content)) {
1113
- content.push({
1114
- type: "tool-result",
1115
- toolCallId: part.tool_use_id,
1116
- toolName: "web_search",
1117
- result: part.content.map((result) => {
1118
- var _a2;
1119
- return {
1120
- url: result.url,
1121
- title: result.title,
1122
- pageAge: (_a2 = result.page_age) != null ? _a2 : null,
1123
- encryptedContent: result.encrypted_content,
1124
- type: result.type
1125
- };
1126
- }),
1127
- providerExecuted: true
1128
- });
1129
- for (const result of part.content) {
1130
- content.push({
1131
- type: "source",
1132
- sourceType: "url",
1133
- id: this.generateId(),
1134
- url: result.url,
1135
- title: result.title,
1136
- providerMetadata: {
1137
- anthropic: {
1138
- pageAge: (_a = result.page_age) != null ? _a : null
1139
- }
1140
- }
1141
- });
1142
- }
1143
- } else {
1144
- content.push({
1145
- type: "tool-result",
1146
- toolCallId: part.tool_use_id,
1147
- toolName: "web_search",
1148
- isError: true,
1149
- result: {
1150
- type: "web_search_tool_result_error",
1151
- errorCode: part.content.error_code
1152
- },
1153
- providerExecuted: true
1154
- });
1155
- }
1156
- break;
1157
- }
1158
- case "code_execution_tool_result": {
1159
- if (part.content.type === "code_execution_result") {
1160
- content.push({
1161
- type: "tool-result",
1162
- toolCallId: part.tool_use_id,
1163
- toolName: "code_execution",
1164
- result: {
1165
- type: part.content.type,
1166
- stdout: part.content.stdout,
1167
- stderr: part.content.stderr,
1168
- return_code: part.content.return_code
1169
- },
1170
- providerExecuted: true
1171
- });
1172
- } else if (part.content.type === "code_execution_tool_result_error") {
1173
- content.push({
1174
- type: "tool-result",
1175
- toolCallId: part.tool_use_id,
1176
- toolName: "code_execution",
1177
- isError: true,
1178
- result: {
1179
- type: "code_execution_tool_result_error",
1180
- errorCode: part.content.error_code
1181
- },
1182
- providerExecuted: true
1183
- });
1184
- }
1185
- break;
1186
- }
1187
- }
1188
- }
1189
- return {
1190
- content,
1191
- finishReason: mapAnthropicStopReason({
1192
- finishReason: response.stop_reason,
1193
- isJsonResponseFromTool: usesJsonResponseTool
1194
- }),
1195
- usage: {
1196
- inputTokens: response.usage.input_tokens,
1197
- outputTokens: response.usage.output_tokens,
1198
- totalTokens: response.usage.input_tokens + response.usage.output_tokens,
1199
- cachedInputTokens: (_b = response.usage.cache_read_input_tokens) != null ? _b : void 0
1200
- },
1201
- request: { body: args },
1202
- response: {
1203
- id: (_c = response.id) != null ? _c : void 0,
1204
- modelId: (_d = response.model) != null ? _d : void 0,
1205
- headers: responseHeaders,
1206
- body: rawResponse
1207
- },
1208
- warnings,
1209
- providerMetadata: {
1210
- anthropic: {
1211
- usage: response.usage,
1212
- cacheCreationInputTokens: (_e = response.usage.cache_creation_input_tokens) != null ? _e : null
1213
- }
1214
- }
1215
- };
1216
- }
1217
- async doStream(options) {
1218
- const { args, warnings, betas, usesJsonResponseTool } = await this.getArgs(options);
1219
- const citationDocuments = this.extractCitationDocuments(options.prompt);
1220
- const body = { ...args, stream: true };
1221
- const { responseHeaders, value: response } = await postJsonToApi({
1222
- url: this.buildRequestUrl(true),
1223
- headers: await this.getHeaders({ betas, headers: options.headers }),
1224
- body: this.transformRequestBody(body),
1225
- failedResponseHandler: anthropicFailedResponseHandler,
1226
- successfulResponseHandler: createEventSourceResponseHandler(
1227
- anthropicMessagesChunkSchema
1228
- ),
1229
- abortSignal: options.abortSignal,
1230
- fetch: this.config.fetch
1231
- });
1232
- let finishReason = "unknown";
1233
- const usage = {
1234
- inputTokens: void 0,
1235
- outputTokens: void 0,
1236
- totalTokens: void 0
1237
- };
1238
- const contentBlocks = {};
1239
- let providerMetadata = void 0;
1240
- let blockType = void 0;
1241
- const generateId3 = this.generateId;
1242
- return {
1243
- stream: response.pipeThrough(
1244
- new TransformStream({
1245
- start(controller) {
1246
- controller.enqueue({ type: "stream-start", warnings });
1247
- },
1248
- transform(chunk, controller) {
1249
- var _a, _b, _c, _d, _e, _f, _g;
1250
- if (options.includeRawChunks) {
1251
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
1252
- }
1253
- if (!chunk.success) {
1254
- controller.enqueue({ type: "error", error: chunk.error });
1255
- return;
1256
- }
1257
- const value = chunk.value;
1258
- switch (value.type) {
1259
- case "ping": {
1260
- return;
1261
- }
1262
- case "content_block_start": {
1263
- const contentBlockType = value.content_block.type;
1264
- blockType = contentBlockType;
1265
- switch (contentBlockType) {
1266
- case "text": {
1267
- contentBlocks[value.index] = { type: "text" };
1268
- controller.enqueue({
1269
- type: "text-start",
1270
- id: String(value.index)
1271
- });
1272
- return;
1273
- }
1274
- case "thinking": {
1275
- contentBlocks[value.index] = { type: "reasoning" };
1276
- controller.enqueue({
1277
- type: "reasoning-start",
1278
- id: String(value.index)
1279
- });
1280
- return;
1281
- }
1282
- case "redacted_thinking": {
1283
- contentBlocks[value.index] = { type: "reasoning" };
1284
- controller.enqueue({
1285
- type: "reasoning-start",
1286
- id: String(value.index),
1287
- providerMetadata: {
1288
- anthropic: {
1289
- redactedData: value.content_block.data
1290
- }
1291
- }
1292
- });
1293
- return;
1294
- }
1295
- case "tool_use": {
1296
- contentBlocks[value.index] = usesJsonResponseTool ? { type: "text" } : {
1297
- type: "tool-call",
1298
- toolCallId: value.content_block.id,
1299
- toolName: value.content_block.name,
1300
- input: ""
1301
- };
1302
- controller.enqueue(
1303
- usesJsonResponseTool ? { type: "text-start", id: String(value.index) } : {
1304
- type: "tool-input-start",
1305
- id: value.content_block.id,
1306
- toolName: value.content_block.name
1307
- }
1308
- );
1309
- return;
1310
- }
1311
- case "server_tool_use": {
1312
- if (value.content_block.name === "web_search" || value.content_block.name === "code_execution") {
1313
- contentBlocks[value.index] = {
1314
- type: "tool-call",
1315
- toolCallId: value.content_block.id,
1316
- toolName: value.content_block.name,
1317
- input: "",
1318
- providerExecuted: true
1319
- };
1320
- controller.enqueue({
1321
- type: "tool-input-start",
1322
- id: value.content_block.id,
1323
- toolName: value.content_block.name,
1324
- providerExecuted: true
1325
- });
1326
- }
1327
- return;
1328
- }
1329
- case "web_search_tool_result": {
1330
- const part = value.content_block;
1331
- if (Array.isArray(part.content)) {
1332
- controller.enqueue({
1333
- type: "tool-result",
1334
- toolCallId: part.tool_use_id,
1335
- toolName: "web_search",
1336
- result: part.content.map((result) => {
1337
- var _a2;
1338
- return {
1339
- url: result.url,
1340
- title: result.title,
1341
- pageAge: (_a2 = result.page_age) != null ? _a2 : null,
1342
- encryptedContent: result.encrypted_content,
1343
- type: result.type
1344
- };
1345
- }),
1346
- providerExecuted: true
1347
- });
1348
- for (const result of part.content) {
1349
- controller.enqueue({
1350
- type: "source",
1351
- sourceType: "url",
1352
- id: generateId3(),
1353
- url: result.url,
1354
- title: result.title,
1355
- providerMetadata: {
1356
- anthropic: {
1357
- pageAge: (_a = result.page_age) != null ? _a : null
1358
- }
1359
- }
1360
- });
1361
- }
1362
- } else {
1363
- controller.enqueue({
1364
- type: "tool-result",
1365
- toolCallId: part.tool_use_id,
1366
- toolName: "web_search",
1367
- isError: true,
1368
- result: {
1369
- type: "web_search_tool_result_error",
1370
- errorCode: part.content.error_code
1371
- },
1372
- providerExecuted: true
1373
- });
1374
- }
1375
- return;
1376
- }
1377
- case "code_execution_tool_result": {
1378
- const part = value.content_block;
1379
- if (part.content.type === "code_execution_result") {
1380
- controller.enqueue({
1381
- type: "tool-result",
1382
- toolCallId: part.tool_use_id,
1383
- toolName: "code_execution",
1384
- result: {
1385
- type: part.content.type,
1386
- stdout: part.content.stdout,
1387
- stderr: part.content.stderr,
1388
- return_code: part.content.return_code
1389
- },
1390
- providerExecuted: true
1391
- });
1392
- } else if (part.content.type === "code_execution_tool_result_error") {
1393
- controller.enqueue({
1394
- type: "tool-result",
1395
- toolCallId: part.tool_use_id,
1396
- toolName: "code_execution",
1397
- isError: true,
1398
- result: {
1399
- type: "code_execution_tool_result_error",
1400
- errorCode: part.content.error_code
1401
- },
1402
- providerExecuted: true
1403
- });
1404
- }
1405
- return;
1406
- }
1407
- default: {
1408
- const _exhaustiveCheck = contentBlockType;
1409
- throw new Error(
1410
- `Unsupported content block type: ${_exhaustiveCheck}`
1411
- );
1412
- }
1413
- }
1414
- }
1415
- case "content_block_stop": {
1416
- if (contentBlocks[value.index] != null) {
1417
- const contentBlock = contentBlocks[value.index];
1418
- switch (contentBlock.type) {
1419
- case "text": {
1420
- controller.enqueue({
1421
- type: "text-end",
1422
- id: String(value.index)
1423
- });
1424
- break;
1425
- }
1426
- case "reasoning": {
1427
- controller.enqueue({
1428
- type: "reasoning-end",
1429
- id: String(value.index)
1430
- });
1431
- break;
1432
- }
1433
- case "tool-call":
1434
- if (!usesJsonResponseTool) {
1435
- controller.enqueue({
1436
- type: "tool-input-end",
1437
- id: contentBlock.toolCallId
1438
- });
1439
- controller.enqueue(contentBlock);
1440
- }
1441
- break;
1442
- }
1443
- delete contentBlocks[value.index];
1444
- }
1445
- blockType = void 0;
1446
- return;
1447
- }
1448
- case "content_block_delta": {
1449
- const deltaType = value.delta.type;
1450
- switch (deltaType) {
1451
- case "text_delta": {
1452
- if (usesJsonResponseTool) {
1453
- return;
1454
- }
1455
- controller.enqueue({
1456
- type: "text-delta",
1457
- id: String(value.index),
1458
- delta: value.delta.text
1459
- });
1460
- return;
1461
- }
1462
- case "thinking_delta": {
1463
- controller.enqueue({
1464
- type: "reasoning-delta",
1465
- id: String(value.index),
1466
- delta: value.delta.thinking
1467
- });
1468
- return;
1469
- }
1470
- case "signature_delta": {
1471
- if (blockType === "thinking") {
1472
- controller.enqueue({
1473
- type: "reasoning-delta",
1474
- id: String(value.index),
1475
- delta: "",
1476
- providerMetadata: {
1477
- anthropic: {
1478
- signature: value.delta.signature
1479
- }
1480
- }
1481
- });
1482
- }
1483
- return;
1484
- }
1485
- case "input_json_delta": {
1486
- const contentBlock = contentBlocks[value.index];
1487
- const delta = value.delta.partial_json;
1488
- if (usesJsonResponseTool) {
1489
- if ((contentBlock == null ? void 0 : contentBlock.type) !== "text") {
1490
- return;
1491
- }
1492
- controller.enqueue({
1493
- type: "text-delta",
1494
- id: String(value.index),
1495
- delta
1496
- });
1497
- } else {
1498
- if ((contentBlock == null ? void 0 : contentBlock.type) !== "tool-call") {
1499
- return;
1500
- }
1501
- controller.enqueue({
1502
- type: "tool-input-delta",
1503
- id: contentBlock.toolCallId,
1504
- delta
1505
- });
1506
- contentBlock.input += delta;
1507
- }
1508
- return;
1509
- }
1510
- case "citations_delta": {
1511
- const citation = value.delta.citation;
1512
- processCitation(
1513
- citation,
1514
- citationDocuments,
1515
- generateId3,
1516
- (source) => controller.enqueue(source)
1517
- );
1518
- return;
1519
- }
1520
- default: {
1521
- const _exhaustiveCheck = deltaType;
1522
- throw new Error(
1523
- `Unsupported delta type: ${_exhaustiveCheck}`
1524
- );
1525
- }
1526
- }
1527
- }
1528
- case "message_start": {
1529
- usage.inputTokens = value.message.usage.input_tokens;
1530
- usage.cachedInputTokens = (_b = value.message.usage.cache_read_input_tokens) != null ? _b : void 0;
1531
- providerMetadata = {
1532
- anthropic: {
1533
- usage: value.message.usage,
1534
- cacheCreationInputTokens: (_c = value.message.usage.cache_creation_input_tokens) != null ? _c : null
1535
- }
1536
- };
1537
- controller.enqueue({
1538
- type: "response-metadata",
1539
- id: (_d = value.message.id) != null ? _d : void 0,
1540
- modelId: (_e = value.message.model) != null ? _e : void 0
1541
- });
1542
- return;
1543
- }
1544
- case "message_delta": {
1545
- usage.outputTokens = value.usage.output_tokens;
1546
- usage.totalTokens = ((_f = usage.inputTokens) != null ? _f : 0) + ((_g = value.usage.output_tokens) != null ? _g : 0);
1547
- finishReason = mapAnthropicStopReason({
1548
- finishReason: value.delta.stop_reason,
1549
- isJsonResponseFromTool: usesJsonResponseTool
1550
- });
1551
- return;
1552
- }
1553
- case "message_stop": {
1554
- controller.enqueue({
1555
- type: "finish",
1556
- finishReason,
1557
- usage,
1558
- providerMetadata
1559
- });
1560
- return;
1561
- }
1562
- case "error": {
1563
- controller.enqueue({ type: "error", error: value.error });
1564
- return;
1565
- }
1566
- default: {
1567
- const _exhaustiveCheck = value;
1568
- throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);
1569
- }
1570
- }
1571
- }
1572
- })
1573
- ),
1574
- request: { body },
1575
- response: { headers: responseHeaders }
1576
- };
1577
- }
1578
- };
1579
- var anthropicMessagesResponseSchema = z.object({
1580
- type: z.literal("message"),
1581
- id: z.string().nullish(),
1582
- model: z.string().nullish(),
1583
- content: z.array(
1584
- z.discriminatedUnion("type", [
1585
- z.object({
1586
- type: z.literal("text"),
1587
- text: z.string(),
1588
- citations: z.array(citationSchema).optional()
1589
- }),
1590
- z.object({
1591
- type: z.literal("thinking"),
1592
- thinking: z.string(),
1593
- signature: z.string()
1594
- }),
1595
- z.object({
1596
- type: z.literal("redacted_thinking"),
1597
- data: z.string()
1598
- }),
1599
- z.object({
1600
- type: z.literal("tool_use"),
1601
- id: z.string(),
1602
- name: z.string(),
1603
- input: z.unknown()
1604
- }),
1605
- z.object({
1606
- type: z.literal("server_tool_use"),
1607
- id: z.string(),
1608
- name: z.string(),
1609
- input: z.record(z.string(), z.unknown()).nullish()
1610
- }),
1611
- z.object({
1612
- type: z.literal("web_search_tool_result"),
1613
- tool_use_id: z.string(),
1614
- content: z.union([
1615
- z.array(
1616
- z.object({
1617
- type: z.literal("web_search_result"),
1618
- url: z.string(),
1619
- title: z.string(),
1620
- encrypted_content: z.string(),
1621
- page_age: z.string().nullish()
1622
- })
1623
- ),
1624
- z.object({
1625
- type: z.literal("web_search_tool_result_error"),
1626
- error_code: z.string()
1627
- })
1628
- ])
1629
- }),
1630
- z.object({
1631
- type: z.literal("code_execution_tool_result"),
1632
- tool_use_id: z.string(),
1633
- content: z.union([
1634
- z.object({
1635
- type: z.literal("code_execution_result"),
1636
- stdout: z.string(),
1637
- stderr: z.string(),
1638
- return_code: z.number()
1639
- }),
1640
- z.object({
1641
- type: z.literal("code_execution_tool_result_error"),
1642
- error_code: z.string()
1643
- })
1644
- ])
1645
- })
1646
- ])
1647
- ),
1648
- stop_reason: z.string().nullish(),
1649
- usage: z.looseObject({
1650
- input_tokens: z.number(),
1651
- output_tokens: z.number(),
1652
- cache_creation_input_tokens: z.number().nullish(),
1653
- cache_read_input_tokens: z.number().nullish()
1654
- })
1655
- });
1656
- var anthropicMessagesChunkSchema = z.discriminatedUnion("type", [
1657
- z.object({
1658
- type: z.literal("message_start"),
1659
- message: z.object({
1660
- id: z.string().nullish(),
1661
- model: z.string().nullish(),
1662
- usage: z.looseObject({
1663
- input_tokens: z.number(),
1664
- output_tokens: z.number(),
1665
- cache_creation_input_tokens: z.number().nullish(),
1666
- cache_read_input_tokens: z.number().nullish()
1667
- })
1668
- })
1669
- }),
1670
- z.object({
1671
- type: z.literal("content_block_start"),
1672
- index: z.number(),
1673
- content_block: z.discriminatedUnion("type", [
1674
- z.object({
1675
- type: z.literal("text"),
1676
- text: z.string()
1677
- }),
1678
- z.object({
1679
- type: z.literal("thinking"),
1680
- thinking: z.string()
1681
- }),
1682
- z.object({
1683
- type: z.literal("tool_use"),
1684
- id: z.string(),
1685
- name: z.string()
1686
- }),
1687
- z.object({
1688
- type: z.literal("redacted_thinking"),
1689
- data: z.string()
1690
- }),
1691
- z.object({
1692
- type: z.literal("server_tool_use"),
1693
- id: z.string(),
1694
- name: z.string(),
1695
- input: z.record(z.string(), z.unknown()).nullish()
1696
- }),
1697
- z.object({
1698
- type: z.literal("web_search_tool_result"),
1699
- tool_use_id: z.string(),
1700
- content: z.union([
1701
- z.array(
1702
- z.object({
1703
- type: z.literal("web_search_result"),
1704
- url: z.string(),
1705
- title: z.string(),
1706
- encrypted_content: z.string(),
1707
- page_age: z.string().nullish()
1708
- })
1709
- ),
1710
- z.object({
1711
- type: z.literal("web_search_tool_result_error"),
1712
- error_code: z.string()
1713
- })
1714
- ])
1715
- }),
1716
- z.object({
1717
- type: z.literal("code_execution_tool_result"),
1718
- tool_use_id: z.string(),
1719
- content: z.union([
1720
- z.object({
1721
- type: z.literal("code_execution_result"),
1722
- stdout: z.string(),
1723
- stderr: z.string(),
1724
- return_code: z.number()
1725
- }),
1726
- z.object({
1727
- type: z.literal("code_execution_tool_result_error"),
1728
- error_code: z.string()
1729
- })
1730
- ])
1731
- })
1732
- ])
1733
- }),
1734
- z.object({
1735
- type: z.literal("content_block_delta"),
1736
- index: z.number(),
1737
- delta: z.discriminatedUnion("type", [
1738
- z.object({
1739
- type: z.literal("input_json_delta"),
1740
- partial_json: z.string()
1741
- }),
1742
- z.object({
1743
- type: z.literal("text_delta"),
1744
- text: z.string()
1745
- }),
1746
- z.object({
1747
- type: z.literal("thinking_delta"),
1748
- thinking: z.string()
1749
- }),
1750
- z.object({
1751
- type: z.literal("signature_delta"),
1752
- signature: z.string()
1753
- }),
1754
- z.object({
1755
- type: z.literal("citations_delta"),
1756
- citation: citationSchema
1757
- })
1758
- ])
1759
- }),
1760
- z.object({
1761
- type: z.literal("content_block_stop"),
1762
- index: z.number()
1763
- }),
1764
- z.object({
1765
- type: z.literal("error"),
1766
- error: z.object({
1767
- type: z.string(),
1768
- message: z.string()
1769
- })
1770
- }),
1771
- z.object({
1772
- type: z.literal("message_delta"),
1773
- delta: z.object({ stop_reason: z.string().nullish() }),
1774
- usage: z.object({ output_tokens: z.number() })
1775
- }),
1776
- z.object({
1777
- type: z.literal("message_stop")
1778
- }),
1779
- z.object({
1780
- type: z.literal("ping")
1781
- })
1782
- ]);
1783
- var anthropicReasoningMetadataSchema = z.object({
1784
- signature: z.string().optional(),
1785
- redactedData: z.string().optional()
1786
- });
1787
- var bash_20241022 = createProviderDefinedToolFactory({
1788
- id: "anthropic.bash_20241022",
1789
- name: "bash",
1790
- inputSchema: z6.object({
1791
- command: z6.string(),
1792
- restart: z6.boolean().optional()
1793
- })
1794
- });
1795
- var bash_20250124 = createProviderDefinedToolFactory({
1796
- id: "anthropic.bash_20250124",
1797
- name: "bash",
1798
- inputSchema: z6.object({
1799
- command: z6.string(),
1800
- restart: z6.boolean().optional()
1801
- })
1802
- });
1803
- var computer_20241022 = createProviderDefinedToolFactory({
1804
- id: "anthropic.computer_20241022",
1805
- name: "computer",
1806
- inputSchema: z.object({
1807
- action: z.enum([
1808
- "key",
1809
- "type",
1810
- "mouse_move",
1811
- "left_click",
1812
- "left_click_drag",
1813
- "right_click",
1814
- "middle_click",
1815
- "double_click",
1816
- "screenshot",
1817
- "cursor_position"
1818
- ]),
1819
- coordinate: z.array(z.number().int()).optional(),
1820
- text: z.string().optional()
1821
- })
1822
- });
1823
- var computer_20250124 = createProviderDefinedToolFactory({
1824
- id: "anthropic.computer_20250124",
1825
- name: "computer",
1826
- inputSchema: z.object({
1827
- action: z.enum([
1828
- "key",
1829
- "hold_key",
1830
- "type",
1831
- "cursor_position",
1832
- "mouse_move",
1833
- "left_mouse_down",
1834
- "left_mouse_up",
1835
- "left_click",
1836
- "left_click_drag",
1837
- "right_click",
1838
- "middle_click",
1839
- "double_click",
1840
- "triple_click",
1841
- "scroll",
1842
- "wait",
1843
- "screenshot"
1844
- ]),
1845
- coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
1846
- duration: z.number().optional(),
1847
- scroll_amount: z.number().optional(),
1848
- scroll_direction: z.enum(["up", "down", "left", "right"]).optional(),
1849
- start_coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
1850
- text: z.string().optional()
1851
- })
1852
- });
1853
- var textEditor_20241022 = createProviderDefinedToolFactory({
1854
- id: "anthropic.text_editor_20241022",
1855
- name: "str_replace_editor",
1856
- inputSchema: z.object({
1857
- command: z.enum(["view", "create", "str_replace", "insert", "undo_edit"]),
1858
- path: z.string(),
1859
- file_text: z.string().optional(),
1860
- insert_line: z.number().int().optional(),
1861
- new_str: z.string().optional(),
1862
- old_str: z.string().optional(),
1863
- view_range: z.array(z.number().int()).optional()
1864
- })
1865
- });
1866
- var textEditor_20250124 = createProviderDefinedToolFactory({
1867
- id: "anthropic.text_editor_20250124",
1868
- name: "str_replace_editor",
1869
- inputSchema: z.object({
1870
- command: z.enum(["view", "create", "str_replace", "insert", "undo_edit"]),
1871
- path: z.string(),
1872
- file_text: z.string().optional(),
1873
- insert_line: z.number().int().optional(),
1874
- new_str: z.string().optional(),
1875
- old_str: z.string().optional(),
1876
- view_range: z.array(z.number().int()).optional()
1877
- })
1878
- });
1879
- var textEditor_20250429 = createProviderDefinedToolFactory({
1880
- id: "anthropic.text_editor_20250429",
1881
- name: "str_replace_based_edit_tool",
1882
- inputSchema: z.object({
1883
- command: z.enum(["view", "create", "str_replace", "insert"]),
1884
- path: z.string(),
1885
- file_text: z.string().optional(),
1886
- insert_line: z.number().int().optional(),
1887
- new_str: z.string().optional(),
1888
- old_str: z.string().optional(),
1889
- view_range: z.array(z.number().int()).optional()
1890
- })
1891
- });
1892
- var anthropicTools = {
1893
- /**
1894
- * Creates a tool for running a bash command. Must have name "bash".
1895
- *
1896
- * Image results are supported.
1897
- *
1898
- * @param execute - The function to execute the tool. Optional.
1899
- */
1900
- bash_20241022,
1901
- /**
1902
- * Creates a tool for running a bash command. Must have name "bash".
1903
- *
1904
- * Image results are supported.
1905
- *
1906
- * @param execute - The function to execute the tool. Optional.
1907
- */
1908
- bash_20250124,
1909
- /**
1910
- * Creates a tool for editing text. Must have name "str_replace_editor".
1911
- */
1912
- textEditor_20241022,
1913
- /**
1914
- * Creates a tool for editing text. Must have name "str_replace_editor".
1915
- */
1916
- textEditor_20250124,
1917
- /**
1918
- * Creates a tool for editing text. Must have name "str_replace_based_edit_tool".
1919
- * Note: This version does not support the "undo_edit" command.
1920
- */
1921
- textEditor_20250429,
1922
- /**
1923
- * Creates a tool for executing actions on a computer. Must have name "computer".
1924
- *
1925
- * Image results are supported.
1926
- *
1927
- * @param displayWidthPx - The width of the display being controlled by the model in pixels.
1928
- * @param displayHeightPx - The height of the display being controlled by the model in pixels.
1929
- * @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.
1930
- */
1931
- computer_20241022,
1932
- /**
1933
- * Creates a tool for executing actions on a computer. Must have name "computer".
1934
- *
1935
- * Image results are supported.
1936
- *
1937
- * @param displayWidthPx - The width of the display being controlled by the model in pixels.
1938
- * @param displayHeightPx - The height of the display being controlled by the model in pixels.
1939
- * @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.
1940
- * @param execute - The function to execute the tool. Optional.
1941
- */
1942
- computer_20250124,
1943
- /**
1944
- * Creates a web search tool that gives Claude direct access to real-time web content.
1945
- * Must have name "web_search".
1946
- *
1947
- * @param maxUses - Maximum number of web searches Claude can perform during the conversation.
1948
- * @param allowedDomains - Optional list of domains that Claude is allowed to search.
1949
- * @param blockedDomains - Optional list of domains that Claude should avoid when searching.
1950
- * @param userLocation - Optional user location information to provide geographically relevant search results.
1951
- */
1952
- webSearch_20250305,
1953
- /**
1954
- * Creates a tool for executing Python code. Must have name "code_execution".
1955
- */
1956
- codeExecution_20250522
1957
- };
1958
- function createAnthropic(options = {}) {
1959
- var _a;
1960
- const baseURL = (_a = withoutTrailingSlash(options.baseURL)) != null ? _a : "https://api.anthropic.com/v1";
1961
- const getHeaders = () => ({
1962
- "anthropic-version": "2023-06-01",
1963
- "x-api-key": loadApiKey({
1964
- apiKey: options.apiKey,
1965
- environmentVariableName: "ANTHROPIC_API_KEY",
1966
- description: "Anthropic"
1967
- }),
1968
- ...options.headers
1969
- });
1970
- const createChatModel = (modelId) => {
1971
- var _a2;
1972
- return new AnthropicMessagesLanguageModel(modelId, {
1973
- provider: "anthropic.messages",
1974
- baseURL,
1975
- headers: getHeaders,
1976
- fetch: options.fetch,
1977
- generateId: (_a2 = options.generateId) != null ? _a2 : generateId,
1978
- supportedUrls: () => ({
1979
- "image/*": [/^https?:\/\/.*$/]
1980
- })
1981
- });
1982
- };
1983
- const provider = function(modelId) {
1984
- if (new.target) {
1985
- throw new Error(
1986
- "The Anthropic model function cannot be called with the new keyword."
1987
- );
1988
- }
1989
- return createChatModel(modelId);
1990
- };
1991
- provider.languageModel = createChatModel;
1992
- provider.chat = createChatModel;
1993
- provider.messages = createChatModel;
1994
- provider.textEmbeddingModel = (modelId) => {
1995
- throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
1996
- };
1997
- provider.imageModel = (modelId) => {
1998
- throw new NoSuchModelError({ modelId, modelType: "imageModel" });
1999
- };
2000
- provider.tools = anthropicTools;
2001
- return provider;
2002
- }
2003
- var anthropic = createAnthropic();
2004
-
2005
- export { anthropic, createAnthropic };
2006
- //# sourceMappingURL=dist-3WEYC4YO.js.map
2007
- //# sourceMappingURL=dist-3WEYC4YO.js.map