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