ai 5.0.0-canary.2 → 5.0.0-canary.20

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 (51) hide show
  1. package/CHANGELOG.md +305 -0
  2. package/README.md +4 -4
  3. package/dist/index.d.mts +3246 -2586
  4. package/dist/index.d.ts +3246 -2586
  5. package/dist/index.js +4080 -3409
  6. package/dist/index.js.map +1 -1
  7. package/dist/index.mjs +4748 -4084
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/internal/index.d.mts +473 -0
  10. package/dist/internal/index.d.ts +473 -0
  11. package/dist/internal/index.js +957 -0
  12. package/dist/internal/index.js.map +1 -0
  13. package/dist/internal/index.mjs +930 -0
  14. package/dist/internal/index.mjs.map +1 -0
  15. package/{mcp-stdio/dist → dist/mcp-stdio}/index.js +5 -8
  16. package/dist/mcp-stdio/index.js.map +1 -0
  17. package/{mcp-stdio/dist → dist/mcp-stdio}/index.mjs +5 -20
  18. package/dist/mcp-stdio/index.mjs.map +1 -0
  19. package/{test/dist → dist/test}/index.d.mts +23 -24
  20. package/{test/dist → dist/test}/index.d.ts +23 -24
  21. package/{test/dist → dist/test}/index.js +39 -16
  22. package/dist/test/index.js.map +1 -0
  23. package/{test/dist → dist/test}/index.mjs +38 -15
  24. package/dist/test/index.mjs.map +1 -0
  25. package/internal.d.ts +1 -0
  26. package/mcp-stdio.d.ts +1 -0
  27. package/package.json +32 -49
  28. package/test.d.ts +1 -0
  29. package/mcp-stdio/create-child-process.test.ts +0 -92
  30. package/mcp-stdio/create-child-process.ts +0 -21
  31. package/mcp-stdio/dist/index.js.map +0 -1
  32. package/mcp-stdio/dist/index.mjs.map +0 -1
  33. package/mcp-stdio/get-environment.ts +0 -43
  34. package/mcp-stdio/index.ts +0 -4
  35. package/mcp-stdio/mcp-stdio-transport.test.ts +0 -262
  36. package/mcp-stdio/mcp-stdio-transport.ts +0 -157
  37. package/rsc/dist/index.d.ts +0 -813
  38. package/rsc/dist/index.mjs +0 -18
  39. package/rsc/dist/rsc-client.d.mts +0 -1
  40. package/rsc/dist/rsc-client.mjs +0 -18
  41. package/rsc/dist/rsc-client.mjs.map +0 -1
  42. package/rsc/dist/rsc-server.d.mts +0 -748
  43. package/rsc/dist/rsc-server.mjs +0 -2142
  44. package/rsc/dist/rsc-server.mjs.map +0 -1
  45. package/rsc/dist/rsc-shared.d.mts +0 -101
  46. package/rsc/dist/rsc-shared.mjs +0 -308
  47. package/rsc/dist/rsc-shared.mjs.map +0 -1
  48. package/test/dist/index.js.map +0 -1
  49. package/test/dist/index.mjs.map +0 -1
  50. package/{mcp-stdio/dist → dist/mcp-stdio}/index.d.mts +8 -8
  51. package/{mcp-stdio/dist → dist/mcp-stdio}/index.d.ts +8 -8
