ai 3.3.6 → 3.3.7

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.
@@ -139,421 +139,110 @@ function getMutableAIState(...args) {
139
139
  return mutableState;
140
140
  }
141
141
 
142
- // rsc/constants.ts
143
- var STREAMABLE_VALUE_TYPE = Symbol.for("ui.streamable.value");
144
- var DEV_DEFAULT_STREAMABLE_WARNING_TIME = 15 * 1e3;
145
-
146
- // rsc/create-suspended-chunk.tsx
147
- import { Suspense } from "react";
148
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
149
- var R = [
150
- async ({
151
- c: current,
152
- n: next
153
- }) => {
154
- const chunk = await next;
155
- if (chunk.done) {
156
- return chunk.value;
157
- }
158
- if (chunk.append) {
159
- return /* @__PURE__ */ jsxs(Fragment, { children: [
160
- current,
161
- /* @__PURE__ */ jsx(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx(R, { c: chunk.value, n: chunk.next }) })
162
- ] });
163
- }
164
- return /* @__PURE__ */ jsx(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx(R, { c: chunk.value, n: chunk.next }) });
165
- }
166
- ][0];
167
- function createSuspendedChunk(initialValue) {
168
- const { promise, resolve, reject } = createResolvablePromise();
169
- return {
170
- row: /* @__PURE__ */ jsx(Suspense, { fallback: initialValue, children: /* @__PURE__ */ jsx(R, { c: initialValue, n: promise }) }),
171
- resolve,
172
- reject
173
- };
174
- }
175
-
176
- // rsc/streamable.tsx
177
- function createStreamableUI(initialValue) {
178
- let currentValue = initialValue;
179
- let closed = false;
180
- let { row, resolve, reject } = createSuspendedChunk(initialValue);
181
- function assertStream(method) {
182
- if (closed) {
183
- throw new Error(method + ": UI stream is already closed.");
184
- }
185
- }
186
- let warningTimeout;
187
- function warnUnclosedStream() {
188
- if (process.env.NODE_ENV === "development") {
189
- if (warningTimeout) {
190
- clearTimeout(warningTimeout);
191
- }
192
- warningTimeout = setTimeout(() => {
193
- console.warn(
194
- "The streamable UI has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`."
195
- );
196
- }, DEV_DEFAULT_STREAMABLE_WARNING_TIME);
197
- }
198
- }
199
- warnUnclosedStream();
200
- const streamable2 = {
201
- value: row,
202
- update(value) {
203
- assertStream(".update()");
204
- if (value === currentValue) {
205
- warnUnclosedStream();
206
- return streamable2;
207
- }
208
- const resolvable = createResolvablePromise();
209
- currentValue = value;
210
- resolve({ value: currentValue, done: false, next: resolvable.promise });
211
- resolve = resolvable.resolve;
212
- reject = resolvable.reject;
213
- warnUnclosedStream();
214
- return streamable2;
215
- },
216
- append(value) {
217
- assertStream(".append()");
218
- const resolvable = createResolvablePromise();
219
- currentValue = value;
220
- resolve({ value, done: false, append: true, next: resolvable.promise });
221
- resolve = resolvable.resolve;
222
- reject = resolvable.reject;
223
- warnUnclosedStream();
224
- return streamable2;
225
- },
226
- error(error) {
227
- assertStream(".error()");
228
- if (warningTimeout) {
229
- clearTimeout(warningTimeout);
230
- }
231
- closed = true;
232
- reject(error);
233
- return streamable2;
142
+ // rsc/provider.tsx
143
+ import * as React from "react";
144
+ import { InternalAIProvider } from "./rsc-shared.mjs";
145
+ import { jsx } from "react/jsx-runtime";
146
+ async function innerAction({
147
+ action,
148
+ options
149
+ }, state, ...args) {
150
+ "use server";
151
+ return await withAIState(
152
+ {
153
+ state,
154
+ options
234
155
  },
235
- done(...args) {
236
- assertStream(".done()");
237
- if (warningTimeout) {
238
- clearTimeout(warningTimeout);
239
- }
240
- closed = true;
241
- if (args.length) {
242
- resolve({ value: args[0], done: true });
243
- return streamable2;
244
- }
245
- resolve({ value: currentValue, done: true });
246
- return streamable2;
156
+ async () => {
157
+ const result = await action(...args);
158
+ sealMutableAIState();
159
+ return [getAIStateDeltaPromise(), result];
247
160
  }
248
- };
249
- return streamable2;
161
+ );
250
162
  }
251
- var STREAMABLE_VALUE_INTERNAL_LOCK = Symbol("streamable.value.lock");
252
- function createStreamableValue(initialValue) {
253
- const isReadableStream = initialValue instanceof ReadableStream || typeof initialValue === "object" && initialValue !== null && "getReader" in initialValue && typeof initialValue.getReader === "function" && "locked" in initialValue && typeof initialValue.locked === "boolean";
254
- if (!isReadableStream) {
255
- return createStreamableValueImpl(initialValue);
256
- }
257
- const streamableValue = createStreamableValueImpl();
258
- streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;
259
- (async () => {
260
- try {
261
- const reader = initialValue.getReader();
262
- while (true) {
263
- const { value, done } = await reader.read();
264
- if (done) {
265
- break;
266
- }
267
- streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
268
- if (typeof value === "string") {
269
- streamableValue.append(value);
270
- } else {
271
- streamableValue.update(value);
272
- }
273
- streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;
274
- }
275
- streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
276
- streamableValue.done();
277
- } catch (e) {
278
- streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
279
- streamableValue.error(e);
280
- }
281
- })();
282
- return streamableValue;
163
+ function wrapAction(action, options) {
164
+ return innerAction.bind(null, { action, options });
283
165
  }
284
- function createStreamableValueImpl(initialValue) {
285
- let closed = false;
286
- let locked = false;
287
- let resolvable = createResolvablePromise();
288
- let currentValue = initialValue;
289
- let currentError;
290
- let currentPromise = resolvable.promise;
291
- let currentPatchValue;
292
- function assertStream(method) {
293
- if (closed) {
294
- throw new Error(method + ": Value stream is already closed.");
295
- }
296
- if (locked) {
166
+ function createAI({
167
+ actions,
168
+ initialAIState,
169
+ initialUIState,
170
+ onSetAIState,
171
+ onGetUIState
172
+ }) {
173
+ const wrappedActions = {};
174
+ for (const name8 in actions) {
175
+ wrappedActions[name8] = wrapAction(actions[name8], {
176
+ onSetAIState
177
+ });
178
+ }
179
+ const wrappedSyncUIState = onGetUIState ? wrapAction(onGetUIState, {}) : void 0;
180
+ const AI = async (props) => {
181
+ var _a8, _b;
182
+ if ("useState" in React) {
297
183
  throw new Error(
298
- method + ": Value stream is locked and cannot be updated."
184
+ "This component can only be used inside Server Components."
299
185
  );
300
186
  }
301
- }
302
- let warningTimeout;
303
- function warnUnclosedStream() {
304
- if (process.env.NODE_ENV === "development") {
305
- if (warningTimeout) {
306
- clearTimeout(warningTimeout);
187
+ let uiState = (_a8 = props.initialUIState) != null ? _a8 : initialUIState;
188
+ let aiState = (_b = props.initialAIState) != null ? _b : initialAIState;
189
+ let aiStateDelta = void 0;
190
+ if (wrappedSyncUIState) {
191
+ const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);
192
+ if (newUIState !== void 0) {
193
+ aiStateDelta = newAIStateDelta;
194
+ uiState = newUIState;
307
195
  }
308
- warningTimeout = setTimeout(() => {
309
- console.warn(
310
- "The streamable value has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`."
311
- );
312
- }, DEV_DEFAULT_STREAMABLE_WARNING_TIME);
313
196
  }
314
- }
315
- warnUnclosedStream();
316
- function createWrapped(initialChunk) {
317
- let init;
318
- if (currentError !== void 0) {
319
- init = { error: currentError };
320
- } else {
321
- if (currentPatchValue && !initialChunk) {
322
- init = { diff: currentPatchValue };
323
- } else {
324
- init = { curr: currentValue };
197
+ return /* @__PURE__ */ jsx(
198
+ InternalAIProvider,
199
+ {
200
+ wrappedActions,
201
+ wrappedSyncUIState,
202
+ initialUIState: uiState,
203
+ initialAIState: aiState,
204
+ initialAIStatePatch: aiStateDelta,
205
+ children: props.children
325
206
  }
326
- }
327
- if (currentPromise) {
328
- init.next = currentPromise;
329
- }
330
- if (initialChunk) {
331
- init.type = STREAMABLE_VALUE_TYPE;
332
- }
333
- return init;
334
- }
335
- function updateValueStates(value) {
336
- currentPatchValue = void 0;
337
- if (typeof value === "string") {
338
- if (typeof currentValue === "string") {
339
- if (value.startsWith(currentValue)) {
340
- currentPatchValue = [0, value.slice(currentValue.length)];
341
- }
342
- }
343
- }
344
- currentValue = value;
345
- }
346
- const streamable2 = {
347
- set [STREAMABLE_VALUE_INTERNAL_LOCK](state) {
348
- locked = state;
349
- },
350
- get value() {
351
- return createWrapped(true);
352
- },
353
- update(value) {
354
- assertStream(".update()");
355
- const resolvePrevious = resolvable.resolve;
356
- resolvable = createResolvablePromise();
357
- updateValueStates(value);
358
- currentPromise = resolvable.promise;
359
- resolvePrevious(createWrapped());
360
- warnUnclosedStream();
361
- return streamable2;
362
- },
363
- append(value) {
364
- assertStream(".append()");
365
- if (typeof currentValue !== "string" && typeof currentValue !== "undefined") {
366
- throw new Error(
367
- `.append(): The current value is not a string. Received: ${typeof currentValue}`
368
- );
369
- }
370
- if (typeof value !== "string") {
371
- throw new Error(
372
- `.append(): The value is not a string. Received: ${typeof value}`
373
- );
374
- }
375
- const resolvePrevious = resolvable.resolve;
376
- resolvable = createResolvablePromise();
377
- if (typeof currentValue === "string") {
378
- currentPatchValue = [0, value];
379
- currentValue = currentValue + value;
380
- } else {
381
- currentPatchValue = void 0;
382
- currentValue = value;
383
- }
384
- currentPromise = resolvable.promise;
385
- resolvePrevious(createWrapped());
386
- warnUnclosedStream();
387
- return streamable2;
388
- },
389
- error(error) {
390
- assertStream(".error()");
391
- if (warningTimeout) {
392
- clearTimeout(warningTimeout);
393
- }
394
- closed = true;
395
- currentError = error;
396
- currentPromise = void 0;
397
- resolvable.resolve({ error });
398
- return streamable2;
399
- },
400
- done(...args) {
401
- assertStream(".done()");
402
- if (warningTimeout) {
403
- clearTimeout(warningTimeout);
404
- }
405
- closed = true;
406
- currentPromise = void 0;
407
- if (args.length) {
408
- updateValueStates(args[0]);
409
- resolvable.resolve(createWrapped());
410
- return streamable2;
411
- }
412
- resolvable.resolve({});
413
- return streamable2;
414
- }
415
- };
416
- return streamable2;
417
- }
418
-
419
- // rsc/render.ts
420
- import zodToJsonSchema from "zod-to-json-schema";
421
-
422
- // util/retry-with-exponential-backoff.ts
423
- import { APICallError } from "@ai-sdk/provider";
424
- import { getErrorMessage, isAbortError } from "@ai-sdk/provider-utils";
425
-
426
- // util/delay.ts
427
- async function delay(delayInMs) {
428
- return new Promise((resolve) => setTimeout(resolve, delayInMs));
429
- }
430
-
431
- // util/retry-error.ts
432
- import { AISDKError } from "@ai-sdk/provider";
433
- var name = "AI_RetryError";
434
- var marker = `vercel.ai.error.${name}`;
435
- var symbol = Symbol.for(marker);
436
- var _a;
437
- var RetryError = class extends AISDKError {
438
- constructor({
439
- message,
440
- reason,
441
- errors
442
- }) {
443
- super({ name, message });
444
- this[_a] = true;
445
- this.reason = reason;
446
- this.errors = errors;
447
- this.lastError = errors[errors.length - 1];
207
+ );
208
+ };
209
+ return AI;
210
+ }
211
+
212
+ // rsc/stream-ui/stream-ui.tsx
213
+ import { safeParseJSON } from "@ai-sdk/provider-utils";
214
+
215
+ // core/prompt/convert-to-language-model-prompt.ts
216
+ import { getErrorMessage } from "@ai-sdk/provider-utils";
217
+
218
+ // util/download-error.ts
219
+ import { AISDKError } from "@ai-sdk/provider";
220
+ var name = "AI_DownloadError";
221
+ var marker = `vercel.ai.error.${name}`;
222
+ var symbol = Symbol.for(marker);
223
+ var _a;
224
+ var DownloadError = class extends AISDKError {
225
+ constructor({
226
+ url,
227
+ statusCode,
228
+ statusText,
229
+ cause,
230
+ message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
231
+ }) {
232
+ super({ name, message, cause });
233
+ this[_a] = true;
234
+ this.url = url;
235
+ this.statusCode = statusCode;
236
+ this.statusText = statusText;
448
237
  }
449
238
  static isInstance(error) {
450
239
  return AISDKError.hasMarker(error, marker);
451
240
  }
452
- /**
453
- * @deprecated use `isInstance` instead
454
- */
455
- static isRetryError(error) {
456
- return error instanceof Error && error.name === name && typeof error.reason === "string" && Array.isArray(error.errors);
457
- }
458
- /**
459
- * @deprecated Do not use this method. It will be removed in the next major version.
460
- */
461
- toJSON() {
462
- return {
463
- name: this.name,
464
- message: this.message,
465
- reason: this.reason,
466
- lastError: this.lastError,
467
- errors: this.errors
468
- };
469
- }
470
- };
471
- _a = symbol;
472
-
473
- // util/retry-with-exponential-backoff.ts
474
- var retryWithExponentialBackoff = ({
475
- maxRetries = 2,
476
- initialDelayInMs = 2e3,
477
- backoffFactor = 2
478
- } = {}) => async (f) => _retryWithExponentialBackoff(f, {
479
- maxRetries,
480
- delayInMs: initialDelayInMs,
481
- backoffFactor
482
- });
483
- async function _retryWithExponentialBackoff(f, {
484
- maxRetries,
485
- delayInMs,
486
- backoffFactor
487
- }, errors = []) {
488
- try {
489
- return await f();
490
- } catch (error) {
491
- if (isAbortError(error)) {
492
- throw error;
493
- }
494
- if (maxRetries === 0) {
495
- throw error;
496
- }
497
- const errorMessage = getErrorMessage(error);
498
- const newErrors = [...errors, error];
499
- const tryNumber = newErrors.length;
500
- if (tryNumber > maxRetries) {
501
- throw new RetryError({
502
- message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
503
- reason: "maxRetriesExceeded",
504
- errors: newErrors
505
- });
506
- }
507
- if (error instanceof Error && APICallError.isAPICallError(error) && error.isRetryable === true && tryNumber <= maxRetries) {
508
- await delay(delayInMs);
509
- return _retryWithExponentialBackoff(
510
- f,
511
- { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
512
- newErrors
513
- );
514
- }
515
- if (tryNumber === 1) {
516
- throw error;
517
- }
518
- throw new RetryError({
519
- message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
520
- reason: "errorNotRetryable",
521
- errors: newErrors
522
- });
523
- }
524
- }
525
-
526
- // core/prompt/convert-to-language-model-prompt.ts
527
- import { getErrorMessage as getErrorMessage2 } from "@ai-sdk/provider-utils";
528
-
529
- // util/download-error.ts
530
- import { AISDKError as AISDKError2 } from "@ai-sdk/provider";
531
- var name2 = "AI_DownloadError";
532
- var marker2 = `vercel.ai.error.${name2}`;
533
- var symbol2 = Symbol.for(marker2);
534
- var _a2;
535
- var DownloadError = class extends AISDKError2 {
536
- constructor({
537
- url,
538
- statusCode,
539
- statusText,
540
- cause,
541
- message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}`
542
- }) {
543
- super({ name: name2, message, cause });
544
- this[_a2] = true;
545
- this.url = url;
546
- this.statusCode = statusCode;
547
- this.statusText = statusText;
548
- }
549
- static isInstance(error) {
550
- return AISDKError2.hasMarker(error, marker2);
551
- }
552
241
  /**
553
242
  * @deprecated use `isInstance` instead
554
243
  */
555
244
  static isDownloadError(error) {
556
- return error instanceof Error && error.name === name2 && typeof error.url === "string" && (error.statusCode == null || typeof error.statusCode === "number") && (error.statusText == null || typeof error.statusText === "string");
245
+ return error instanceof Error && error.name === name && typeof error.url === "string" && (error.statusCode == null || typeof error.statusCode === "number") && (error.statusText == null || typeof error.statusText === "string");
557
246
  }
558
247
  /**
559
248
  * @deprecated Do not use this method. It will be removed in the next major version.
@@ -569,7 +258,7 @@ var DownloadError = class extends AISDKError2 {
569
258
  };
570
259
  }
571
260
  };
572
- _a2 = symbol2;
261
+ _a = symbol;
573
262
 
574
263
  // util/download.ts
575
264
  async function download({
@@ -622,29 +311,29 @@ import {
622
311
  } from "@ai-sdk/provider-utils";
623
312
 
624
313
  // core/prompt/invalid-data-content-error.ts
625
- import { AISDKError as AISDKError3 } from "@ai-sdk/provider";
626
- var name3 = "AI_InvalidDataContentError";
627
- var marker3 = `vercel.ai.error.${name3}`;
628
- var symbol3 = Symbol.for(marker3);
629
- var _a3;
630
- var InvalidDataContentError = class extends AISDKError3 {
314
+ import { AISDKError as AISDKError2 } from "@ai-sdk/provider";
315
+ var name2 = "AI_InvalidDataContentError";
316
+ var marker2 = `vercel.ai.error.${name2}`;
317
+ var symbol2 = Symbol.for(marker2);
318
+ var _a2;
319
+ var InvalidDataContentError = class extends AISDKError2 {
631
320
  constructor({
632
321
  content,
633
322
  cause,
634
323
  message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
635
324
  }) {
636
- super({ name: name3, message, cause });
637
- this[_a3] = true;
325
+ super({ name: name2, message, cause });
326
+ this[_a2] = true;
638
327
  this.content = content;
639
328
  }
640
329
  static isInstance(error) {
641
- return AISDKError3.hasMarker(error, marker3);
330
+ return AISDKError2.hasMarker(error, marker2);
642
331
  }
643
332
  /**
644
333
  * @deprecated use `isInstance` instead
645
334
  */
646
335
  static isInvalidDataContentError(error) {
647
- return error instanceof Error && error.name === name3 && error.content != null;
336
+ return error instanceof Error && error.name === name2 && error.content != null;
648
337
  }
649
338
  /**
650
339
  * @deprecated Do not use this method. It will be removed in the next major version.
@@ -659,7 +348,7 @@ var InvalidDataContentError = class extends AISDKError3 {
659
348
  };
660
349
  }
661
350
  };
662
- _a3 = symbol3;
351
+ _a2 = symbol2;
663
352
 
664
353
  // core/prompt/data-content.ts
665
354
  function convertDataContentToUint8Array(content) {
@@ -684,28 +373,28 @@ function convertDataContentToUint8Array(content) {
684
373
  }
685
374
 
686
375
  // core/prompt/invalid-message-role-error.ts
687
- import { AISDKError as AISDKError4 } from "@ai-sdk/provider";
688
- var name4 = "AI_InvalidMessageRoleError";
689
- var marker4 = `vercel.ai.error.${name4}`;
690
- var symbol4 = Symbol.for(marker4);
691
- var _a4;
692
- var InvalidMessageRoleError = class extends AISDKError4 {
376
+ import { AISDKError as AISDKError3 } from "@ai-sdk/provider";
377
+ var name3 = "AI_InvalidMessageRoleError";
378
+ var marker3 = `vercel.ai.error.${name3}`;
379
+ var symbol3 = Symbol.for(marker3);
380
+ var _a3;
381
+ var InvalidMessageRoleError = class extends AISDKError3 {
693
382
  constructor({
694
383
  role,
695
384
  message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
696
385
  }) {
697
- super({ name: name4, message });
698
- this[_a4] = true;
386
+ super({ name: name3, message });
387
+ this[_a3] = true;
699
388
  this.role = role;
700
389
  }
701
390
  static isInstance(error) {
702
- return AISDKError4.hasMarker(error, marker4);
391
+ return AISDKError3.hasMarker(error, marker3);
703
392
  }
704
393
  /**
705
394
  * @deprecated use `isInstance` instead
706
395
  */
707
396
  static isInvalidMessageRoleError(error) {
708
- return error instanceof Error && error.name === name4 && typeof error.role === "string";
397
+ return error instanceof Error && error.name === name3 && typeof error.role === "string";
709
398
  }
710
399
  /**
711
400
  * @deprecated Do not use this method. It will be removed in the next major version.
@@ -719,7 +408,7 @@ var InvalidMessageRoleError = class extends AISDKError4 {
719
408
  };
720
409
  }
721
410
  };
722
- _a4 = symbol4;
411
+ _a3 = symbol3;
723
412
 
724
413
  // core/prompt/convert-to-language-model-prompt.ts
725
414
  async function convertToLanguageModelPrompt({
@@ -830,7 +519,7 @@ function convertToLanguageModelMessage(message, downloadedImages) {
830
519
  };
831
520
  } catch (error) {
832
521
  throw new Error(
833
- `Error processing data URL: ${getErrorMessage2(
522
+ `Error processing data URL: ${getErrorMessage(
834
523
  message
835
524
  )}`
836
525
  );
@@ -941,33 +630,33 @@ function getValidatedPrompt(prompt) {
941
630
  }
942
631
 
943
632
  // errors/invalid-argument-error.ts
944
- import { AISDKError as AISDKError5 } from "@ai-sdk/provider";
945
- var name5 = "AI_InvalidArgumentError";
946
- var marker5 = `vercel.ai.error.${name5}`;
947
- var symbol5 = Symbol.for(marker5);
948
- var _a5;
949
- var InvalidArgumentError = class extends AISDKError5 {
633
+ import { AISDKError as AISDKError4 } from "@ai-sdk/provider";
634
+ var name4 = "AI_InvalidArgumentError";
635
+ var marker4 = `vercel.ai.error.${name4}`;
636
+ var symbol4 = Symbol.for(marker4);
637
+ var _a4;
638
+ var InvalidArgumentError = class extends AISDKError4 {
950
639
  constructor({
951
640
  parameter,
952
641
  value,
953
642
  message
954
643
  }) {
955
644
  super({
956
- name: name5,
645
+ name: name4,
957
646
  message: `Invalid argument for parameter ${parameter}: ${message}`
958
647
  });
959
- this[_a5] = true;
648
+ this[_a4] = true;
960
649
  this.parameter = parameter;
961
650
  this.value = value;
962
651
  }
963
652
  static isInstance(error) {
964
- return AISDKError5.hasMarker(error, marker5);
653
+ return AISDKError4.hasMarker(error, marker4);
965
654
  }
966
655
  /**
967
656
  * @deprecated use `isInstance` instead
968
657
  */
969
658
  static isInvalidArgumentError(error) {
970
- return error instanceof Error && error.name === name5 && typeof error.parameter === "string" && typeof error.value === "string";
659
+ return error instanceof Error && error.name === name4 && typeof error.parameter === "string" && typeof error.value === "string";
971
660
  }
972
661
  toJSON() {
973
662
  return {
@@ -979,7 +668,7 @@ var InvalidArgumentError = class extends AISDKError5 {
979
668
  };
980
669
  }
981
670
  };
982
- _a5 = symbol5;
671
+ _a4 = symbol4;
983
672
 
984
673
  // core/prompt/prepare-call-settings.ts
985
674
  function prepareCallSettings({
@@ -1081,15 +770,6 @@ function prepareCallSettings({
1081
770
  };
1082
771
  }
1083
772
 
1084
- // core/types/token-usage.ts
1085
- function calculateCompletionTokenUsage(usage) {
1086
- return {
1087
- promptTokens: usage.promptTokens,
1088
- completionTokens: usage.completionTokens,
1089
- totalTokens: usage.promptTokens + usage.completionTokens
1090
- };
1091
- }
1092
-
1093
773
  // core/prompt/prepare-tools-and-tool-choice.ts
1094
774
  import { asSchema } from "@ai-sdk/ui-utils";
1095
775
 
@@ -1120,34 +800,43 @@ function prepareToolsAndToolChoice({
1120
800
  };
1121
801
  }
1122
802
 
1123
- // errors/invalid-tool-arguments-error.ts
1124
- import { AISDKError as AISDKError6, getErrorMessage as getErrorMessage3 } from "@ai-sdk/provider";
1125
- var name6 = "AI_InvalidToolArgumentsError";
1126
- var marker6 = `vercel.ai.error.${name6}`;
1127
- var symbol6 = Symbol.for(marker6);
1128
- var _a6;
1129
- var InvalidToolArgumentsError = class extends AISDKError6 {
1130
- constructor({
1131
- toolArgs,
1132
- toolName,
803
+ // core/types/token-usage.ts
804
+ function calculateCompletionTokenUsage(usage) {
805
+ return {
806
+ promptTokens: usage.promptTokens,
807
+ completionTokens: usage.completionTokens,
808
+ totalTokens: usage.promptTokens + usage.completionTokens
809
+ };
810
+ }
811
+
812
+ // errors/invalid-tool-arguments-error.ts
813
+ import { AISDKError as AISDKError5, getErrorMessage as getErrorMessage2 } from "@ai-sdk/provider";
814
+ var name5 = "AI_InvalidToolArgumentsError";
815
+ var marker5 = `vercel.ai.error.${name5}`;
816
+ var symbol5 = Symbol.for(marker5);
817
+ var _a5;
818
+ var InvalidToolArgumentsError = class extends AISDKError5 {
819
+ constructor({
820
+ toolArgs,
821
+ toolName,
1133
822
  cause,
1134
- message = `Invalid arguments for tool ${toolName}: ${getErrorMessage3(
823
+ message = `Invalid arguments for tool ${toolName}: ${getErrorMessage2(
1135
824
  cause
1136
825
  )}`
1137
826
  }) {
1138
- super({ name: name6, message, cause });
1139
- this[_a6] = true;
827
+ super({ name: name5, message, cause });
828
+ this[_a5] = true;
1140
829
  this.toolArgs = toolArgs;
1141
830
  this.toolName = toolName;
1142
831
  }
1143
832
  static isInstance(error) {
1144
- return AISDKError6.hasMarker(error, marker6);
833
+ return AISDKError5.hasMarker(error, marker5);
1145
834
  }
1146
835
  /**
1147
836
  * @deprecated use `isInstance` instead
1148
837
  */
1149
838
  static isInvalidToolArgumentsError(error) {
1150
- return error instanceof Error && error.name === name6 && typeof error.toolName === "string" && typeof error.toolArgs === "string";
839
+ return error instanceof Error && error.name === name5 && typeof error.toolName === "string" && typeof error.toolArgs === "string";
1151
840
  }
1152
841
  /**
1153
842
  * @deprecated Do not use this method. It will be removed in the next major version.
@@ -1163,48 +852,465 @@ var InvalidToolArgumentsError = class extends AISDKError6 {
1163
852
  };
1164
853
  }
1165
854
  };
855
+ _a5 = symbol5;
856
+
857
+ // errors/no-such-tool-error.ts
858
+ import { AISDKError as AISDKError6 } from "@ai-sdk/provider";
859
+ var name6 = "AI_NoSuchToolError";
860
+ var marker6 = `vercel.ai.error.${name6}`;
861
+ var symbol6 = Symbol.for(marker6);
862
+ var _a6;
863
+ var NoSuchToolError = class extends AISDKError6 {
864
+ constructor({
865
+ toolName,
866
+ availableTools = void 0,
867
+ message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}`
868
+ }) {
869
+ super({ name: name6, message });
870
+ this[_a6] = true;
871
+ this.toolName = toolName;
872
+ this.availableTools = availableTools;
873
+ }
874
+ static isInstance(error) {
875
+ return AISDKError6.hasMarker(error, marker6);
876
+ }
877
+ /**
878
+ * @deprecated use `isInstance` instead
879
+ */
880
+ static isNoSuchToolError(error) {
881
+ return error instanceof Error && error.name === name6 && "toolName" in error && error.toolName != void 0 && typeof error.name === "string";
882
+ }
883
+ /**
884
+ * @deprecated Do not use this method. It will be removed in the next major version.
885
+ */
886
+ toJSON() {
887
+ return {
888
+ name: this.name,
889
+ message: this.message,
890
+ stack: this.stack,
891
+ toolName: this.toolName,
892
+ availableTools: this.availableTools
893
+ };
894
+ }
895
+ };
1166
896
  _a6 = symbol6;
1167
897
 
1168
- // errors/no-such-tool-error.ts
1169
- import { AISDKError as AISDKError7 } from "@ai-sdk/provider";
1170
- var name7 = "AI_NoSuchToolError";
1171
- var marker7 = `vercel.ai.error.${name7}`;
1172
- var symbol7 = Symbol.for(marker7);
1173
- var _a7;
1174
- var NoSuchToolError = class extends AISDKError7 {
1175
- constructor({
1176
- toolName,
1177
- availableTools = void 0,
1178
- message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? "No tools are available." : `Available tools: ${availableTools.join(", ")}.`}`
1179
- }) {
1180
- super({ name: name7, message });
1181
- this[_a7] = true;
1182
- this.toolName = toolName;
1183
- this.availableTools = availableTools;
1184
- }
1185
- static isInstance(error) {
1186
- return AISDKError7.hasMarker(error, marker7);
1187
- }
1188
- /**
1189
- * @deprecated use `isInstance` instead
1190
- */
1191
- static isNoSuchToolError(error) {
1192
- return error instanceof Error && error.name === name7 && "toolName" in error && error.toolName != void 0 && typeof error.name === "string";
1193
- }
1194
- /**
1195
- * @deprecated Do not use this method. It will be removed in the next major version.
1196
- */
1197
- toJSON() {
1198
- return {
1199
- name: this.name,
1200
- message: this.message,
1201
- stack: this.stack,
1202
- toolName: this.toolName,
1203
- availableTools: this.availableTools
1204
- };
1205
- }
1206
- };
1207
- _a7 = symbol7;
898
+ // util/is-async-generator.ts
899
+ function isAsyncGenerator(value) {
900
+ return value != null && typeof value === "object" && Symbol.asyncIterator in value;
901
+ }
902
+
903
+ // util/is-generator.ts
904
+ function isGenerator(value) {
905
+ return value != null && typeof value === "object" && Symbol.iterator in value;
906
+ }
907
+
908
+ // util/retry-with-exponential-backoff.ts
909
+ import { APICallError } from "@ai-sdk/provider";
910
+ import { getErrorMessage as getErrorMessage3, isAbortError } from "@ai-sdk/provider-utils";
911
+
912
+ // util/delay.ts
913
+ async function delay(delayInMs) {
914
+ return delayInMs === void 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, delayInMs));
915
+ }
916
+
917
+ // util/retry-error.ts
918
+ import { AISDKError as AISDKError7 } from "@ai-sdk/provider";
919
+ var name7 = "AI_RetryError";
920
+ var marker7 = `vercel.ai.error.${name7}`;
921
+ var symbol7 = Symbol.for(marker7);
922
+ var _a7;
923
+ var RetryError = class extends AISDKError7 {
924
+ constructor({
925
+ message,
926
+ reason,
927
+ errors
928
+ }) {
929
+ super({ name: name7, message });
930
+ this[_a7] = true;
931
+ this.reason = reason;
932
+ this.errors = errors;
933
+ this.lastError = errors[errors.length - 1];
934
+ }
935
+ static isInstance(error) {
936
+ return AISDKError7.hasMarker(error, marker7);
937
+ }
938
+ /**
939
+ * @deprecated use `isInstance` instead
940
+ */
941
+ static isRetryError(error) {
942
+ return error instanceof Error && error.name === name7 && typeof error.reason === "string" && Array.isArray(error.errors);
943
+ }
944
+ /**
945
+ * @deprecated Do not use this method. It will be removed in the next major version.
946
+ */
947
+ toJSON() {
948
+ return {
949
+ name: this.name,
950
+ message: this.message,
951
+ reason: this.reason,
952
+ lastError: this.lastError,
953
+ errors: this.errors
954
+ };
955
+ }
956
+ };
957
+ _a7 = symbol7;
958
+
959
+ // util/retry-with-exponential-backoff.ts
960
+ var retryWithExponentialBackoff = ({
961
+ maxRetries = 2,
962
+ initialDelayInMs = 2e3,
963
+ backoffFactor = 2
964
+ } = {}) => async (f) => _retryWithExponentialBackoff(f, {
965
+ maxRetries,
966
+ delayInMs: initialDelayInMs,
967
+ backoffFactor
968
+ });
969
+ async function _retryWithExponentialBackoff(f, {
970
+ maxRetries,
971
+ delayInMs,
972
+ backoffFactor
973
+ }, errors = []) {
974
+ try {
975
+ return await f();
976
+ } catch (error) {
977
+ if (isAbortError(error)) {
978
+ throw error;
979
+ }
980
+ if (maxRetries === 0) {
981
+ throw error;
982
+ }
983
+ const errorMessage = getErrorMessage3(error);
984
+ const newErrors = [...errors, error];
985
+ const tryNumber = newErrors.length;
986
+ if (tryNumber > maxRetries) {
987
+ throw new RetryError({
988
+ message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,
989
+ reason: "maxRetriesExceeded",
990
+ errors: newErrors
991
+ });
992
+ }
993
+ if (error instanceof Error && APICallError.isAPICallError(error) && error.isRetryable === true && tryNumber <= maxRetries) {
994
+ await delay(delayInMs);
995
+ return _retryWithExponentialBackoff(
996
+ f,
997
+ { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
998
+ newErrors
999
+ );
1000
+ }
1001
+ if (tryNumber === 1) {
1002
+ throw error;
1003
+ }
1004
+ throw new RetryError({
1005
+ message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,
1006
+ reason: "errorNotRetryable",
1007
+ errors: newErrors
1008
+ });
1009
+ }
1010
+ }
1011
+
1012
+ // util/constants.ts
1013
+ var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
1014
+
1015
+ // rsc/streamable-ui/create-suspended-chunk.tsx
1016
+ import { Suspense } from "react";
1017
+ import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
1018
+ var R = [
1019
+ async ({
1020
+ c: current,
1021
+ n: next
1022
+ }) => {
1023
+ const chunk = await next;
1024
+ if (chunk.done) {
1025
+ return chunk.value;
1026
+ }
1027
+ if (chunk.append) {
1028
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1029
+ current,
1030
+ /* @__PURE__ */ jsx2(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx2(R, { c: chunk.value, n: chunk.next }) })
1031
+ ] });
1032
+ }
1033
+ return /* @__PURE__ */ jsx2(Suspense, { fallback: chunk.value, children: /* @__PURE__ */ jsx2(R, { c: chunk.value, n: chunk.next }) });
1034
+ }
1035
+ ][0];
1036
+ function createSuspendedChunk(initialValue) {
1037
+ const { promise, resolve, reject } = createResolvablePromise();
1038
+ return {
1039
+ row: /* @__PURE__ */ jsx2(Suspense, { fallback: initialValue, children: /* @__PURE__ */ jsx2(R, { c: initialValue, n: promise }) }),
1040
+ resolve,
1041
+ reject
1042
+ };
1043
+ }
1044
+
1045
+ // rsc/streamable-ui/create-streamable-ui.tsx
1046
+ function createStreamableUI(initialValue) {
1047
+ let currentValue = initialValue;
1048
+ let closed = false;
1049
+ let { row, resolve, reject } = createSuspendedChunk(initialValue);
1050
+ function assertStream(method) {
1051
+ if (closed) {
1052
+ throw new Error(method + ": UI stream is already closed.");
1053
+ }
1054
+ }
1055
+ let warningTimeout;
1056
+ function warnUnclosedStream() {
1057
+ if (process.env.NODE_ENV === "development") {
1058
+ if (warningTimeout) {
1059
+ clearTimeout(warningTimeout);
1060
+ }
1061
+ warningTimeout = setTimeout(() => {
1062
+ console.warn(
1063
+ "The streamable UI has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`."
1064
+ );
1065
+ }, HANGING_STREAM_WARNING_TIME_MS);
1066
+ }
1067
+ }
1068
+ warnUnclosedStream();
1069
+ const streamable2 = {
1070
+ value: row,
1071
+ update(value) {
1072
+ assertStream(".update()");
1073
+ if (value === currentValue) {
1074
+ warnUnclosedStream();
1075
+ return streamable2;
1076
+ }
1077
+ const resolvable = createResolvablePromise();
1078
+ currentValue = value;
1079
+ resolve({ value: currentValue, done: false, next: resolvable.promise });
1080
+ resolve = resolvable.resolve;
1081
+ reject = resolvable.reject;
1082
+ warnUnclosedStream();
1083
+ return streamable2;
1084
+ },
1085
+ append(value) {
1086
+ assertStream(".append()");
1087
+ const resolvable = createResolvablePromise();
1088
+ currentValue = value;
1089
+ resolve({ value, done: false, append: true, next: resolvable.promise });
1090
+ resolve = resolvable.resolve;
1091
+ reject = resolvable.reject;
1092
+ warnUnclosedStream();
1093
+ return streamable2;
1094
+ },
1095
+ error(error) {
1096
+ assertStream(".error()");
1097
+ if (warningTimeout) {
1098
+ clearTimeout(warningTimeout);
1099
+ }
1100
+ closed = true;
1101
+ reject(error);
1102
+ return streamable2;
1103
+ },
1104
+ done(...args) {
1105
+ assertStream(".done()");
1106
+ if (warningTimeout) {
1107
+ clearTimeout(warningTimeout);
1108
+ }
1109
+ closed = true;
1110
+ if (args.length) {
1111
+ resolve({ value: args[0], done: true });
1112
+ return streamable2;
1113
+ }
1114
+ resolve({ value: currentValue, done: true });
1115
+ return streamable2;
1116
+ }
1117
+ };
1118
+ return streamable2;
1119
+ }
1120
+
1121
+ // rsc/stream-ui/stream-ui.tsx
1122
+ var defaultTextRenderer = ({ content }) => content;
1123
+ async function streamUI({
1124
+ model,
1125
+ tools,
1126
+ toolChoice,
1127
+ system,
1128
+ prompt,
1129
+ messages,
1130
+ maxRetries,
1131
+ abortSignal,
1132
+ headers,
1133
+ initial,
1134
+ text,
1135
+ onFinish,
1136
+ ...settings
1137
+ }) {
1138
+ if (typeof model === "string") {
1139
+ throw new Error(
1140
+ "`model` cannot be a string in `streamUI`. Use the actual model instance instead."
1141
+ );
1142
+ }
1143
+ if ("functions" in settings) {
1144
+ throw new Error(
1145
+ "`functions` is not supported in `streamUI`, use `tools` instead."
1146
+ );
1147
+ }
1148
+ if ("provider" in settings) {
1149
+ throw new Error(
1150
+ "`provider` is no longer needed in `streamUI`. Use `model` instead."
1151
+ );
1152
+ }
1153
+ if (tools) {
1154
+ for (const [name8, tool] of Object.entries(tools)) {
1155
+ if ("render" in tool) {
1156
+ throw new Error(
1157
+ "Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: " + name8
1158
+ );
1159
+ }
1160
+ }
1161
+ }
1162
+ const ui = createStreamableUI(initial);
1163
+ const textRender = text || defaultTextRenderer;
1164
+ let finished;
1165
+ async function render2({
1166
+ args,
1167
+ renderer,
1168
+ streamableUI,
1169
+ isLastCall = false
1170
+ }) {
1171
+ if (!renderer)
1172
+ return;
1173
+ const renderFinished = createResolvablePromise();
1174
+ finished = finished ? finished.then(() => renderFinished.promise) : renderFinished.promise;
1175
+ const rendererResult = renderer(...args);
1176
+ if (isAsyncGenerator(rendererResult) || isGenerator(rendererResult)) {
1177
+ while (true) {
1178
+ const { done, value } = await rendererResult.next();
1179
+ const node = await value;
1180
+ if (isLastCall && done) {
1181
+ streamableUI.done(node);
1182
+ } else {
1183
+ streamableUI.update(node);
1184
+ }
1185
+ if (done)
1186
+ break;
1187
+ }
1188
+ } else {
1189
+ const node = await rendererResult;
1190
+ if (isLastCall) {
1191
+ streamableUI.done(node);
1192
+ } else {
1193
+ streamableUI.update(node);
1194
+ }
1195
+ }
1196
+ renderFinished.resolve(void 0);
1197
+ }
1198
+ const retry = retryWithExponentialBackoff({ maxRetries });
1199
+ const validatedPrompt = getValidatedPrompt({ system, prompt, messages });
1200
+ const result = await retry(
1201
+ async () => model.doStream({
1202
+ mode: {
1203
+ type: "regular",
1204
+ ...prepareToolsAndToolChoice({ tools, toolChoice })
1205
+ },
1206
+ ...prepareCallSettings(settings),
1207
+ inputFormat: validatedPrompt.type,
1208
+ prompt: await convertToLanguageModelPrompt({
1209
+ prompt: validatedPrompt,
1210
+ modelSupportsImageUrls: model.supportsImageUrls
1211
+ }),
1212
+ abortSignal,
1213
+ headers
1214
+ })
1215
+ );
1216
+ const [stream, forkedStream] = result.stream.tee();
1217
+ (async () => {
1218
+ try {
1219
+ let content = "";
1220
+ let hasToolCall = false;
1221
+ const reader = forkedStream.getReader();
1222
+ while (true) {
1223
+ const { done, value } = await reader.read();
1224
+ if (done)
1225
+ break;
1226
+ switch (value.type) {
1227
+ case "text-delta": {
1228
+ content += value.textDelta;
1229
+ render2({
1230
+ renderer: textRender,
1231
+ args: [{ content, done: false, delta: value.textDelta }],
1232
+ streamableUI: ui
1233
+ });
1234
+ break;
1235
+ }
1236
+ case "tool-call-delta": {
1237
+ hasToolCall = true;
1238
+ break;
1239
+ }
1240
+ case "tool-call": {
1241
+ const toolName = value.toolName;
1242
+ if (!tools) {
1243
+ throw new NoSuchToolError({ toolName });
1244
+ }
1245
+ const tool = tools[toolName];
1246
+ if (!tool) {
1247
+ throw new NoSuchToolError({
1248
+ toolName,
1249
+ availableTools: Object.keys(tools)
1250
+ });
1251
+ }
1252
+ hasToolCall = true;
1253
+ const parseResult = safeParseJSON({
1254
+ text: value.args,
1255
+ schema: tool.parameters
1256
+ });
1257
+ if (parseResult.success === false) {
1258
+ throw new InvalidToolArgumentsError({
1259
+ toolName,
1260
+ toolArgs: value.args,
1261
+ cause: parseResult.error
1262
+ });
1263
+ }
1264
+ render2({
1265
+ renderer: tool.generate,
1266
+ args: [
1267
+ parseResult.value,
1268
+ {
1269
+ toolName,
1270
+ toolCallId: value.toolCallId
1271
+ }
1272
+ ],
1273
+ streamableUI: ui,
1274
+ isLastCall: true
1275
+ });
1276
+ break;
1277
+ }
1278
+ case "error": {
1279
+ throw value.error;
1280
+ }
1281
+ case "finish": {
1282
+ onFinish == null ? void 0 : onFinish({
1283
+ finishReason: value.finishReason,
1284
+ usage: calculateCompletionTokenUsage(value.usage),
1285
+ value: ui.value,
1286
+ warnings: result.warnings,
1287
+ rawResponse: result.rawResponse
1288
+ });
1289
+ }
1290
+ }
1291
+ }
1292
+ if (!hasToolCall) {
1293
+ render2({
1294
+ renderer: textRender,
1295
+ args: [{ content, done: true }],
1296
+ streamableUI: ui,
1297
+ isLastCall: true
1298
+ });
1299
+ }
1300
+ await finished;
1301
+ } catch (error) {
1302
+ ui.error(error);
1303
+ }
1304
+ })();
1305
+ return {
1306
+ ...result,
1307
+ stream,
1308
+ value: ui.value
1309
+ };
1310
+ }
1311
+
1312
+ // rsc/stream-ui/render.ts
1313
+ import zodToJsonSchema from "zod-to-json-schema";
1208
1314
 
1209
1315
  // streams/ai-stream.ts
1210
1316
  import {
@@ -1332,7 +1438,6 @@ function readableFromAsyncIterable(iterable) {
1332
1438
 
1333
1439
  // streams/stream-data.ts
1334
1440
  import { formatStreamPart } from "@ai-sdk/ui-utils";
1335
- var STREAM_DATA_WARNING_TIME_MS = 15 * 1e3;
1336
1441
  function createStreamDataTransformer() {
1337
1442
  const encoder = new TextEncoder();
1338
1443
  const decoder = new TextDecoder();
@@ -1676,7 +1781,7 @@ async function consumeStream(stream) {
1676
1781
  }
1677
1782
  }
1678
1783
 
1679
- // rsc/render.ts
1784
+ // rsc/stream-ui/render.ts
1680
1785
  function render(options) {
1681
1786
  const ui = createStreamableUI(options.initial);
1682
1787
  const text = options.text ? options.text : ({ content }) => content;
@@ -1777,308 +1882,206 @@ function render(options) {
1777
1882
  async experimental_onToolCall(toolCallPayload) {
1778
1883
  var _a8, _b;
1779
1884
  hasFunction = true;
1780
- for (const tool of toolCallPayload.tools) {
1781
- handleRender(
1782
- tool.func.arguments,
1783
- (_b = (_a8 = options.tools) == null ? void 0 : _a8[tool.func.name]) == null ? void 0 : _b.render,
1784
- ui
1785
- );
1786
- }
1787
- }
1788
- } : {},
1789
- onText(chunk) {
1790
- content += chunk;
1791
- handleRender({ content, done: false, delta: chunk }, text, ui);
1792
- },
1793
- async onFinal() {
1794
- if (hasFunction) {
1795
- await finished;
1796
- ui.done();
1797
- return;
1798
- }
1799
- handleRender({ content, done: true }, text, ui);
1800
- await finished;
1801
- ui.done();
1802
- }
1803
- }
1804
- )
1805
- );
1806
- })();
1807
- return ui.value;
1808
- }
1809
-
1810
- // rsc/stream-ui/stream-ui.tsx
1811
- import { safeParseJSON } from "@ai-sdk/provider-utils";
1812
-
1813
- // util/is-async-generator.ts
1814
- function isAsyncGenerator(value) {
1815
- return value != null && typeof value === "object" && Symbol.asyncIterator in value;
1816
- }
1817
-
1818
- // util/is-generator.ts
1819
- function isGenerator(value) {
1820
- return value != null && typeof value === "object" && Symbol.iterator in value;
1821
- }
1822
-
1823
- // rsc/stream-ui/stream-ui.tsx
1824
- var defaultTextRenderer = ({ content }) => content;
1825
- async function streamUI({
1826
- model,
1827
- tools,
1828
- toolChoice,
1829
- system,
1830
- prompt,
1831
- messages,
1832
- maxRetries,
1833
- abortSignal,
1834
- headers,
1835
- initial,
1836
- text,
1837
- onFinish,
1838
- ...settings
1839
- }) {
1840
- if (typeof model === "string") {
1841
- throw new Error(
1842
- "`model` cannot be a string in `streamUI`. Use the actual model instance instead."
1843
- );
1844
- }
1845
- if ("functions" in settings) {
1846
- throw new Error(
1847
- "`functions` is not supported in `streamUI`, use `tools` instead."
1848
- );
1849
- }
1850
- if ("provider" in settings) {
1851
- throw new Error(
1852
- "`provider` is no longer needed in `streamUI`. Use `model` instead."
1853
- );
1854
- }
1855
- if (tools) {
1856
- for (const [name8, tool] of Object.entries(tools)) {
1857
- if ("render" in tool) {
1858
- throw new Error(
1859
- "Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: " + name8
1860
- );
1861
- }
1862
- }
1863
- }
1864
- const ui = createStreamableUI(initial);
1865
- const textRender = text || defaultTextRenderer;
1866
- let finished;
1867
- async function render2({
1868
- args,
1869
- renderer,
1870
- streamableUI,
1871
- isLastCall = false
1872
- }) {
1873
- if (!renderer)
1874
- return;
1875
- const renderFinished = createResolvablePromise();
1876
- finished = finished ? finished.then(() => renderFinished.promise) : renderFinished.promise;
1877
- const rendererResult = renderer(...args);
1878
- if (isAsyncGenerator(rendererResult) || isGenerator(rendererResult)) {
1879
- while (true) {
1880
- const { done, value } = await rendererResult.next();
1881
- const node = await value;
1882
- if (isLastCall && done) {
1883
- streamableUI.done(node);
1884
- } else {
1885
- streamableUI.update(node);
1886
- }
1887
- if (done)
1888
- break;
1889
- }
1890
- } else {
1891
- const node = await rendererResult;
1892
- if (isLastCall) {
1893
- streamableUI.done(node);
1894
- } else {
1895
- streamableUI.update(node);
1896
- }
1897
- }
1898
- renderFinished.resolve(void 0);
1899
- }
1900
- const retry = retryWithExponentialBackoff({ maxRetries });
1901
- const validatedPrompt = getValidatedPrompt({ system, prompt, messages });
1902
- const result = await retry(
1903
- async () => model.doStream({
1904
- mode: {
1905
- type: "regular",
1906
- ...prepareToolsAndToolChoice({ tools, toolChoice })
1907
- },
1908
- ...prepareCallSettings(settings),
1909
- inputFormat: validatedPrompt.type,
1910
- prompt: await convertToLanguageModelPrompt({
1911
- prompt: validatedPrompt,
1912
- modelSupportsImageUrls: model.supportsImageUrls
1913
- }),
1914
- abortSignal,
1915
- headers
1916
- })
1917
- );
1918
- const [stream, forkedStream] = result.stream.tee();
1919
- (async () => {
1920
- try {
1921
- let content = "";
1922
- let hasToolCall = false;
1923
- const reader = forkedStream.getReader();
1924
- while (true) {
1925
- const { done, value } = await reader.read();
1926
- if (done)
1927
- break;
1928
- switch (value.type) {
1929
- case "text-delta": {
1930
- content += value.textDelta;
1931
- render2({
1932
- renderer: textRender,
1933
- args: [{ content, done: false, delta: value.textDelta }],
1934
- streamableUI: ui
1935
- });
1936
- break;
1937
- }
1938
- case "tool-call-delta": {
1939
- hasToolCall = true;
1940
- break;
1941
- }
1942
- case "tool-call": {
1943
- const toolName = value.toolName;
1944
- if (!tools) {
1945
- throw new NoSuchToolError({ toolName });
1946
- }
1947
- const tool = tools[toolName];
1948
- if (!tool) {
1949
- throw new NoSuchToolError({
1950
- toolName,
1951
- availableTools: Object.keys(tools)
1952
- });
1953
- }
1954
- hasToolCall = true;
1955
- const parseResult = safeParseJSON({
1956
- text: value.args,
1957
- schema: tool.parameters
1958
- });
1959
- if (parseResult.success === false) {
1960
- throw new InvalidToolArgumentsError({
1961
- toolName,
1962
- toolArgs: value.args,
1963
- cause: parseResult.error
1964
- });
1965
- }
1966
- render2({
1967
- renderer: tool.generate,
1968
- args: [
1969
- parseResult.value,
1970
- {
1971
- toolName,
1972
- toolCallId: value.toolCallId
1973
- }
1974
- ],
1975
- streamableUI: ui,
1976
- isLastCall: true
1977
- });
1978
- break;
1979
- }
1980
- case "error": {
1981
- throw value.error;
1982
- }
1983
- case "finish": {
1984
- onFinish == null ? void 0 : onFinish({
1985
- finishReason: value.finishReason,
1986
- usage: calculateCompletionTokenUsage(value.usage),
1987
- value: ui.value,
1988
- warnings: result.warnings,
1989
- rawResponse: result.rawResponse
1990
- });
1885
+ for (const tool of toolCallPayload.tools) {
1886
+ handleRender(
1887
+ tool.func.arguments,
1888
+ (_b = (_a8 = options.tools) == null ? void 0 : _a8[tool.func.name]) == null ? void 0 : _b.render,
1889
+ ui
1890
+ );
1891
+ }
1892
+ }
1893
+ } : {},
1894
+ onText(chunk) {
1895
+ content += chunk;
1896
+ handleRender({ content, done: false, delta: chunk }, text, ui);
1897
+ },
1898
+ async onFinal() {
1899
+ if (hasFunction) {
1900
+ await finished;
1901
+ ui.done();
1902
+ return;
1903
+ }
1904
+ handleRender({ content, done: true }, text, ui);
1905
+ await finished;
1906
+ ui.done();
1991
1907
  }
1992
1908
  }
1993
- }
1994
- if (!hasToolCall) {
1995
- render2({
1996
- renderer: textRender,
1997
- args: [{ content, done: true }],
1998
- streamableUI: ui,
1999
- isLastCall: true
2000
- });
2001
- }
2002
- await finished;
2003
- } catch (error) {
2004
- ui.error(error);
2005
- }
1909
+ )
1910
+ );
2006
1911
  })();
2007
- return {
2008
- ...result,
2009
- stream,
2010
- value: ui.value
2011
- };
1912
+ return ui.value;
2012
1913
  }
2013
1914
 
2014
- // rsc/provider.tsx
2015
- import * as React2 from "react";
2016
- import { InternalAIProvider } from "./rsc-shared.mjs";
2017
- import { jsx as jsx2 } from "react/jsx-runtime";
2018
- async function innerAction({
2019
- action,
2020
- options
2021
- }, state, ...args) {
2022
- "use server";
2023
- return await withAIState(
2024
- {
2025
- state,
2026
- options
2027
- },
2028
- async () => {
2029
- const result = await action(...args);
2030
- sealMutableAIState();
2031
- return [getAIStateDeltaPromise(), result];
1915
+ // rsc/streamable-value/streamable-value.ts
1916
+ var STREAMABLE_VALUE_TYPE = Symbol.for("ui.streamable.value");
1917
+
1918
+ // rsc/streamable-value/create-streamable-value.ts
1919
+ var STREAMABLE_VALUE_INTERNAL_LOCK = Symbol("streamable.value.lock");
1920
+ function createStreamableValue(initialValue) {
1921
+ const isReadableStream = initialValue instanceof ReadableStream || typeof initialValue === "object" && initialValue !== null && "getReader" in initialValue && typeof initialValue.getReader === "function" && "locked" in initialValue && typeof initialValue.locked === "boolean";
1922
+ if (!isReadableStream) {
1923
+ return createStreamableValueImpl(initialValue);
1924
+ }
1925
+ const streamableValue = createStreamableValueImpl();
1926
+ streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;
1927
+ (async () => {
1928
+ try {
1929
+ const reader = initialValue.getReader();
1930
+ while (true) {
1931
+ const { value, done } = await reader.read();
1932
+ if (done) {
1933
+ break;
1934
+ }
1935
+ streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
1936
+ if (typeof value === "string") {
1937
+ streamableValue.append(value);
1938
+ } else {
1939
+ streamableValue.update(value);
1940
+ }
1941
+ streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;
1942
+ }
1943
+ streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
1944
+ streamableValue.done();
1945
+ } catch (e) {
1946
+ streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;
1947
+ streamableValue.error(e);
2032
1948
  }
2033
- );
2034
- }
2035
- function wrapAction(action, options) {
2036
- return innerAction.bind(null, { action, options });
1949
+ })();
1950
+ return streamableValue;
2037
1951
  }
2038
- function createAI({
2039
- actions,
2040
- initialAIState,
2041
- initialUIState,
2042
- onSetAIState,
2043
- onGetUIState
2044
- }) {
2045
- const wrappedActions = {};
2046
- for (const name8 in actions) {
2047
- wrappedActions[name8] = wrapAction(actions[name8], {
2048
- onSetAIState
2049
- });
2050
- }
2051
- const wrappedSyncUIState = onGetUIState ? wrapAction(onGetUIState, {}) : void 0;
2052
- const AI = async (props) => {
2053
- var _a8, _b;
2054
- if ("useState" in React2) {
1952
+ function createStreamableValueImpl(initialValue) {
1953
+ let closed = false;
1954
+ let locked = false;
1955
+ let resolvable = createResolvablePromise();
1956
+ let currentValue = initialValue;
1957
+ let currentError;
1958
+ let currentPromise = resolvable.promise;
1959
+ let currentPatchValue;
1960
+ function assertStream(method) {
1961
+ if (closed) {
1962
+ throw new Error(method + ": Value stream is already closed.");
1963
+ }
1964
+ if (locked) {
2055
1965
  throw new Error(
2056
- "This component can only be used inside Server Components."
1966
+ method + ": Value stream is locked and cannot be updated."
2057
1967
  );
2058
1968
  }
2059
- let uiState = (_a8 = props.initialUIState) != null ? _a8 : initialUIState;
2060
- let aiState = (_b = props.initialAIState) != null ? _b : initialAIState;
2061
- let aiStateDelta = void 0;
2062
- if (wrappedSyncUIState) {
2063
- const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);
2064
- if (newUIState !== void 0) {
2065
- aiStateDelta = newAIStateDelta;
2066
- uiState = newUIState;
1969
+ }
1970
+ let warningTimeout;
1971
+ function warnUnclosedStream() {
1972
+ if (process.env.NODE_ENV === "development") {
1973
+ if (warningTimeout) {
1974
+ clearTimeout(warningTimeout);
2067
1975
  }
1976
+ warningTimeout = setTimeout(() => {
1977
+ console.warn(
1978
+ "The streamable value has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`."
1979
+ );
1980
+ }, HANGING_STREAM_WARNING_TIME_MS);
2068
1981
  }
2069
- return /* @__PURE__ */ jsx2(
2070
- InternalAIProvider,
2071
- {
2072
- wrappedActions,
2073
- wrappedSyncUIState,
2074
- initialUIState: uiState,
2075
- initialAIState: aiState,
2076
- initialAIStatePatch: aiStateDelta,
2077
- children: props.children
1982
+ }
1983
+ warnUnclosedStream();
1984
+ function createWrapped(initialChunk) {
1985
+ let init;
1986
+ if (currentError !== void 0) {
1987
+ init = { error: currentError };
1988
+ } else {
1989
+ if (currentPatchValue && !initialChunk) {
1990
+ init = { diff: currentPatchValue };
1991
+ } else {
1992
+ init = { curr: currentValue };
2078
1993
  }
2079
- );
1994
+ }
1995
+ if (currentPromise) {
1996
+ init.next = currentPromise;
1997
+ }
1998
+ if (initialChunk) {
1999
+ init.type = STREAMABLE_VALUE_TYPE;
2000
+ }
2001
+ return init;
2002
+ }
2003
+ function updateValueStates(value) {
2004
+ currentPatchValue = void 0;
2005
+ if (typeof value === "string") {
2006
+ if (typeof currentValue === "string") {
2007
+ if (value.startsWith(currentValue)) {
2008
+ currentPatchValue = [0, value.slice(currentValue.length)];
2009
+ }
2010
+ }
2011
+ }
2012
+ currentValue = value;
2013
+ }
2014
+ const streamable2 = {
2015
+ set [STREAMABLE_VALUE_INTERNAL_LOCK](state) {
2016
+ locked = state;
2017
+ },
2018
+ get value() {
2019
+ return createWrapped(true);
2020
+ },
2021
+ update(value) {
2022
+ assertStream(".update()");
2023
+ const resolvePrevious = resolvable.resolve;
2024
+ resolvable = createResolvablePromise();
2025
+ updateValueStates(value);
2026
+ currentPromise = resolvable.promise;
2027
+ resolvePrevious(createWrapped());
2028
+ warnUnclosedStream();
2029
+ return streamable2;
2030
+ },
2031
+ append(value) {
2032
+ assertStream(".append()");
2033
+ if (typeof currentValue !== "string" && typeof currentValue !== "undefined") {
2034
+ throw new Error(
2035
+ `.append(): The current value is not a string. Received: ${typeof currentValue}`
2036
+ );
2037
+ }
2038
+ if (typeof value !== "string") {
2039
+ throw new Error(
2040
+ `.append(): The value is not a string. Received: ${typeof value}`
2041
+ );
2042
+ }
2043
+ const resolvePrevious = resolvable.resolve;
2044
+ resolvable = createResolvablePromise();
2045
+ if (typeof currentValue === "string") {
2046
+ currentPatchValue = [0, value];
2047
+ currentValue = currentValue + value;
2048
+ } else {
2049
+ currentPatchValue = void 0;
2050
+ currentValue = value;
2051
+ }
2052
+ currentPromise = resolvable.promise;
2053
+ resolvePrevious(createWrapped());
2054
+ warnUnclosedStream();
2055
+ return streamable2;
2056
+ },
2057
+ error(error) {
2058
+ assertStream(".error()");
2059
+ if (warningTimeout) {
2060
+ clearTimeout(warningTimeout);
2061
+ }
2062
+ closed = true;
2063
+ currentError = error;
2064
+ currentPromise = void 0;
2065
+ resolvable.resolve({ error });
2066
+ return streamable2;
2067
+ },
2068
+ done(...args) {
2069
+ assertStream(".done()");
2070
+ if (warningTimeout) {
2071
+ clearTimeout(warningTimeout);
2072
+ }
2073
+ closed = true;
2074
+ currentPromise = void 0;
2075
+ if (args.length) {
2076
+ updateValueStates(args[0]);
2077
+ resolvable.resolve(createWrapped());
2078
+ return streamable2;
2079
+ }
2080
+ resolvable.resolve({});
2081
+ return streamable2;
2082
+ }
2080
2083
  };
2081
- return AI;
2084
+ return streamable2;
2082
2085
  }
2083
2086
  export {
2084
2087
  createAI,