ai 0.0.0-156c9f7b-20250115085202

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1848 @@
1
+ // rsc/ai-state.tsx
2
+ import * as jsondiffpatch from "jsondiffpatch";
3
+ import { AsyncLocalStorage } from "async_hooks";
4
+
5
+ // util/create-resolvable-promise.ts
6
+ function createResolvablePromise() {
7
+ let resolve;
8
+ let reject;
9
+ const promise = new Promise((res, rej) => {
10
+ resolve = res;
11
+ reject = rej;
12
+ });
13
+ return {
14
+ promise,
15
+ resolve,
16
+ reject
17
+ };
18
+ }
19
+
20
+ // util/is-function.ts
21
+ var isFunction = (value) => typeof value === "function";
22
+
23
+ // rsc/ai-state.tsx
24
+ var asyncAIStateStorage = new AsyncLocalStorage();
25
+ function getAIStateStoreOrThrow(message) {
26
+ const store = asyncAIStateStorage.getStore();
27
+ if (!store) {
28
+ throw new Error(message);
29
+ }
30
+ return store;
31
+ }
32
+ function withAIState({ state, options }, fn) {
33
+ return asyncAIStateStorage.run(
34
+ {
35
+ currentState: JSON.parse(JSON.stringify(state)),
36
+ // deep clone object
37
+ originalState: state,
38
+ sealed: false,
39
+ options
40
+ },
41
+ fn
42
+ );
43
+ }
44
+ function getAIStateDeltaPromise() {
45
+ const store = getAIStateStoreOrThrow("Internal error occurred.");
46
+ return store.mutationDeltaPromise;
47
+ }
48
+ function sealMutableAIState() {
49
+ const store = getAIStateStoreOrThrow("Internal error occurred.");
50
+ store.sealed = true;
51
+ }
52
+ function getAIState(...args) {
53
+ const store = getAIStateStoreOrThrow(
54
+ "`getAIState` must be called within an AI Action."
55
+ );
56
+ if (args.length > 0) {
57
+ const key = args[0];
58
+ if (typeof store.currentState !== "object") {
59
+ throw new Error(
60
+ `You can't get the "${String(
61
+ key
62
+ )}" field from the AI state because it's not an object.`
63
+ );
64
+ }
65
+ return store.currentState[key];
66
+ }
67
+ return store.currentState;
68
+ }
69
+ function getMutableAIState(...args) {
70
+ const store = getAIStateStoreOrThrow(
71
+ "`getMutableAIState` must be called within an AI Action."
72
+ );
73
+ if (store.sealed) {
74
+ throw new Error(
75
+ "`getMutableAIState` must be called before returning from an AI Action. Please move it to the top level of the Action's function body."
76
+ );
77
+ }
78
+ if (!store.mutationDeltaPromise) {
79
+ const { promise, resolve } = createResolvablePromise();
80
+ store.mutationDeltaPromise = promise;
81
+ store.mutationDeltaResolve = resolve;
82
+ }
83
+ function doUpdate(newState, done) {
84
+ var _a9, _b;
85
+ if (args.length > 0) {
86
+ if (typeof store.currentState !== "object") {
87
+ const key = args[0];
88
+ throw new Error(
89
+ `You can't modify the "${String(
90
+ key
91
+ )}" field of the AI state because it's not an object.`
92
+ );
93
+ }
94
+ }
95
+ if (isFunction(newState)) {
96
+ if (args.length > 0) {
97
+ store.currentState[args[0]] = newState(store.currentState[args[0]]);
98
+ } else {
99
+ store.currentState = newState(store.currentState);
100
+ }
101
+ } else {
102
+ if (args.length > 0) {
103
+ store.currentState[args[0]] = newState;
104
+ } else {
105
+ store.currentState = newState;
106
+ }
107
+ }
108
+ (_b = (_a9 = store.options).onSetAIState) == null ? void 0 : _b.call(_a9, {
109
+ key: args.length > 0 ? args[0] : void 0,
110
+ state: store.currentState,
111
+ done
112
+ });
113
+ }
114
+ const mutableState = {
115
+ get: () => {
116
+ if (args.length > 0) {
117
+ const key = args[0];
118
+ if (typeof store.currentState !== "object") {
119
+ throw new Error(
120
+ `You can't get the "${String(
121
+ key
122
+ )}" field from the AI state because it's not an object.`
123
+ );
124
+ }
125
+ return store.currentState[key];
126
+ }
127
+ return store.currentState;
128
+ },
129
+ update: function update(newAIState) {
130
+ doUpdate(newAIState, false);
131
+ },
132
+ done: function done(...doneArgs) {
133
+ if (doneArgs.length > 0) {
134
+ doUpdate(doneArgs[0], true);
135
+ }
136
+ const delta = jsondiffpatch.diff(store.originalState, store.currentState);
137
+ store.mutationDeltaResolve(delta);
138
+ }
139
+ };
140
+ return mutableState;
141
+ }
142
+
143
+ // rsc/provider.tsx
144
+ import * as React from "react";
145
+ import { InternalAIProvider } from "./rsc-shared.mjs";
146
+ import { jsx } from "react/jsx-runtime";
147
+ async function innerAction({
148
+ action,
149
+ options
150
+ }, state, ...args) {
151
+ "use server";
152
+ return await withAIState(
153
+ {
154
+ state,
155
+ options
156
+ },
157
+ async () => {
158
+ const result = await action(...args);
159
+ sealMutableAIState();
160
+ return [getAIStateDeltaPromise(), result];
161
+ }
162
+ );
163
+ }
164
+ function wrapAction(action, options) {
165
+ return innerAction.bind(null, { action, options });
166
+ }
167
+ function createAI({
168
+ actions,
169
+ initialAIState,
170
+ initialUIState,
171
+ onSetAIState,
172
+ onGetUIState
173
+ }) {
174
+ const wrappedActions = {};
175
+ for (const name9 in actions) {
176
+ wrappedActions[name9] = wrapAction(actions[name9], {
177
+ onSetAIState
178
+ });
179
+ }
180
+ const wrappedSyncUIState = onGetUIState ? wrapAction(onGetUIState, {}) : void 0;
181
+ const AI = async (props) => {
182
+ var _a9, _b;
183
+ if ("useState" in React) {
184
+ throw new Error(
185
+ "This component can only be used inside Server Components."
186
+ );
187
+ }
188
+ let uiState = (_a9 = props.initialUIState) != null ? _a9 : initialUIState;
189
+ let aiState = (_b = props.initialAIState) != null ? _b : initialAIState;
190
+ let aiStateDelta = void 0;
191
+ if (wrappedSyncUIState) {
192
+ const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);
193
+ if (newUIState !== void 0) {
194
+ aiStateDelta = newAIStateDelta;
195
+ uiState = newUIState;
196
+ }
197
+ }
198
+ return /* @__PURE__ */ jsx(
199
+ InternalAIProvider,
200
+ {
201
+ wrappedActions,
202
+ wrappedSyncUIState,
203
+ initialUIState: uiState,
204
+ initialAIState: aiState,
205
+ initialAIStatePatch: aiStateDelta,
206
+ children: props.children
207
+ }
208
+ );
209
+ };
210
+ return AI;
211
+ }
212
+
213
+ // rsc/stream-ui/stream-ui.tsx
214
+ import { safeParseJSON } from "@ai-sdk/provider-utils";
215
+
216
+ // util/download-error.ts
217
+ import { AISDKError } from "@ai-sdk/provider";
218
+ var name = "AI_DownloadError";
219
+ var marker = `vercel.ai.error.${name}`;
220
+ var symbol = Symbol.for(marker);
221
+ var _a;
222
+ var DownloadError = class extends AISDKError {
223
+ constructor({
224
+ url,
225
+ statusCode,
226
+ statusText,
227
+ cause,
228
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
229
+ }) {
230
+ super({ name, message, cause });
231
+ this[_a] = true;
232
+ this.url = url;
233
+ this.statusCode = statusCode;
234
+ this.statusText = statusText;
235
+ }
236
+ static isInstance(error) {
237
+ return AISDKError.hasMarker(error, marker);
238
+ }
239
+ };
240
+ _a = symbol;
241
+
242
+ // util/download.ts
243
+ async function download({
244
+ url,
245
+ fetchImplementation = fetch
246
+ }) {
247
+ var _a9;
248
+ const urlText = url.toString();
249
+ try {
250
+ const response = await fetchImplementation(urlText);
251
+ if (!response.ok) {
252
+ throw new DownloadError({
253
+ url: urlText,
254
+ statusCode: response.status,
255
+ statusText: response.statusText
256
+ });
257
+ }
258
+ return {
259
+ data: new Uint8Array(await response.arrayBuffer()),
260
+ mimeType: (_a9 = response.headers.get("content-type")) != null ? _a9 : void 0
261
+ };
262
+ } catch (error) {
263
+ if (DownloadError.isInstance(error)) {
264
+ throw error;
265
+ }
266
+ throw new DownloadError({ url: urlText, cause: error });
267
+ }
268
+ }
269
+
270
+ // core/util/detect-image-mimetype.ts
271
+ var mimeTypeSignatures = [
272
+ { mimeType: "image/gif", bytes: [71, 73, 70] },
273
+ { mimeType: "image/png", bytes: [137, 80, 78, 71] },
274
+ { mimeType: "image/jpeg", bytes: [255, 216] },
275
+ { mimeType: "image/webp", bytes: [82, 73, 70, 70] }
276
+ ];
277
+ function detectImageMimeType(image) {
278
+ for (const { bytes, mimeType } of mimeTypeSignatures) {
279
+ if (image.length >= bytes.length && bytes.every((byte, index) => image[index] === byte)) {
280
+ return mimeType;
281
+ }
282
+ }
283
+ return void 0;
284
+ }
285
+
286
+ // core/prompt/data-content.ts
287
+ import {
288
+ convertBase64ToUint8Array,
289
+ convertUint8ArrayToBase64
290
+ } from "@ai-sdk/provider-utils";
291
+
292
+ // core/prompt/invalid-data-content-error.ts
293
+ import { AISDKError as AISDKError2 } from "@ai-sdk/provider";
294
+ var name2 = "AI_InvalidDataContentError";
295
+ var marker2 = `vercel.ai.error.${name2}`;
296
+ var symbol2 = Symbol.for(marker2);
297
+ var _a2;
298
+ var InvalidDataContentError = class extends AISDKError2 {
299
+ constructor({
300
+ content,
301
+ cause,
302
+ message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
303
+ }) {
304
+ super({ name: name2, message, cause });
305
+ this[_a2] = true;
306
+ this.content = content;
307
+ }
308
+ static isInstance(error) {
309
+ return AISDKError2.hasMarker(error, marker2);
310
+ }
311
+ };
312
+ _a2 = symbol2;
313
+
314
+ // core/prompt/data-content.ts
315
+ import { z } from "zod";
316
+ var dataContentSchema = z.union([
317
+ z.string(),
318
+ z.instanceof(Uint8Array),
319
+ z.instanceof(ArrayBuffer),
320
+ z.custom(
321
+ // Buffer might not be available in some environments such as CloudFlare:
322
+ (value) => {
323
+ var _a9, _b;
324
+ return (_b = (_a9 = globalThis.Buffer) == null ? void 0 : _a9.isBuffer(value)) != null ? _b : false;
325
+ },
326
+ { message: "Must be a Buffer" }
327
+ )
328
+ ]);
329
+ function convertDataContentToBase64String(content) {
330
+ if (typeof content === "string") {
331
+ return content;
332
+ }
333
+ if (content instanceof ArrayBuffer) {
334
+ return convertUint8ArrayToBase64(new Uint8Array(content));
335
+ }
336
+ return convertUint8ArrayToBase64(content);
337
+ }
338
+ function convertDataContentToUint8Array(content) {
339
+ if (content instanceof Uint8Array) {
340
+ return content;
341
+ }
342
+ if (typeof content === "string") {
343
+ try {
344
+ return convertBase64ToUint8Array(content);
345
+ } catch (error) {
346
+ throw new InvalidDataContentError({
347
+ message: "Invalid data content. Content string is not a base64-encoded media.",
348
+ content,
349
+ cause: error
350
+ });
351
+ }
352
+ }
353
+ if (content instanceof ArrayBuffer) {
354
+ return new Uint8Array(content);
355
+ }
356
+ throw new InvalidDataContentError({ content });
357
+ }
358
+ function convertUint8ArrayToText(uint8Array) {
359
+ try {
360
+ return new TextDecoder().decode(uint8Array);
361
+ } catch (error) {
362
+ throw new Error("Error decoding Uint8Array to text");
363
+ }
364
+ }
365
+
366
+ // core/prompt/invalid-message-role-error.ts
367
+ import { AISDKError as AISDKError3 } from "@ai-sdk/provider";
368
+ var name3 = "AI_InvalidMessageRoleError";
369
+ var marker3 = `vercel.ai.error.${name3}`;
370
+ var symbol3 = Symbol.for(marker3);
371
+ var _a3;
372
+ var InvalidMessageRoleError = class extends AISDKError3 {
373
+ constructor({
374
+ role,
375
+ message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
376
+ }) {
377
+ super({ name: name3, message });
378
+ this[_a3] = true;
379
+ this.role = role;
380
+ }
381
+ static isInstance(error) {
382
+ return AISDKError3.hasMarker(error, marker3);
383
+ }
384
+ };
385
+ _a3 = symbol3;
386
+
387
+ // core/prompt/split-data-url.ts
388
+ function splitDataUrl(dataUrl) {
389
+ try {
390
+ const [header, base64Content] = dataUrl.split(",");
391
+ return {
392
+ mimeType: header.split(";")[0].split(":")[1],
393
+ base64Content
394
+ };
395
+ } catch (error) {
396
+ return {
397
+ mimeType: void 0,
398
+ base64Content: void 0
399
+ };
400
+ }
401
+ }
402
+
403
+ // core/prompt/convert-to-language-model-prompt.ts
404
+ async function convertToLanguageModelPrompt({
405
+ prompt,
406
+ modelSupportsImageUrls = true,
407
+ modelSupportsUrl = () => false,
408
+ downloadImplementation = download
409
+ }) {
410
+ const downloadedAssets = await downloadAssets(
411
+ prompt.messages,
412
+ downloadImplementation,
413
+ modelSupportsImageUrls,
414
+ modelSupportsUrl
415
+ );
416
+ return [
417
+ ...prompt.system != null ? [{ role: "system", content: prompt.system }] : [],
418
+ ...prompt.messages.map(
419
+ (message) => convertToLanguageModelMessage(message, downloadedAssets)
420
+ )
421
+ ];
422
+ }
423
+ function convertToLanguageModelMessage(message, downloadedAssets) {
424
+ const role = message.role;
425
+ switch (role) {
426
+ case "system": {
427
+ return {
428
+ role: "system",
429
+ content: message.content,
430
+ providerMetadata: message.experimental_providerMetadata
431
+ };
432
+ }
433
+ case "user": {
434
+ if (typeof message.content === "string") {
435
+ return {
436
+ role: "user",
437
+ content: [{ type: "text", text: message.content }],
438
+ providerMetadata: message.experimental_providerMetadata
439
+ };
440
+ }
441
+ return {
442
+ role: "user",
443
+ content: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== "text" || part.text !== ""),
444
+ providerMetadata: message.experimental_providerMetadata
445
+ };
446
+ }
447
+ case "assistant": {
448
+ if (typeof message.content === "string") {
449
+ return {
450
+ role: "assistant",
451
+ content: [{ type: "text", text: message.content }],
452
+ providerMetadata: message.experimental_providerMetadata
453
+ };
454
+ }
455
+ return {
456
+ role: "assistant",
457
+ content: message.content.filter(
458
+ // remove empty text parts:
459
+ (part) => part.type !== "text" || part.text !== ""
460
+ ).map((part) => {
461
+ const { experimental_providerMetadata, ...rest } = part;
462
+ return {
463
+ ...rest,
464
+ providerMetadata: experimental_providerMetadata
465
+ };
466
+ }),
467
+ providerMetadata: message.experimental_providerMetadata
468
+ };
469
+ }
470
+ case "tool": {
471
+ return {
472
+ role: "tool",
473
+ content: message.content.map((part) => ({
474
+ type: "tool-result",
475
+ toolCallId: part.toolCallId,
476
+ toolName: part.toolName,
477
+ result: part.result,
478
+ content: part.experimental_content,
479
+ isError: part.isError,
480
+ providerMetadata: part.experimental_providerMetadata
481
+ })),
482
+ providerMetadata: message.experimental_providerMetadata
483
+ };
484
+ }
485
+ default: {
486
+ const _exhaustiveCheck = role;
487
+ throw new InvalidMessageRoleError({ role: _exhaustiveCheck });
488
+ }
489
+ }
490
+ }
491
+ async function downloadAssets(messages, downloadImplementation, modelSupportsImageUrls, modelSupportsUrl) {
492
+ const urls = messages.filter((message) => message.role === "user").map((message) => message.content).filter(
493
+ (content) => Array.isArray(content)
494
+ ).flat().filter(
495
+ (part) => part.type === "image" || part.type === "file"
496
+ ).filter(
497
+ (part) => !(part.type === "image" && modelSupportsImageUrls === true)
498
+ ).map((part) => part.type === "image" ? part.image : part.data).map(
499
+ (part) => (
500
+ // support string urls:
501
+ typeof part === "string" && (part.startsWith("http:") || part.startsWith("https:")) ? new URL(part) : part
502
+ )
503
+ ).filter((image) => image instanceof URL).filter((url) => !modelSupportsUrl(url));
504
+ const downloadedImages = await Promise.all(
505
+ urls.map(async (url) => ({
506
+ url,
507
+ data: await downloadImplementation({ url })
508
+ }))
509
+ );
510
+ return Object.fromEntries(
511
+ downloadedImages.map(({ url, data }) => [url.toString(), data])
512
+ );
513
+ }
514
+ function convertPartToLanguageModelPart(part, downloadedAssets) {
515
+ var _a9;
516
+ if (part.type === "text") {
517
+ return {
518
+ type: "text",
519
+ text: part.text,
520
+ providerMetadata: part.experimental_providerMetadata
521
+ };
522
+ }
523
+ let mimeType = part.mimeType;
524
+ let data;
525
+ let content;
526
+ let normalizedData;
527
+ const type = part.type;
528
+ switch (type) {
529
+ case "image":
530
+ data = part.image;
531
+ break;
532
+ case "file":
533
+ data = part.data;
534
+ break;
535
+ default:
536
+ throw new Error(`Unsupported part type: ${type}`);
537
+ }
538
+ try {
539
+ content = typeof data === "string" ? new URL(data) : data;
540
+ } catch (error) {
541
+ content = data;
542
+ }
543
+ if (content instanceof URL) {
544
+ if (content.protocol === "data:") {
545
+ const { mimeType: dataUrlMimeType, base64Content } = splitDataUrl(
546
+ content.toString()
547
+ );
548
+ if (dataUrlMimeType == null || base64Content == null) {
549
+ throw new Error(`Invalid data URL format in part ${type}`);
550
+ }
551
+ mimeType = dataUrlMimeType;
552
+ normalizedData = convertDataContentToUint8Array(base64Content);
553
+ } else {
554
+ const downloadedFile = downloadedAssets[content.toString()];
555
+ if (downloadedFile) {
556
+ normalizedData = downloadedFile.data;
557
+ mimeType != null ? mimeType : mimeType = downloadedFile.mimeType;
558
+ } else {
559
+ normalizedData = content;
560
+ }
561
+ }
562
+ } else {
563
+ normalizedData = convertDataContentToUint8Array(content);
564
+ }
565
+ switch (type) {
566
+ case "image": {
567
+ if (normalizedData instanceof Uint8Array) {
568
+ mimeType = (_a9 = detectImageMimeType(normalizedData)) != null ? _a9 : mimeType;
569
+ }
570
+ return {
571
+ type: "image",
572
+ image: normalizedData,
573
+ mimeType,
574
+ providerMetadata: part.experimental_providerMetadata
575
+ };
576
+ }
577
+ case "file": {
578
+ if (mimeType == null) {
579
+ throw new Error(`Mime type is missing for file part`);
580
+ }
581
+ return {
582
+ type: "file",
583
+ data: normalizedData instanceof Uint8Array ? convertDataContentToBase64String(normalizedData) : normalizedData,
584
+ mimeType,
585
+ providerMetadata: part.experimental_providerMetadata
586
+ };
587
+ }
588
+ }
589
+ }
590
+
591
+ // errors/invalid-argument-error.ts
592
+ import { AISDKError as AISDKError4 } from "@ai-sdk/provider";
593
+ var name4 = "AI_InvalidArgumentError";
594
+ var marker4 = `vercel.ai.error.${name4}`;
595
+ var symbol4 = Symbol.for(marker4);
596
+ var _a4;
597
+ var InvalidArgumentError = class extends AISDKError4 {
598
+ constructor({
599
+ parameter,
600
+ value,
601
+ message
602
+ }) {
603
+ super({
604
+ name: name4,
605
+ message: `Invalid argument for parameter ${parameter}: ${message}`
606
+ });
607
+ this[_a4] = true;
608
+ this.parameter = parameter;
609
+ this.value = value;
610
+ }
611
+ static isInstance(error) {
612
+ return AISDKError4.hasMarker(error, marker4);
613
+ }
614
+ };
615
+ _a4 = symbol4;
616
+
617
+ // core/prompt/prepare-call-settings.ts
618
+ function prepareCallSettings({
619
+ maxTokens,
620
+ temperature,
621
+ topP,
622
+ topK,
623
+ presencePenalty,
624
+ frequencyPenalty,
625
+ stopSequences,
626
+ seed
627
+ }) {
628
+ if (maxTokens != null) {
629
+ if (!Number.isInteger(maxTokens)) {
630
+ throw new InvalidArgumentError({
631
+ parameter: "maxTokens",
632
+ value: maxTokens,
633
+ message: "maxTokens must be an integer"
634
+ });
635
+ }
636
+ if (maxTokens < 1) {
637
+ throw new InvalidArgumentError({
638
+ parameter: "maxTokens",
639
+ value: maxTokens,
640
+ message: "maxTokens must be >= 1"
641
+ });
642
+ }
643
+ }
644
+ if (temperature != null) {
645
+ if (typeof temperature !== "number") {
646
+ throw new InvalidArgumentError({
647
+ parameter: "temperature",
648
+ value: temperature,
649
+ message: "temperature must be a number"
650
+ });
651
+ }
652
+ }
653
+ if (topP != null) {
654
+ if (typeof topP !== "number") {
655
+ throw new InvalidArgumentError({
656
+ parameter: "topP",
657
+ value: topP,
658
+ message: "topP must be a number"
659
+ });
660
+ }
661
+ }
662
+ if (topK != null) {
663
+ if (typeof topK !== "number") {
664
+ throw new InvalidArgumentError({
665
+ parameter: "topK",
666
+ value: topK,
667
+ message: "topK must be a number"
668
+ });
669
+ }
670
+ }
671
+ if (presencePenalty != null) {
672
+ if (typeof presencePenalty !== "number") {
673
+ throw new InvalidArgumentError({
674
+ parameter: "presencePenalty",
675
+ value: presencePenalty,
676
+ message: "presencePenalty must be a number"
677
+ });
678
+ }
679
+ }
680
+ if (frequencyPenalty != null) {
681
+ if (typeof frequencyPenalty !== "number") {
682
+ throw new InvalidArgumentError({
683
+ parameter: "frequencyPenalty",
684
+ value: frequencyPenalty,
685
+ message: "frequencyPenalty must be a number"
686
+ });
687
+ }
688
+ }
689
+ if (seed != null) {
690
+ if (!Number.isInteger(seed)) {
691
+ throw new InvalidArgumentError({
692
+ parameter: "seed",
693
+ value: seed,
694
+ message: "seed must be an integer"
695
+ });
696
+ }
697
+ }
698
+ return {
699
+ maxTokens,
700
+ temperature: temperature != null ? temperature : 0,
701
+ topP,
702
+ topK,
703
+ presencePenalty,
704
+ frequencyPenalty,
705
+ stopSequences: stopSequences != null && stopSequences.length > 0 ? stopSequences : void 0,
706
+ seed
707
+ };
708
+ }
709
+
710
+ // util/retry-with-exponential-backoff.ts
711
+ import { APICallError } from "@ai-sdk/provider";
712
+ import { getErrorMessage, isAbortError } from "@ai-sdk/provider-utils";
713
+
714
+ // util/delay.ts
715
+ async function delay(delayInMs) {
716
+ return delayInMs == null ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, delayInMs));
717
+ }
718
+
719
+ // util/retry-error.ts
720
+ import { AISDKError as AISDKError5 } from "@ai-sdk/provider";
721
+ var name5 = "AI_RetryError";
722
+ var marker5 = `vercel.ai.error.${name5}`;
723
+ var symbol5 = Symbol.for(marker5);
724
+ var _a5;
725
+ var RetryError = class extends AISDKError5 {
726
+ constructor({
727
+ message,
728
+ reason,
729
+ errors
730
+ }) {
731
+ super({ name: name5, message });
732
+ this[_a5] = true;
733
+ this.reason = reason;
734
+ this.errors = errors;
735
+ this.lastError = errors[errors.length - 1];
736
+ }
737
+ static isInstance(error) {
738
+ return AISDKError5.hasMarker(error, marker5);
739
+ }
740
+ };
741
+ _a5 = symbol5;
742
+
743
+ // util/retry-with-exponential-backoff.ts
744
+ var retryWithExponentialBackoff = ({
745
+ maxRetries = 2,
746
+ initialDelayInMs = 2e3,
747
+ backoffFactor = 2
748
+ } = {}) => async (f) => _retryWithExponentialBackoff(f, {
749
+ maxRetries,
750
+ delayInMs: initialDelayInMs,
751
+ backoffFactor
752
+ });
753
+ async function _retryWithExponentialBackoff(f, {
754
+ maxRetries,
755
+ delayInMs,
756
+ backoffFactor
757
+ }, errors = []) {
758
+ try {
759
+ return await f();
760
+ } catch (error) {
761
+ if (isAbortError(error)) {
762
+ throw error;
763
+ }
764
+ if (maxRetries === 0) {
765
+ throw error;
766
+ }
767
+ const errorMessage = getErrorMessage(error);
768
+ const newErrors = [...errors, error];
769
+ const tryNumber = newErrors.length;
770
+ if (tryNumber > maxRetries) {
771
+ throw new RetryError({
772
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
773
+ reason: "maxRetriesExceeded",
774
+ errors: newErrors
775
+ });
776
+ }
777
+ if (error instanceof Error && APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
778
+ await delay(delayInMs);
779
+ return _retryWithExponentialBackoff(
780
+ f,
781
+ { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
782
+ newErrors
783
+ );
784
+ }
785
+ if (tryNumber === 1) {
786
+ throw error;
787
+ }
788
+ throw new RetryError({
789
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
790
+ reason: "errorNotRetryable",
791
+ errors: newErrors
792
+ });
793
+ }
794
+ }
795
+
796
+ // core/prompt/prepare-retries.ts
797
+ function prepareRetries({
798
+ maxRetries
799
+ }) {
800
+ if (maxRetries != null) {
801
+ if (!Number.isInteger(maxRetries)) {
802
+ throw new InvalidArgumentError({
803
+ parameter: "maxRetries",
804
+ value: maxRetries,
805
+ message: "maxRetries must be an integer"
806
+ });
807
+ }
808
+ if (maxRetries < 0) {
809
+ throw new InvalidArgumentError({
810
+ parameter: "maxRetries",
811
+ value: maxRetries,
812
+ message: "maxRetries must be >= 0"
813
+ });
814
+ }
815
+ }
816
+ const maxRetriesResult = maxRetries != null ? maxRetries : 2;
817
+ return {
818
+ maxRetries: maxRetriesResult,
819
+ retry: retryWithExponentialBackoff({ maxRetries: maxRetriesResult })
820
+ };
821
+ }
822
+
823
+ // core/prompt/prepare-tools-and-tool-choice.ts
824
+ import { asSchema } from "@ai-sdk/ui-utils";
825
+
826
+ // core/util/is-non-empty-object.ts
827
+ function isNonEmptyObject(object) {
828
+ return object != null && Object.keys(object).length > 0;
829
+ }
830
+
831
+ // core/prompt/prepare-tools-and-tool-choice.ts
832
+ function prepareToolsAndToolChoice({
833
+ tools,
834
+ toolChoice,
835
+ activeTools
836
+ }) {
837
+ if (!isNonEmptyObject(tools)) {
838
+ return {
839
+ tools: void 0,
840
+ toolChoice: void 0
841
+ };
842
+ }
843
+ const filteredTools = activeTools != null ? Object.entries(tools).filter(
844
+ ([name9]) => activeTools.includes(name9)
845
+ ) : Object.entries(tools);
846
+ return {
847
+ tools: filteredTools.map(([name9, tool]) => {
848
+ const toolType = tool.type;
849
+ switch (toolType) {
850
+ case void 0:
851
+ case "function":
852
+ return {
853
+ type: "function",
854
+ name: name9,
855
+ description: tool.description,
856
+ parameters: asSchema(tool.parameters).jsonSchema
857
+ };
858
+ case "provider-defined":
859
+ return {
860
+ type: "provider-defined",
861
+ name: name9,
862
+ id: tool.id,
863
+ args: tool.args
864
+ };
865
+ default: {
866
+ const exhaustiveCheck = toolType;
867
+ throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);
868
+ }
869
+ }
870
+ }),
871
+ toolChoice: toolChoice == null ? { type: "auto" } : typeof toolChoice === "string" ? { type: toolChoice } : { type: "tool", toolName: toolChoice.toolName }
872
+ };
873
+ }
874
+
875
+ // core/prompt/standardize-prompt.ts
876
+ import { InvalidPromptError } from "@ai-sdk/provider";
877
+ import { safeValidateTypes } from "@ai-sdk/provider-utils";
878
+ import { z as z7 } from "zod";
879
+
880
+ // core/prompt/message.ts
881
+ import { z as z6 } from "zod";
882
+
883
+ // core/types/provider-metadata.ts
884
+ import { z as z3 } from "zod";
885
+
886
+ // core/types/json-value.ts
887
+ import { z as z2 } from "zod";
888
+ var jsonValueSchema = z2.lazy(
889
+ () => z2.union([
890
+ z2.null(),
891
+ z2.string(),
892
+ z2.number(),
893
+ z2.boolean(),
894
+ z2.record(z2.string(), jsonValueSchema),
895
+ z2.array(jsonValueSchema)
896
+ ])
897
+ );
898
+
899
+ // core/types/provider-metadata.ts
900
+ var providerMetadataSchema = z3.record(
901
+ z3.string(),
902
+ z3.record(z3.string(), jsonValueSchema)
903
+ );
904
+
905
+ // core/prompt/content-part.ts
906
+ import { z as z5 } from "zod";
907
+
908
+ // core/prompt/tool-result-content.ts
909
+ import { z as z4 } from "zod";
910
+ var toolResultContentSchema = z4.array(
911
+ z4.union([
912
+ z4.object({ type: z4.literal("text"), text: z4.string() }),
913
+ z4.object({
914
+ type: z4.literal("image"),
915
+ data: z4.string(),
916
+ mimeType: z4.string().optional()
917
+ })
918
+ ])
919
+ );
920
+
921
+ // core/prompt/content-part.ts
922
+ var textPartSchema = z5.object({
923
+ type: z5.literal("text"),
924
+ text: z5.string(),
925
+ experimental_providerMetadata: providerMetadataSchema.optional()
926
+ });
927
+ var imagePartSchema = z5.object({
928
+ type: z5.literal("image"),
929
+ image: z5.union([dataContentSchema, z5.instanceof(URL)]),
930
+ mimeType: z5.string().optional(),
931
+ experimental_providerMetadata: providerMetadataSchema.optional()
932
+ });
933
+ var filePartSchema = z5.object({
934
+ type: z5.literal("file"),
935
+ data: z5.union([dataContentSchema, z5.instanceof(URL)]),
936
+ mimeType: z5.string(),
937
+ experimental_providerMetadata: providerMetadataSchema.optional()
938
+ });
939
+ var toolCallPartSchema = z5.object({
940
+ type: z5.literal("tool-call"),
941
+ toolCallId: z5.string(),
942
+ toolName: z5.string(),
943
+ args: z5.unknown()
944
+ });
945
+ var toolResultPartSchema = z5.object({
946
+ type: z5.literal("tool-result"),
947
+ toolCallId: z5.string(),
948
+ toolName: z5.string(),
949
+ result: z5.unknown(),
950
+ content: toolResultContentSchema.optional(),
951
+ isError: z5.boolean().optional(),
952
+ experimental_providerMetadata: providerMetadataSchema.optional()
953
+ });
954
+
955
+ // core/prompt/message.ts
956
+ var coreSystemMessageSchema = z6.object({
957
+ role: z6.literal("system"),
958
+ content: z6.string(),
959
+ experimental_providerMetadata: providerMetadataSchema.optional()
960
+ });
961
+ var coreUserMessageSchema = z6.object({
962
+ role: z6.literal("user"),
963
+ content: z6.union([
964
+ z6.string(),
965
+ z6.array(z6.union([textPartSchema, imagePartSchema, filePartSchema]))
966
+ ]),
967
+ experimental_providerMetadata: providerMetadataSchema.optional()
968
+ });
969
+ var coreAssistantMessageSchema = z6.object({
970
+ role: z6.literal("assistant"),
971
+ content: z6.union([
972
+ z6.string(),
973
+ z6.array(z6.union([textPartSchema, toolCallPartSchema]))
974
+ ]),
975
+ experimental_providerMetadata: providerMetadataSchema.optional()
976
+ });
977
+ var coreToolMessageSchema = z6.object({
978
+ role: z6.literal("tool"),
979
+ content: z6.array(toolResultPartSchema),
980
+ experimental_providerMetadata: providerMetadataSchema.optional()
981
+ });
982
+ var coreMessageSchema = z6.union([
983
+ coreSystemMessageSchema,
984
+ coreUserMessageSchema,
985
+ coreAssistantMessageSchema,
986
+ coreToolMessageSchema
987
+ ]);
988
+
989
+ // core/prompt/detect-prompt-type.ts
990
+ function detectPromptType(prompt) {
991
+ if (!Array.isArray(prompt)) {
992
+ return "other";
993
+ }
994
+ if (prompt.length === 0) {
995
+ return "messages";
996
+ }
997
+ const characteristics = prompt.map(detectSingleMessageCharacteristics);
998
+ if (characteristics.some((c) => c === "has-ui-specific-parts")) {
999
+ return "ui-messages";
1000
+ } else if (characteristics.every(
1001
+ (c) => c === "has-core-specific-parts" || c === "message"
1002
+ )) {
1003
+ return "messages";
1004
+ } else {
1005
+ return "other";
1006
+ }
1007
+ }
1008
+ function detectSingleMessageCharacteristics(message) {
1009
+ if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
1010
+ message.role === "data" || // UI-only role
1011
+ "toolInvocations" in message || // UI-specific field
1012
+ "experimental_attachments" in message)) {
1013
+ return "has-ui-specific-parts";
1014
+ } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
1015
+ "experimental_providerMetadata" in message)) {
1016
+ return "has-core-specific-parts";
1017
+ } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
1018
+ return "message";
1019
+ } else {
1020
+ return "other";
1021
+ }
1022
+ }
1023
+
1024
+ // core/prompt/attachments-to-parts.ts
1025
+ function attachmentsToParts(attachments) {
1026
+ var _a9, _b, _c;
1027
+ const parts = [];
1028
+ for (const attachment of attachments) {
1029
+ let url;
1030
+ try {
1031
+ url = new URL(attachment.url);
1032
+ } catch (error) {
1033
+ throw new Error(`Invalid URL: ${attachment.url}`);
1034
+ }
1035
+ switch (url.protocol) {
1036
+ case "http:":
1037
+ case "https:": {
1038
+ if ((_a9 = attachment.contentType) == null ? void 0 : _a9.startsWith("image/")) {
1039
+ parts.push({ type: "image", image: url });
1040
+ } else {
1041
+ if (!attachment.contentType) {
1042
+ throw new Error(
1043
+ "If the attachment is not an image, it must specify a content type"
1044
+ );
1045
+ }
1046
+ parts.push({
1047
+ type: "file",
1048
+ data: url,
1049
+ mimeType: attachment.contentType
1050
+ });
1051
+ }
1052
+ break;
1053
+ }
1054
+ case "data:": {
1055
+ let header;
1056
+ let base64Content;
1057
+ let mimeType;
1058
+ try {
1059
+ [header, base64Content] = attachment.url.split(",");
1060
+ mimeType = header.split(";")[0].split(":")[1];
1061
+ } catch (error) {
1062
+ throw new Error(`Error processing data URL: ${attachment.url}`);
1063
+ }
1064
+ if (mimeType == null || base64Content == null) {
1065
+ throw new Error(`Invalid data URL format: ${attachment.url}`);
1066
+ }
1067
+ if ((_b = attachment.contentType) == null ? void 0 : _b.startsWith("image/")) {
1068
+ parts.push({
1069
+ type: "image",
1070
+ image: convertDataContentToUint8Array(base64Content)
1071
+ });
1072
+ } else if ((_c = attachment.contentType) == null ? void 0 : _c.startsWith("text/")) {
1073
+ parts.push({
1074
+ type: "text",
1075
+ text: convertUint8ArrayToText(
1076
+ convertDataContentToUint8Array(base64Content)
1077
+ )
1078
+ });
1079
+ } else {
1080
+ if (!attachment.contentType) {
1081
+ throw new Error(
1082
+ "If the attachment is not an image or text, it must specify a content type"
1083
+ );
1084
+ }
1085
+ parts.push({
1086
+ type: "file",
1087
+ data: base64Content,
1088
+ mimeType: attachment.contentType
1089
+ });
1090
+ }
1091
+ break;
1092
+ }
1093
+ default: {
1094
+ throw new Error(`Unsupported URL protocol: ${url.protocol}`);
1095
+ }
1096
+ }
1097
+ }
1098
+ return parts;
1099
+ }
1100
+
1101
+ // core/prompt/message-conversion-error.ts
1102
+ import { AISDKError as AISDKError6 } from "@ai-sdk/provider";
1103
+ var name6 = "AI_MessageConversionError";
1104
+ var marker6 = `vercel.ai.error.${name6}`;
1105
+ var symbol6 = Symbol.for(marker6);
1106
+ var _a6;
1107
+ var MessageConversionError = class extends AISDKError6 {
1108
+ constructor({
1109
+ originalMessage,
1110
+ message
1111
+ }) {
1112
+ super({ name: name6, message });
1113
+ this[_a6] = true;
1114
+ this.originalMessage = originalMessage;
1115
+ }
1116
+ static isInstance(error) {
1117
+ return AISDKError6.hasMarker(error, marker6);
1118
+ }
1119
+ };
1120
+ _a6 = symbol6;
1121
+
1122
+ // core/prompt/convert-to-core-messages.ts
1123
+ function convertToCoreMessages(messages, options) {
1124
+ var _a9;
1125
+ const tools = (_a9 = options == null ? void 0 : options.tools) != null ? _a9 : {};
1126
+ const coreMessages = [];
1127
+ for (const message of messages) {
1128
+ const { role, content, toolInvocations, experimental_attachments } = message;
1129
+ switch (role) {
1130
+ case "system": {
1131
+ coreMessages.push({
1132
+ role: "system",
1133
+ content
1134
+ });
1135
+ break;
1136
+ }
1137
+ case "user": {
1138
+ coreMessages.push({
1139
+ role: "user",
1140
+ content: experimental_attachments ? [
1141
+ { type: "text", text: content },
1142
+ ...attachmentsToParts(experimental_attachments)
1143
+ ] : content
1144
+ });
1145
+ break;
1146
+ }
1147
+ case "assistant": {
1148
+ if (toolInvocations == null) {
1149
+ coreMessages.push({ role: "assistant", content });
1150
+ break;
1151
+ }
1152
+ coreMessages.push({
1153
+ role: "assistant",
1154
+ content: [
1155
+ { type: "text", text: content },
1156
+ ...toolInvocations.map(
1157
+ ({ toolCallId, toolName, args }) => ({
1158
+ type: "tool-call",
1159
+ toolCallId,
1160
+ toolName,
1161
+ args
1162
+ })
1163
+ )
1164
+ ]
1165
+ });
1166
+ coreMessages.push({
1167
+ role: "tool",
1168
+ content: toolInvocations.map((toolInvocation) => {
1169
+ if (!("result" in toolInvocation)) {
1170
+ throw new MessageConversionError({
1171
+ originalMessage: message,
1172
+ message: "ToolInvocation must have a result: " + JSON.stringify(toolInvocation)
1173
+ });
1174
+ }
1175
+ const { toolCallId, toolName, result } = toolInvocation;
1176
+ const tool = tools[toolName];
1177
+ return (tool == null ? void 0 : tool.experimental_toToolResultContent) != null ? {
1178
+ type: "tool-result",
1179
+ toolCallId,
1180
+ toolName,
1181
+ result: tool.experimental_toToolResultContent(result),
1182
+ experimental_content: tool.experimental_toToolResultContent(result)
1183
+ } : {
1184
+ type: "tool-result",
1185
+ toolCallId,
1186
+ toolName,
1187
+ result
1188
+ };
1189
+ })
1190
+ });
1191
+ break;
1192
+ }
1193
+ case "data": {
1194
+ break;
1195
+ }
1196
+ default: {
1197
+ const _exhaustiveCheck = role;
1198
+ throw new MessageConversionError({
1199
+ originalMessage: message,
1200
+ message: `Unsupported role: ${_exhaustiveCheck}`
1201
+ });
1202
+ }
1203
+ }
1204
+ }
1205
+ return coreMessages;
1206
+ }
1207
+
1208
+ // core/prompt/standardize-prompt.ts
1209
+ function standardizePrompt({
1210
+ prompt,
1211
+ tools
1212
+ }) {
1213
+ if (prompt.prompt == null && prompt.messages == null) {
1214
+ throw new InvalidPromptError({
1215
+ prompt,
1216
+ message: "prompt or messages must be defined"
1217
+ });
1218
+ }
1219
+ if (prompt.prompt != null && prompt.messages != null) {
1220
+ throw new InvalidPromptError({
1221
+ prompt,
1222
+ message: "prompt and messages cannot be defined at the same time"
1223
+ });
1224
+ }
1225
+ if (prompt.system != null && typeof prompt.system !== "string") {
1226
+ throw new InvalidPromptError({
1227
+ prompt,
1228
+ message: "system must be a string"
1229
+ });
1230
+ }
1231
+ if (prompt.prompt != null) {
1232
+ if (typeof prompt.prompt !== "string") {
1233
+ throw new InvalidPromptError({
1234
+ prompt,
1235
+ message: "prompt must be a string"
1236
+ });
1237
+ }
1238
+ return {
1239
+ type: "prompt",
1240
+ system: prompt.system,
1241
+ messages: [
1242
+ {
1243
+ role: "user",
1244
+ content: prompt.prompt
1245
+ }
1246
+ ]
1247
+ };
1248
+ }
1249
+ if (prompt.messages != null) {
1250
+ const promptType = detectPromptType(prompt.messages);
1251
+ if (promptType === "other") {
1252
+ throw new InvalidPromptError({
1253
+ prompt,
1254
+ message: "messages must be an array of CoreMessage or UIMessage"
1255
+ });
1256
+ }
1257
+ const messages = promptType === "ui-messages" ? convertToCoreMessages(prompt.messages, {
1258
+ tools
1259
+ }) : prompt.messages;
1260
+ const validationResult = safeValidateTypes({
1261
+ value: messages,
1262
+ schema: z7.array(coreMessageSchema)
1263
+ });
1264
+ if (!validationResult.success) {
1265
+ throw new InvalidPromptError({
1266
+ prompt,
1267
+ message: "messages must be an array of CoreMessage or UIMessage",
1268
+ cause: validationResult.error
1269
+ });
1270
+ }
1271
+ return {
1272
+ type: "messages",
1273
+ messages,
1274
+ system: prompt.system
1275
+ };
1276
+ }
1277
+ throw new Error("unreachable");
1278
+ }
1279
+
1280
+ // core/types/usage.ts
1281
+ function calculateLanguageModelUsage({
1282
+ promptTokens,
1283
+ completionTokens
1284
+ }) {
1285
+ return {
1286
+ promptTokens,
1287
+ completionTokens,
1288
+ totalTokens: promptTokens + completionTokens
1289
+ };
1290
+ }
1291
+
1292
+ // errors/invalid-tool-arguments-error.ts
1293
+ import { AISDKError as AISDKError7, getErrorMessage as getErrorMessage2 } from "@ai-sdk/provider";
1294
+ var name7 = "AI_InvalidToolArgumentsError";
1295
+ var marker7 = `vercel.ai.error.${name7}`;
1296
+ var symbol7 = Symbol.for(marker7);
1297
+ var _a7;
1298
+ var InvalidToolArgumentsError = class extends AISDKError7 {
1299
+ constructor({
1300
+ toolArgs,
1301
+ toolName,
1302
+ cause,
1303
+ message = `Invalid arguments for tool ${toolName}: ${getErrorMessage2(
1304
+ cause
1305
+ )}`
1306
+ }) {
1307
+ super({ name: name7, message, cause });
1308
+ this[_a7] = true;
1309
+ this.toolArgs = toolArgs;
1310
+ this.toolName = toolName;
1311
+ }
1312
+ static isInstance(error) {
1313
+ return AISDKError7.hasMarker(error, marker7);
1314
+ }
1315
+ };
1316
+ _a7 = symbol7;
1317
+
1318
+ // errors/no-such-tool-error.ts
1319
+ import { AISDKError as AISDKError8 } from "@ai-sdk/provider";
1320
+ var name8 = "AI_NoSuchToolError";
1321
+ var marker8 = `vercel.ai.error.${name8}`;
1322
+ var symbol8 = Symbol.for(marker8);
1323
+ var _a8;
1324
+ var NoSuchToolError = class extends AISDKError8 {
1325
+ constructor({
1326
+ toolName,
1327
+ availableTools = void 0,
1328
+ message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}`
1329
+ }) {
1330
+ super({ name: name8, message });
1331
+ this[_a8] = true;
1332
+ this.toolName = toolName;
1333
+ this.availableTools = availableTools;
1334
+ }
1335
+ static isInstance(error) {
1336
+ return AISDKError8.hasMarker(error, marker8);
1337
+ }
1338
+ };
1339
+ _a8 = symbol8;
1340
+
1341
+ // util/is-async-generator.ts
1342
+ function isAsyncGenerator(value) {
1343
+ return value != null && typeof value === "object" && Symbol.asyncIterator in value;
1344
+ }
1345
+
1346
+ // util/is-generator.ts
1347
+ function isGenerator(value) {
1348
+ return value != null && typeof value === "object" && Symbol.iterator in value;
1349
+ }
1350
+
1351
+ // util/constants.ts
1352
+ var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
1353
+
1354
+ // rsc/streamable-ui/create-suspended-chunk.tsx
1355
+ import { Suspense } from "react";
1356
+ import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
1357
+ var R = [
1358
+ async ({
1359
+ c: current,
1360
+ n: next
1361
+ }) => {
1362
+ const chunk = await next;
1363
+ if (chunk.done) {
1364
+ return chunk.value;
1365
+ }
1366
+ if (chunk.append) {
1367
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1368
+ current,
1369
+ /* @__PURE__ */ jsx2(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx2(R, { c: chunk.value, n: chunk.next }) })
1370
+ ] });
1371
+ }
1372
+ return /* @__PURE__ */ jsx2(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx2(R, { c: chunk.value, n: chunk.next }) });
1373
+ }
1374
+ ][0];
1375
+ function createSuspendedChunk(initialValue) {
1376
+ const { promise, resolve, reject } = createResolvablePromise();
1377
+ return {
1378
+ row: /* @__PURE__ */ jsx2(Suspense, { fallback: initialValue, children: /* @__PURE__ */ jsx2(R, { c: initialValue, n: promise }) }),
1379
+ resolve,
1380
+ reject
1381
+ };
1382
+ }
1383
+
1384
+ // rsc/streamable-ui/create-streamable-ui.tsx
1385
+ function createStreamableUI(initialValue) {
1386
+ let currentValue = initialValue;
1387
+ let closed = false;
1388
+ let { row, resolve, reject } = createSuspendedChunk(initialValue);
1389
+ function assertStream(method) {
1390
+ if (closed) {
1391
+ throw new Error(method + ": UI stream is already closed.");
1392
+ }
1393
+ }
1394
+ let warningTimeout;
1395
+ function warnUnclosedStream() {
1396
+ if (process.env.NODE_ENV === "development") {
1397
+ if (warningTimeout) {
1398
+ clearTimeout(warningTimeout);
1399
+ }
1400
+ warningTimeout = setTimeout(() => {
1401
+ console.warn(
1402
+ "The streamable UI has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`."
1403
+ );
1404
+ }, HANGING_STREAM_WARNING_TIME_MS);
1405
+ }
1406
+ }
1407
+ warnUnclosedStream();
1408
+ const streamable = {
1409
+ value: row,
1410
+ update(value) {
1411
+ assertStream(".update()");
1412
+ if (value === currentValue) {
1413
+ warnUnclosedStream();
1414
+ return streamable;
1415
+ }
1416
+ const resolvable = createResolvablePromise();
1417
+ currentValue = value;
1418
+ resolve({ value: currentValue, done: false, next: resolvable.promise });
1419
+ resolve = resolvable.resolve;
1420
+ reject = resolvable.reject;
1421
+ warnUnclosedStream();
1422
+ return streamable;
1423
+ },
1424
+ append(value) {
1425
+ assertStream(".append()");
1426
+ const resolvable = createResolvablePromise();
1427
+ currentValue = value;
1428
+ resolve({ value, done: false, append: true, next: resolvable.promise });
1429
+ resolve = resolvable.resolve;
1430
+ reject = resolvable.reject;
1431
+ warnUnclosedStream();
1432
+ return streamable;
1433
+ },
1434
+ error(error) {
1435
+ assertStream(".error()");
1436
+ if (warningTimeout) {
1437
+ clearTimeout(warningTimeout);
1438
+ }
1439
+ closed = true;
1440
+ reject(error);
1441
+ return streamable;
1442
+ },
1443
+ done(...args) {
1444
+ assertStream(".done()");
1445
+ if (warningTimeout) {
1446
+ clearTimeout(warningTimeout);
1447
+ }
1448
+ closed = true;
1449
+ if (args.length) {
1450
+ resolve({ value: args[0], done: true });
1451
+ return streamable;
1452
+ }
1453
+ resolve({ value: currentValue, done: true });
1454
+ return streamable;
1455
+ }
1456
+ };
1457
+ return streamable;
1458
+ }
1459
+
1460
+ // rsc/stream-ui/stream-ui.tsx
1461
+ var defaultTextRenderer = ({ content }) => content;
1462
+ async function streamUI({
1463
+ model,
1464
+ tools,
1465
+ toolChoice,
1466
+ system,
1467
+ prompt,
1468
+ messages,
1469
+ maxRetries,
1470
+ abortSignal,
1471
+ headers,
1472
+ initial,
1473
+ text,
1474
+ experimental_providerMetadata: providerMetadata,
1475
+ onFinish,
1476
+ ...settings
1477
+ }) {
1478
+ if (typeof model === "string") {
1479
+ throw new Error(
1480
+ "`model` cannot be a string in `streamUI`. Use the actual model instance instead."
1481
+ );
1482
+ }
1483
+ if ("functions" in settings) {
1484
+ throw new Error(
1485
+ "`functions` is not supported in `streamUI`, use `tools` instead."
1486
+ );
1487
+ }
1488
+ if ("provider" in settings) {
1489
+ throw new Error(
1490
+ "`provider` is no longer needed in `streamUI`. Use `model` instead."
1491
+ );
1492
+ }
1493
+ if (tools) {
1494
+ for (const [name9, tool] of Object.entries(tools)) {
1495
+ if ("render" in tool) {
1496
+ throw new Error(
1497
+ "Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: " + name9
1498
+ );
1499
+ }
1500
+ }
1501
+ }
1502
+ const ui = createStreamableUI(initial);
1503
+ const textRender = text || defaultTextRenderer;
1504
+ let finished;
1505
+ let finishEvent = null;
1506
+ async function render({
1507
+ args,
1508
+ renderer,
1509
+ streamableUI,
1510
+ isLastCall = false
1511
+ }) {
1512
+ if (!renderer)
1513
+ return;
1514
+ const renderFinished = createResolvablePromise();
1515
+ finished = finished ? finished.then(() => renderFinished.promise) : renderFinished.promise;
1516
+ const rendererResult = renderer(...args);
1517
+ if (isAsyncGenerator(rendererResult) || isGenerator(rendererResult)) {
1518
+ while (true) {
1519
+ const { done, value } = await rendererResult.next();
1520
+ const node = await value;
1521
+ if (isLastCall && done) {
1522
+ streamableUI.done(node);
1523
+ } else {
1524
+ streamableUI.update(node);
1525
+ }
1526
+ if (done)
1527
+ break;
1528
+ }
1529
+ } else {
1530
+ const node = await rendererResult;
1531
+ if (isLastCall) {
1532
+ streamableUI.done(node);
1533
+ } else {
1534
+ streamableUI.update(node);
1535
+ }
1536
+ }
1537
+ renderFinished.resolve(void 0);
1538
+ }
1539
+ const { retry } = prepareRetries({ maxRetries });
1540
+ const validatedPrompt = standardizePrompt({
1541
+ prompt: { system, prompt, messages },
1542
+ tools: void 0
1543
+ // streamUI tools don't support multi-modal tool result conversion
1544
+ });
1545
+ const result = await retry(
1546
+ async () => model.doStream({
1547
+ mode: {
1548
+ type: "regular",
1549
+ ...prepareToolsAndToolChoice({
1550
+ tools,
1551
+ toolChoice,
1552
+ activeTools: void 0
1553
+ })
1554
+ },
1555
+ ...prepareCallSettings(settings),
1556
+ inputFormat: validatedPrompt.type,
1557
+ prompt: await convertToLanguageModelPrompt({
1558
+ prompt: validatedPrompt,
1559
+ modelSupportsImageUrls: model.supportsImageUrls,
1560
+ modelSupportsUrl: model.supportsUrl
1561
+ }),
1562
+ providerMetadata,
1563
+ abortSignal,
1564
+ headers
1565
+ })
1566
+ );
1567
+ const [stream, forkedStream] = result.stream.tee();
1568
+ (async () => {
1569
+ try {
1570
+ let content = "";
1571
+ let hasToolCall = false;
1572
+ const reader = forkedStream.getReader();
1573
+ while (true) {
1574
+ const { done, value } = await reader.read();
1575
+ if (done)
1576
+ break;
1577
+ switch (value.type) {
1578
+ case "text-delta": {
1579
+ content += value.textDelta;
1580
+ render({
1581
+ renderer: textRender,
1582
+ args: [{ content, done: false, delta: value.textDelta }],
1583
+ streamableUI: ui
1584
+ });
1585
+ break;
1586
+ }
1587
+ case "tool-call-delta": {
1588
+ hasToolCall = true;
1589
+ break;
1590
+ }
1591
+ case "tool-call": {
1592
+ const toolName = value.toolName;
1593
+ if (!tools) {
1594
+ throw new NoSuchToolError({ toolName });
1595
+ }
1596
+ const tool = tools[toolName];
1597
+ if (!tool) {
1598
+ throw new NoSuchToolError({
1599
+ toolName,
1600
+ availableTools: Object.keys(tools)
1601
+ });
1602
+ }
1603
+ hasToolCall = true;
1604
+ const parseResult = safeParseJSON({
1605
+ text: value.args,
1606
+ schema: tool.parameters
1607
+ });
1608
+ if (parseResult.success === false) {
1609
+ throw new InvalidToolArgumentsError({
1610
+ toolName,
1611
+ toolArgs: value.args,
1612
+ cause: parseResult.error
1613
+ });
1614
+ }
1615
+ render({
1616
+ renderer: tool.generate,
1617
+ args: [
1618
+ parseResult.value,
1619
+ {
1620
+ toolName,
1621
+ toolCallId: value.toolCallId
1622
+ }
1623
+ ],
1624
+ streamableUI: ui,
1625
+ isLastCall: true
1626
+ });
1627
+ break;
1628
+ }
1629
+ case "error": {
1630
+ throw value.error;
1631
+ }
1632
+ case "finish": {
1633
+ finishEvent = {
1634
+ finishReason: value.finishReason,
1635
+ usage: calculateLanguageModelUsage(value.usage),
1636
+ warnings: result.warnings,
1637
+ rawResponse: result.rawResponse
1638
+ };
1639
+ break;
1640
+ }
1641
+ }
1642
+ }
1643
+ if (!hasToolCall) {
1644
+ render({
1645
+ renderer: textRender,
1646
+ args: [{ content, done: true }],
1647
+ streamableUI: ui,
1648
+ isLastCall: true
1649
+ });
1650
+ }
1651
+ await finished;
1652
+ if (finishEvent && onFinish) {
1653
+ await onFinish({
1654
+ ...finishEvent,
1655
+ value: ui.value
1656
+ });
1657
+ }
1658
+ } catch (error) {
1659
+ ui.error(error);
1660
+ }
1661
+ })();
1662
+ return {
1663
+ ...result,
1664
+ stream,
1665
+ value: ui.value
1666
+ };
1667
+ }
1668
+
1669
+ // rsc/streamable-value/streamable-value.ts
1670
+ var STREAMABLE_VALUE_TYPE = Symbol.for("ui.streamable.value");
1671
+
1672
+ // rsc/streamable-value/create-streamable-value.ts
1673
+ var STREAMABLE_VALUE_INTERNAL_LOCK = Symbol("streamable.value.lock");
1674
+ function createStreamableValue(initialValue) {
1675
+ const isReadableStream = initialValue instanceof ReadableStream || typeof initialValue === "object" && initialValue !== null && "getReader" in initialValue && typeof initialValue.getReader === "function" && "locked" in initialValue && typeof initialValue.locked === "boolean";
1676
+ if (!isReadableStream) {
1677
+ return createStreamableValueImpl(initialValue);
1678
+ }
1679
+ const streamableValue = createStreamableValueImpl();
1680
+ streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;
1681
+ (async () => {
1682
+ try {
1683
+ const reader = initialValue.getReader();
1684
+ while (true) {
1685
+ const { value, done } = await reader.read();
1686
+ if (done) {
1687
+ break;
1688
+ }
1689
+ streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
1690
+ if (typeof value === "string") {
1691
+ streamableValue.append(value);
1692
+ } else {
1693
+ streamableValue.update(value);
1694
+ }
1695
+ streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;
1696
+ }
1697
+ streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
1698
+ streamableValue.done();
1699
+ } catch (e) {
1700
+ streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
1701
+ streamableValue.error(e);
1702
+ }
1703
+ })();
1704
+ return streamableValue;
1705
+ }
1706
+ function createStreamableValueImpl(initialValue) {
1707
+ let closed = false;
1708
+ let locked = false;
1709
+ let resolvable = createResolvablePromise();
1710
+ let currentValue = initialValue;
1711
+ let currentError;
1712
+ let currentPromise = resolvable.promise;
1713
+ let currentPatchValue;
1714
+ function assertStream(method) {
1715
+ if (closed) {
1716
+ throw new Error(method + ": Value stream is already closed.");
1717
+ }
1718
+ if (locked) {
1719
+ throw new Error(
1720
+ method + ": Value stream is locked and cannot be updated."
1721
+ );
1722
+ }
1723
+ }
1724
+ let warningTimeout;
1725
+ function warnUnclosedStream() {
1726
+ if (process.env.NODE_ENV === "development") {
1727
+ if (warningTimeout) {
1728
+ clearTimeout(warningTimeout);
1729
+ }
1730
+ warningTimeout = setTimeout(() => {
1731
+ console.warn(
1732
+ "The streamable value has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`."
1733
+ );
1734
+ }, HANGING_STREAM_WARNING_TIME_MS);
1735
+ }
1736
+ }
1737
+ warnUnclosedStream();
1738
+ function createWrapped(initialChunk) {
1739
+ let init;
1740
+ if (currentError !== void 0) {
1741
+ init = { error: currentError };
1742
+ } else {
1743
+ if (currentPatchValue && !initialChunk) {
1744
+ init = { diff: currentPatchValue };
1745
+ } else {
1746
+ init = { curr: currentValue };
1747
+ }
1748
+ }
1749
+ if (currentPromise) {
1750
+ init.next = currentPromise;
1751
+ }
1752
+ if (initialChunk) {
1753
+ init.type = STREAMABLE_VALUE_TYPE;
1754
+ }
1755
+ return init;
1756
+ }
1757
+ function updateValueStates(value) {
1758
+ currentPatchValue = void 0;
1759
+ if (typeof value === "string") {
1760
+ if (typeof currentValue === "string") {
1761
+ if (value.startsWith(currentValue)) {
1762
+ currentPatchValue = [0, value.slice(currentValue.length)];
1763
+ }
1764
+ }
1765
+ }
1766
+ currentValue = value;
1767
+ }
1768
+ const streamable = {
1769
+ set [STREAMABLE_VALUE_INTERNAL_LOCK](state) {
1770
+ locked = state;
1771
+ },
1772
+ get value() {
1773
+ return createWrapped(true);
1774
+ },
1775
+ update(value) {
1776
+ assertStream(".update()");
1777
+ const resolvePrevious = resolvable.resolve;
1778
+ resolvable = createResolvablePromise();
1779
+ updateValueStates(value);
1780
+ currentPromise = resolvable.promise;
1781
+ resolvePrevious(createWrapped());
1782
+ warnUnclosedStream();
1783
+ return streamable;
1784
+ },
1785
+ append(value) {
1786
+ assertStream(".append()");
1787
+ if (typeof currentValue !== "string" && typeof currentValue !== "undefined") {
1788
+ throw new Error(
1789
+ `.append(): The current value is not a string. Received: ${typeof currentValue}`
1790
+ );
1791
+ }
1792
+ if (typeof value !== "string") {
1793
+ throw new Error(
1794
+ `.append(): The value is not a string. Received: ${typeof value}`
1795
+ );
1796
+ }
1797
+ const resolvePrevious = resolvable.resolve;
1798
+ resolvable = createResolvablePromise();
1799
+ if (typeof currentValue === "string") {
1800
+ currentPatchValue = [0, value];
1801
+ currentValue = currentValue + value;
1802
+ } else {
1803
+ currentPatchValue = void 0;
1804
+ currentValue = value;
1805
+ }
1806
+ currentPromise = resolvable.promise;
1807
+ resolvePrevious(createWrapped());
1808
+ warnUnclosedStream();
1809
+ return streamable;
1810
+ },
1811
+ error(error) {
1812
+ assertStream(".error()");
1813
+ if (warningTimeout) {
1814
+ clearTimeout(warningTimeout);
1815
+ }
1816
+ closed = true;
1817
+ currentError = error;
1818
+ currentPromise = void 0;
1819
+ resolvable.resolve({ error });
1820
+ return streamable;
1821
+ },
1822
+ done(...args) {
1823
+ assertStream(".done()");
1824
+ if (warningTimeout) {
1825
+ clearTimeout(warningTimeout);
1826
+ }
1827
+ closed = true;
1828
+ currentPromise = void 0;
1829
+ if (args.length) {
1830
+ updateValueStates(args[0]);
1831
+ resolvable.resolve(createWrapped());
1832
+ return streamable;
1833
+ }
1834
+ resolvable.resolve({});
1835
+ return streamable;
1836
+ }
1837
+ };
1838
+ return streamable;
1839
+ }
1840
+ export {
1841
+ createAI,
1842
+ createStreamableUI,
1843
+ createStreamableValue,
1844
+ getAIState,
1845
+ getMutableAIState,
1846
+ streamUI
1847
+ };
1848
+ //# sourceMappingURL=rsc-server.mjs.map