@@ -0,0 +1,957 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name5 in all)
8
+ __defProp(target, name5, { get: all[name5], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // internal/index.ts
21
+ var internal_exports = {};
22
+ __export(internal_exports, {
23
+ convertAsyncIteratorToReadableStream: () => import_provider_utils7.convertAsyncIteratorToReadableStream,
24
+ convertToLanguageModelPrompt: () => convertToLanguageModelPrompt,
25
+ prepareCallSettings: () => prepareCallSettings,
26
+ prepareRetries: () => prepareRetries,
27
+ prepareToolsAndToolChoice: () => prepareToolsAndToolChoice,
28
+ standardizePrompt: () => standardizePrompt
29
+ });
30
+ module.exports = __toCommonJS(internal_exports);
31
+ var import_provider_utils7 = require("@ai-sdk/provider-utils");
32
+
33
+ // core/prompt/convert-to-language-model-prompt.ts
34
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
35
+
36
+ // src/util/detect-media-type.ts
37
+ var import_provider_utils = require("@ai-sdk/provider-utils");
38
+ var imageMediaTypeSignatures = [
39
+ {
40
+ mediaType: "image/gif",
41
+ bytesPrefix: [71, 73, 70],
42
+ base64Prefix: "R0lG"
43
+ },
44
+ {
45
+ mediaType: "image/png",
46
+ bytesPrefix: [137, 80, 78, 71],
47
+ base64Prefix: "iVBORw"
48
+ },
49
+ {
50
+ mediaType: "image/jpeg",
51
+ bytesPrefix: [255, 216],
52
+ base64Prefix: "/9j/"
53
+ },
54
+ {
55
+ mediaType: "image/webp",
56
+ bytesPrefix: [82, 73, 70, 70],
57
+ base64Prefix: "UklGRg"
58
+ },
59
+ {
60
+ mediaType: "image/bmp",
61
+ bytesPrefix: [66, 77],
62
+ base64Prefix: "Qk"
63
+ },
64
+ {
65
+ mediaType: "image/tiff",
66
+ bytesPrefix: [73, 73, 42, 0],
67
+ base64Prefix: "SUkqAA"
68
+ },
69
+ {
70
+ mediaType: "image/tiff",
71
+ bytesPrefix: [77, 77, 0, 42],
72
+ base64Prefix: "TU0AKg"
73
+ },
74
+ {
75
+ mediaType: "image/avif",
76
+ bytesPrefix: [
77
+ 0,
78
+ 0,
79
+ 0,
80
+ 32,
81
+ 102,
82
+ 116,
83
+ 121,
84
+ 112,
85
+ 97,
86
+ 118,
87
+ 105,
88
+ 102
89
+ ],
90
+ base64Prefix: "AAAAIGZ0eXBhdmlm"
91
+ },
92
+ {
93
+ mediaType: "image/heic",
94
+ bytesPrefix: [
95
+ 0,
96
+ 0,
97
+ 0,
98
+ 32,
99
+ 102,
100
+ 116,
101
+ 121,
102
+ 112,
103
+ 104,
104
+ 101,
105
+ 105,
106
+ 99
107
+ ],
108
+ base64Prefix: "AAAAIGZ0eXBoZWlj"
109
+ }
110
+ ];
111
+ var stripID3 = (data) => {
112
+ const bytes = typeof data === "string" ? (0, import_provider_utils.convertBase64ToUint8Array)(data) : data;
113
+ const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
114
+ return bytes.slice(id3Size + 10);
115
+ };
116
+ function stripID3TagsIfPresent(data) {
117
+ const hasId3 = typeof data === "string" && data.startsWith("SUQz") || typeof data !== "string" && data.length > 10 && data[0] === 73 && // 'I'
118
+ data[1] === 68 && // 'D'
119
+ data[2] === 51;
120
+ return hasId3 ? stripID3(data) : data;
121
+ }
122
+ function detectMediaType({
123
+ data,
124
+ signatures
125
+ }) {
126
+ const processedData = stripID3TagsIfPresent(data);
127
+ for (const signature of signatures) {
128
+ if (typeof processedData === "string" ? processedData.startsWith(signature.base64Prefix) : processedData.length >= signature.bytesPrefix.length && signature.bytesPrefix.every(
129
+ (byte, index) => processedData[index] === byte
130
+ )) {
131
+ return signature.mediaType;
132
+ }
133
+ }
134
+ return void 0;
135
+ }
136
+
137
+ // src/util/download-error.ts
138
+ var import_provider = require("@ai-sdk/provider");
139
+ var name = "AI_DownloadError";
140
+ var marker = `vercel.ai.error.${name}`;
141
+ var symbol = Symbol.for(marker);
142
+ var _a;
143
+ var DownloadError = class extends import_provider.AISDKError {
144
+ constructor({
145
+ url,
146
+ statusCode,
147
+ statusText,
148
+ cause,
149
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
150
+ }) {
151
+ super({ name, message, cause });
152
+ this[_a] = true;
153
+ this.url = url;
154
+ this.statusCode = statusCode;
155
+ this.statusText = statusText;
156
+ }
157
+ static isInstance(error) {
158
+ return import_provider.AISDKError.hasMarker(error, marker);
159
+ }
160
+ };
161
+ _a = symbol;
162
+
163
+ // src/util/download.ts
164
+ async function download({ url }) {
165
+ var _a5;
166
+ const urlText = url.toString();
167
+ try {
168
+ const response = await fetch(urlText);
169
+ if (!response.ok) {
170
+ throw new DownloadError({
171
+ url: urlText,
172
+ statusCode: response.status,
173
+ statusText: response.statusText
174
+ });
175
+ }
176
+ return {
177
+ data: new Uint8Array(await response.arrayBuffer()),
178
+ mediaType: (_a5 = response.headers.get("content-type")) != null ? _a5 : void 0
179
+ };
180
+ } catch (error) {
181
+ if (DownloadError.isInstance(error)) {
182
+ throw error;
183
+ }
184
+ throw new DownloadError({ url: urlText, cause: error });
185
+ }
186
+ }
187
+
188
+ // core/prompt/data-content.ts
189
+ var import_provider2 = require("@ai-sdk/provider");
190
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
191
+ var import_zod = require("zod");
192
+
193
+ // core/prompt/split-data-url.ts
194
+ function splitDataUrl(dataUrl) {
195
+ try {
196
+ const [header, base64Content] = dataUrl.split(",");
197
+ return {
198
+ mediaType: header.split(";")[0].split(":")[1],
199
+ base64Content
200
+ };
201
+ } catch (error) {
202
+ return {
203
+ mediaType: void 0,
204
+ base64Content: void 0
205
+ };
206
+ }
207
+ }
208
+
209
+ // core/prompt/data-content.ts
210
+ var dataContentSchema = import_zod.z.union([
211
+ import_zod.z.string(),
212
+ import_zod.z.instanceof(Uint8Array),
213
+ import_zod.z.instanceof(ArrayBuffer),
214
+ import_zod.z.custom(
215
+ // Buffer might not be available in some environments such as CloudFlare:
216
+ (value) => {
217
+ var _a5, _b;
218
+ return (_b = (_a5 = globalThis.Buffer) == null ? void 0 : _a5.isBuffer(value)) != null ? _b : false;
219
+ },
220
+ { message: "Must be a Buffer" }
221
+ )
222
+ ]);
223
+ function convertToLanguageModelV2DataContent(content) {
224
+ if (content instanceof Uint8Array) {
225
+ return { data: content, mediaType: void 0 };
226
+ }
227
+ if (content instanceof ArrayBuffer) {
228
+ return { data: new Uint8Array(content), mediaType: void 0 };
229
+ }
230
+ if (typeof content === "string") {
231
+ try {
232
+ content = new URL(content);
233
+ } catch (error) {
234
+ }
235
+ }
236
+ if (content instanceof URL && content.protocol === "data:") {
237
+ const { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(
238
+ content.toString()
239
+ );
240
+ if (dataUrlMediaType == null || base64Content == null) {
241
+ throw new import_provider2.AISDKError({
242
+ name: "InvalidDataContentError",
243
+ message: `Invalid data URL format in content ${content.toString()}`
244
+ });
245
+ }
246
+ return { data: base64Content, mediaType: dataUrlMediaType };
247
+ }
248
+ return { data: content, mediaType: void 0 };
249
+ }
250
+
251
+ // core/prompt/invalid-message-role-error.ts
252
+ var import_provider3 = require("@ai-sdk/provider");
253
+ var name2 = "AI_InvalidMessageRoleError";
254
+ var marker2 = `vercel.ai.error.${name2}`;
255
+ var symbol2 = Symbol.for(marker2);
256
+ var _a2;
257
+ var InvalidMessageRoleError = class extends import_provider3.AISDKError {
258
+ constructor({
259
+ role,
260
+ message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
261
+ }) {
262
+ super({ name: name2, message });
263
+ this[_a2] = true;
264
+ this.role = role;
265
+ }
266
+ static isInstance(error) {
267
+ return import_provider3.AISDKError.hasMarker(error, marker2);
268
+ }
269
+ };
270
+ _a2 = symbol2;
271
+
272
+ // core/prompt/convert-to-language-model-prompt.ts
273
+ async function convertToLanguageModelPrompt({
274
+ prompt,
275
+ supportedUrls,
276
+ downloadImplementation = download
277
+ }) {
278
+ const downloadedAssets = await downloadAssets(
279
+ prompt.messages,
280
+ downloadImplementation,
281
+ supportedUrls
282
+ );
283
+ return [
284
+ ...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
285
+ ...prompt.messages.map(
286
+ (message) => convertToLanguageModelMessage(message, downloadedAssets)
287
+ )
288
+ ];
289
+ }
290
+ function convertToLanguageModelMessage(message, downloadedAssets) {
291
+ const role = message.role;
292
+ switch (role) {
293
+ case "system": {
294
+ return {
295
+ role: "system",
296
+ content: message.content,
297
+ providerOptions: message.providerOptions
298
+ };
299
+ }
300
+ case "user": {
301
+ if (typeof message.content === "string") {
302
+ return {
303
+ role: "user",
304
+ content: [{ type: "text", text: message.content }],
305
+ providerOptions: message.providerOptions
306
+ };
307
+ }
308
+ return {
309
+ role: "user",
310
+ content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
311
+ providerOptions: message.providerOptions
312
+ };
313
+ }
314
+ case "assistant": {
315
+ if (typeof message.content === "string") {
316
+ return {
317
+ role: "assistant",
318
+ content: [{ type: "text", text: message.content }],
319
+ providerOptions: message.providerOptions
320
+ };
321
+ }
322
+ return {
323
+ role: "assistant",
324
+ content: message.content.filter(
325
+ // remove empty text parts:
326
+ (part) => part.type !== "text" || part.text !== ""
327
+ ).map((part) => {
328
+ const providerOptions = part.providerOptions;
329
+ switch (part.type) {
330
+ case "file": {
331
+ const { data, mediaType } = convertToLanguageModelV2DataContent(
332
+ part.data
333
+ );
334
+ return {
335
+ type: "file",
336
+ data,
337
+ filename: part.filename,
338
+ mediaType: mediaType != null ? mediaType : part.mediaType,
339
+ providerOptions
340
+ };
341
+ }
342
+ case "reasoning": {
343
+ return {
344
+ type: "reasoning",
345
+ text: part.text,
346
+ providerOptions
347
+ };
348
+ }
349
+ case "text": {
350
+ return {
351
+ type: "text",
352
+ text: part.text,
353
+ providerOptions
354
+ };
355
+ }
356
+ case "tool-call": {
357
+ return {
358
+ type: "tool-call",
359
+ toolCallId: part.toolCallId,
360
+ toolName: part.toolName,
361
+ args: part.args,
362
+ providerOptions
363
+ };
364
+ }
365
+ }
366
+ }),
367
+ providerOptions: message.providerOptions
368
+ };
369
+ }
370
+ case "tool": {
371
+ return {
372
+ role: "tool",
373
+ content: message.content.map((part) => ({
374
+ type: "tool-result",
375
+ toolCallId: part.toolCallId,
376
+ toolName: part.toolName,
377
+ result: part.result,
378
+ content: part.experimental_content,
379
+ isError: part.isError,
380
+ providerOptions: part.providerOptions
381
+ })),
382
+ providerOptions: message.providerOptions
383
+ };
384
+ }
385
+ default: {
386
+ const _exhaustiveCheck = role;
387
+ throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
388
+ }
389
+ }
390
+ }
391
+ async function downloadAssets(messages, downloadImplementation, supportedUrls) {
392
+ const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter(
393
+ (content) => Array.isArray(content)
394
+ ).flat().filter(
395
+ (part) => part.type === "image" || part.type === "file"
396
+ ).map((part) => {
397
+ var _a5;
398
+ const mediaType = (_a5 = part.mediaType) != null ? _a5 : part.type === "image" ? "image/*" : void 0;
399
+ let data = part.type === "image" ? part.image : part.data;
400
+ if (typeof data === "string") {
401
+ try {
402
+ data = new URL(data);
403
+ } catch (ignored) {
404
+ }
405
+ }
406
+ return { mediaType, data };
407
+ }).filter(
408
+ (part) => part.data instanceof URL && part.mediaType != null && !(0, import_provider_utils3.isUrlSupported)({
409
+ url: part.data.toString(),
410
+ mediaType: part.mediaType,
411
+ supportedUrls
412
+ })
413
+ ).map((part) => part.data);
414
+ const downloadedImages = await Promise.all(
415
+ urls.map(async (url) => ({
416
+ url,
417
+ data: await downloadImplementation({ url })
418
+ }))
419
+ );
420
+ return Object.fromEntries(
421
+ downloadedImages.map(({ url, data }) => [url.toString(), data])
422
+ );
423
+ }
424
+ function convertPartToLanguageModelPart(part, downloadedAssets) {
425
+ var _a5, _b;
426
+ if (part.type === "text") {
427
+ return {
428
+ type: "text",
429
+ text: part.text,
430
+ providerOptions: part.providerOptions
431
+ };
432
+ }
433
+ let originalData;
434
+ const type = part.type;
435
+ switch (type) {
436
+ case "image":
437
+ originalData = part.image;
438
+ break;
439
+ case "file":
440
+ originalData = part.data;
441
+ break;
442
+ default:
443
+ throw new Error(`Unsupported part type: ${type}`);
444
+ }
445
+ const { data: convertedData, mediaType: convertedMediaType } = convertToLanguageModelV2DataContent(originalData);
446
+ let mediaType = convertedMediaType != null ? convertedMediaType : part.mediaType;
447
+ let data = convertedData;
448
+ if (data instanceof URL) {
449
+ const downloadedFile = downloadedAssets[data.toString()];
450
+ if (downloadedFile) {
451
+ data = downloadedFile.data;
452
+ mediaType = (_a5 = downloadedFile.mediaType) != null ? _a5 : mediaType;
453
+ }
454
+ }
455
+ switch (type) {
456
+ case "image": {
457
+ if (data instanceof Uint8Array || typeof data === "string") {
458
+ mediaType = (_b = detectMediaType({ data, signatures: imageMediaTypeSignatures })) != null ? _b : mediaType;
459
+ }
460
+ return {
461
+ type: "file",
462
+ mediaType: mediaType != null ? mediaType : "image/*",
463
+ // any image
464
+ filename: void 0,
465
+ data,
466
+ providerOptions: part.providerOptions
467
+ };
468
+ }
469
+ case "file": {
470
+ if (mediaType == null) {
471
+ throw new Error(`Media type is missing for file part`);
472
+ }
473
+ return {
474
+ type: "file",
475
+ mediaType,
476
+ filename: part.filename,
477
+ data,
478
+ providerOptions: part.providerOptions
479
+ };
480
+ }
481
+ }
482
+ }
483
+
484
+ // src/error/invalid-argument-error.ts
485
+ var import_provider4 = require("@ai-sdk/provider");
486
+ var name3 = "AI_InvalidArgumentError";
487
+ var marker3 = `vercel.ai.error.${name3}`;
488
+ var symbol3 = Symbol.for(marker3);
489
+ var _a3;
490
+ var InvalidArgumentError = class extends import_provider4.AISDKError {
491
+ constructor({
492
+ parameter,
493
+ value,
494
+ message
495
+ }) {
496
+ super({
497
+ name: name3,
498
+ message: `Invalid argument for parameter ${parameter}: ${message}`
499
+ });
500
+ this[_a3] = true;
501
+ this.parameter = parameter;
502
+ this.value = value;
503
+ }
504
+ static isInstance(error) {
505
+ return import_provider4.AISDKError.hasMarker(error, marker3);
506
+ }
507
+ };
508
+ _a3 = symbol3;
509
+
510
+ // core/prompt/prepare-call-settings.ts
511
+ function prepareCallSettings({
512
+ maxOutputTokens,
513
+ temperature,
514
+ topP,
515
+ topK,
516
+ presencePenalty,
517
+ frequencyPenalty,
518
+ stopSequences,
519
+ seed
520
+ }) {
521
+ if (maxOutputTokens != null) {
522
+ if (!Number.isInteger(maxOutputTokens)) {
523
+ throw new InvalidArgumentError({
524
+ parameter: "maxOutputTokens",
525
+ value: maxOutputTokens,
526
+ message: "maxOutputTokens must be an integer"
527
+ });
528
+ }
529
+ if (maxOutputTokens < 1) {
530
+ throw new InvalidArgumentError({
531
+ parameter: "maxOutputTokens",
532
+ value: maxOutputTokens,
533
+ message: "maxOutputTokens must be >= 1"
534
+ });
535
+ }
536
+ }
537
+ if (temperature != null) {
538
+ if (typeof temperature !== "number") {
539
+ throw new InvalidArgumentError({
540
+ parameter: "temperature",
541
+ value: temperature,
542
+ message: "temperature must be a number"
543
+ });
544
+ }
545
+ }
546
+ if (topP != null) {
547
+ if (typeof topP !== "number") {
548
+ throw new InvalidArgumentError({
549
+ parameter: "topP",
550
+ value: topP,
551
+ message: "topP must be a number"
552
+ });
553
+ }
554
+ }
555
+ if (topK != null) {
556
+ if (typeof topK !== "number") {
557
+ throw new InvalidArgumentError({
558
+ parameter: "topK",
559
+ value: topK,
560
+ message: "topK must be a number"
561
+ });
562
+ }
563
+ }
564
+ if (presencePenalty != null) {
565
+ if (typeof presencePenalty !== "number") {
566
+ throw new InvalidArgumentError({
567
+ parameter: "presencePenalty",
568
+ value: presencePenalty,
569
+ message: "presencePenalty must be a number"
570
+ });
571
+ }
572
+ }
573
+ if (frequencyPenalty != null) {
574
+ if (typeof frequencyPenalty !== "number") {
575
+ throw new InvalidArgumentError({
576
+ parameter: "frequencyPenalty",
577
+ value: frequencyPenalty,
578
+ message: "frequencyPenalty must be a number"
579
+ });
580
+ }
581
+ }
582
+ if (seed != null) {
583
+ if (!Number.isInteger(seed)) {
584
+ throw new InvalidArgumentError({
585
+ parameter: "seed",
586
+ value: seed,
587
+ message: "seed must be an integer"
588
+ });
589
+ }
590
+ }
591
+ return {
592
+ maxOutputTokens,
593
+ temperature: temperature != null ? temperature : temperature === null ? void 0 : 0,
594
+ topP,
595
+ topK,
596
+ presencePenalty,
597
+ frequencyPenalty,
598
+ stopSequences: stopSequences != null && stopSequences.length > 0 ? stopSequences : void 0,
599
+ seed
600
+ };
601
+ }
602
+
603
+ // core/prompt/prepare-tools-and-tool-choice.ts
604
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
605
+
606
+ // src/util/is-non-empty-object.ts
607
+ function isNonEmptyObject(object) {
608
+ return object != null && Object.keys(object).length > 0;
609
+ }
610
+
611
+ // core/prompt/prepare-tools-and-tool-choice.ts
612
+ function prepareToolsAndToolChoice({
613
+ tools,
614
+ toolChoice,
615
+ activeTools
616
+ }) {
617
+ if (!isNonEmptyObject(tools)) {
618
+ return {
619
+ tools: void 0,
620
+ toolChoice: void 0
621
+ };
622
+ }
623
+ const filteredTools = activeTools != null ? Object.entries(tools).filter(
624
+ ([name5]) => activeTools.includes(name5)
625
+ ) : Object.entries(tools);
626
+ return {
627
+ tools: filteredTools.map(([name5, tool]) => {
628
+ const toolType = tool.type;
629
+ switch (toolType) {
630
+ case void 0:
631
+ case "function":
632
+ return {
633
+ type: "function",
634
+ name: name5,
635
+ description: tool.description,
636
+ parameters: (0, import_provider_utils4.asSchema)(tool.parameters).jsonSchema
637
+ };
638
+ case "provider-defined":
639
+ return {
640
+ type: "provider-defined",
641
+ name: name5,
642
+ id: tool.id,
643
+ args: tool.args
644
+ };
645
+ default: {
646
+ const exhaustiveCheck = toolType;
647
+ throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);
648
+ }
649
+ }
650
+ }),
651
+ toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
652
+ };
653
+ }
654
+
655
+ // core/prompt/standardize-prompt.ts
656
+ var import_provider5 = require("@ai-sdk/provider");
657
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
658
+ var import_zod7 = require("zod");
659
+
660
+ // core/prompt/message.ts
661
+ var import_zod6 = require("zod");
662
+
663
+ // core/types/provider-metadata.ts
664
+ var import_zod3 = require("zod");
665
+
666
+ // core/types/json-value.ts
667
+ var import_zod2 = require("zod");
668
+ var jsonValueSchema = import_zod2.z.lazy(
669
+ () => import_zod2.z.union([
670
+ import_zod2.z.null(),
671
+ import_zod2.z.string(),
672
+ import_zod2.z.number(),
673
+ import_zod2.z.boolean(),
674
+ import_zod2.z.record(import_zod2.z.string(), jsonValueSchema),
675
+ import_zod2.z.array(jsonValueSchema)
676
+ ])
677
+ );
678
+
679
+ // core/types/provider-metadata.ts
680
+ var providerMetadataSchema = import_zod3.z.record(
681
+ import_zod3.z.string(),
682
+ import_zod3.z.record(import_zod3.z.string(), jsonValueSchema)
683
+ );
684
+
685
+ // core/prompt/content-part.ts
686
+ var import_zod5 = require("zod");
687
+
688
+ // core/prompt/tool-result-content.ts
689
+ var import_zod4 = require("zod");
690
+ var toolResultContentSchema = import_zod4.z.array(
691
+ import_zod4.z.union([
692
+ import_zod4.z.object({ type: import_zod4.z.literal("text"), text: import_zod4.z.string() }),
693
+ import_zod4.z.object({
694
+ type: import_zod4.z.literal("image"),
695
+ data: import_zod4.z.string(),
696
+ mediaType: import_zod4.z.string().optional()
697
+ })
698
+ ])
699
+ );
700
+
701
+ // core/prompt/content-part.ts
702
+ var textPartSchema = import_zod5.z.object({
703
+ type: import_zod5.z.literal("text"),
704
+ text: import_zod5.z.string(),
705
+ providerOptions: providerMetadataSchema.optional()
706
+ });
707
+ var imagePartSchema = import_zod5.z.object({
708
+ type: import_zod5.z.literal("image"),
709
+ image: import_zod5.z.union([dataContentSchema, import_zod5.z.instanceof(URL)]),
710
+ mediaType: import_zod5.z.string().optional(),
711
+ providerOptions: providerMetadataSchema.optional()
712
+ });
713
+ var filePartSchema = import_zod5.z.object({
714
+ type: import_zod5.z.literal("file"),
715
+ data: import_zod5.z.union([dataContentSchema, import_zod5.z.instanceof(URL)]),
716
+ filename: import_zod5.z.string().optional(),
717
+ mediaType: import_zod5.z.string(),
718
+ providerOptions: providerMetadataSchema.optional()
719
+ });
720
+ var reasoningPartSchema = import_zod5.z.object({
721
+ type: import_zod5.z.literal("reasoning"),
722
+ text: import_zod5.z.string(),
723
+ providerOptions: providerMetadataSchema.optional()
724
+ });
725
+ var toolCallPartSchema = import_zod5.z.object({
726
+ type: import_zod5.z.literal("tool-call"),
727
+ toolCallId: import_zod5.z.string(),
728
+ toolName: import_zod5.z.string(),
729
+ args: import_zod5.z.unknown(),
730
+ providerOptions: providerMetadataSchema.optional()
731
+ });
732
+ var toolResultPartSchema = import_zod5.z.object({
733
+ type: import_zod5.z.literal("tool-result"),
734
+ toolCallId: import_zod5.z.string(),
735
+ toolName: import_zod5.z.string(),
736
+ result: import_zod5.z.unknown(),
737
+ content: toolResultContentSchema.optional(),
738
+ isError: import_zod5.z.boolean().optional(),
739
+ providerOptions: providerMetadataSchema.optional()
740
+ });
741
+
742
+ // core/prompt/message.ts
743
+ var systemModelMessageSchema = import_zod6.z.object(
744
+ {
745
+ role: import_zod6.z.literal("system"),
746
+ content: import_zod6.z.string(),
747
+ providerOptions: providerMetadataSchema.optional()
748
+ }
749
+ );
750
+ var userModelMessageSchema = import_zod6.z.object({
751
+ role: import_zod6.z.literal("user"),
752
+ content: import_zod6.z.union([
753
+ import_zod6.z.string(),
754
+ import_zod6.z.array(import_zod6.z.union([textPartSchema, imagePartSchema, filePartSchema]))
755
+ ]),
756
+ providerOptions: providerMetadataSchema.optional()
757
+ });
758
+ var assistantModelMessageSchema = import_zod6.z.object({
759
+ role: import_zod6.z.literal("assistant"),
760
+ content: import_zod6.z.union([
761
+ import_zod6.z.string(),
762
+ import_zod6.z.array(
763
+ import_zod6.z.union([
764
+ textPartSchema,
765
+ filePartSchema,
766
+ reasoningPartSchema,
767
+ toolCallPartSchema
768
+ ])
769
+ )
770
+ ]),
771
+ providerOptions: providerMetadataSchema.optional()
772
+ });
773
+ var toolModelMessageSchema = import_zod6.z.object({
774
+ role: import_zod6.z.literal("tool"),
775
+ content: import_zod6.z.array(toolResultPartSchema),
776
+ providerOptions: providerMetadataSchema.optional()
777
+ });
778
+ var modelMessageSchema = import_zod6.z.union([
779
+ systemModelMessageSchema,
780
+ userModelMessageSchema,
781
+ assistantModelMessageSchema,
782
+ toolModelMessageSchema
783
+ ]);
784
+
785
+ // core/prompt/standardize-prompt.ts
786
+ async function standardizePrompt(prompt) {
787
+ if (prompt.prompt == null && prompt.messages == null) {
788
+ throw new import_provider5.InvalidPromptError({
789
+ prompt,
790
+ message: "prompt or messages must be defined"
791
+ });
792
+ }
793
+ if (prompt.prompt != null && prompt.messages != null) {
794
+ throw new import_provider5.InvalidPromptError({
795
+ prompt,
796
+ message: "prompt and messages cannot be defined at the same time"
797
+ });
798
+ }
799
+ if (prompt.system != null && typeof prompt.system !== "string") {
800
+ throw new import_provider5.InvalidPromptError({
801
+ prompt,
802
+ message: "system must be a string"
803
+ });
804
+ }
805
+ let messages;
806
+ if (prompt.prompt != null && typeof prompt.prompt === "string") {
807
+ messages = [{ role: "user", content: prompt.prompt }];
808
+ } else if (prompt.prompt != null && Array.isArray(prompt.prompt)) {
809
+ messages = prompt.prompt;
810
+ } else if (prompt.messages != null) {
811
+ messages = prompt.messages;
812
+ } else {
813
+ throw new import_provider5.InvalidPromptError({
814
+ prompt,
815
+ message: "prompt or messages must be defined"
816
+ });
817
+ }
818
+ if (messages.length === 0) {
819
+ throw new import_provider5.InvalidPromptError({
820
+ prompt,
821
+ message: "messages must not be empty"
822
+ });
823
+ }
824
+ const validationResult = await (0, import_provider_utils5.safeValidateTypes)({
825
+ value: messages,
826
+ schema: import_zod7.z.array(modelMessageSchema)
827
+ });
828
+ if (!validationResult.success) {
829
+ throw new import_provider5.InvalidPromptError({
830
+ prompt,
831
+ message: "messages must be an array of ModelMessage",
832
+ cause: validationResult.error
833
+ });
834
+ }
835
+ return {
836
+ messages,
837
+ system: prompt.system
838
+ };
839
+ }
840
+
841
+ // src/util/retry-with-exponential-backoff.ts
842
+ var import_provider7 = require("@ai-sdk/provider");
843
+ var import_provider_utils6 = require("@ai-sdk/provider-utils");
844
+
845
+ // src/util/retry-error.ts
846
+ var import_provider6 = require("@ai-sdk/provider");
847
+ var name4 = "AI_RetryError";
848
+ var marker4 = `vercel.ai.error.${name4}`;
849
+ var symbol4 = Symbol.for(marker4);
850
+ var _a4;
851
+ var RetryError = class extends import_provider6.AISDKError {
852
+ constructor({
853
+ message,
854
+ reason,
855
+ errors
856
+ }) {
857
+ super({ name: name4, message });
858
+ this[_a4] = true;
859
+ this.reason = reason;
860
+ this.errors = errors;
861
+ this.lastError = errors[errors.length - 1];
862
+ }
863
+ static isInstance(error) {
864
+ return import_provider6.AISDKError.hasMarker(error, marker4);
865
+ }
866
+ };
867
+ _a4 = symbol4;
868
+
869
+ // src/util/retry-with-exponential-backoff.ts
870
+ var retryWithExponentialBackoff = ({
871
+ maxRetries = 2,
872
+ initialDelayInMs = 2e3,
873
+ backoffFactor = 2
874
+ } = {}) => async (f) => _retryWithExponentialBackoff(f, {
875
+ maxRetries,
876
+ delayInMs: initialDelayInMs,
877
+ backoffFactor
878
+ });
879
+ async function _retryWithExponentialBackoff(f, {
880
+ maxRetries,
881
+ delayInMs,
882
+ backoffFactor
883
+ }, errors = []) {
884
+ try {
885
+ return await f();
886
+ } catch (error) {
887
+ if ((0, import_provider_utils6.isAbortError)(error)) {
888
+ throw error;
889
+ }
890
+ if (maxRetries === 0) {
891
+ throw error;
892
+ }
893
+ const errorMessage = (0, import_provider_utils6.getErrorMessage)(error);
894
+ const newErrors = [...errors, error];
895
+ const tryNumber = newErrors.length;
896
+ if (tryNumber > maxRetries) {
897
+ throw new RetryError({
898
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
899
+ reason: "maxRetriesExceeded",
900
+ errors: newErrors
901
+ });
902
+ }
903
+ if (error instanceof Error && import_provider7.APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
904
+ await (0, import_provider_utils6.delay)(delayInMs);
905
+ return _retryWithExponentialBackoff(
906
+ f,
907
+ { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
908
+ newErrors
909
+ );
910
+ }
911
+ if (tryNumber === 1) {
912
+ throw error;
913
+ }
914
+ throw new RetryError({
915
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
916
+ reason: "errorNotRetryable",
917
+ errors: newErrors
918
+ });
919
+ }
920
+ }
921
+
922
+ // src/util/prepare-retries.ts
923
+ function prepareRetries({
924
+ maxRetries
925
+ }) {
926
+ if (maxRetries != null) {
927
+ if (!Number.isInteger(maxRetries)) {
928
+ throw new InvalidArgumentError({
929
+ parameter: "maxRetries",
930
+ value: maxRetries,
931
+ message: "maxRetries must be an integer"
932
+ });
933
+ }
934
+ if (maxRetries < 0) {
935
+ throw new InvalidArgumentError({
936
+ parameter: "maxRetries",
937
+ value: maxRetries,
938
+ message: "maxRetries must be >= 0"
939
+ });
940
+ }
941
+ }
942
+ const maxRetriesResult = maxRetries != null ? maxRetries : 2;
943
+ return {
944
+ maxRetries: maxRetriesResult,
945
+ retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
946
+ };
947
+ }
948
+ // Annotate the CommonJS export names for ESM import in node:
949
+ 0 && (module.exports = {
950
+ convertAsyncIteratorToReadableStream,
951
+ convertToLanguageModelPrompt,
952
+ prepareCallSettings,
953
+ prepareRetries,
954
+ prepareToolsAndToolChoice,
955
+ standardizePrompt
956
+ });
957
+ //# sourceMappingURL=index.js.map