@ai-sdk/rsc 3.0.0-beta.10 → 3.0.0-beta.101

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,661 @@
1
1
  # @ai-sdk/rsc
2
2
 
3
+ ## 3.0.0-beta.101
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [add1126]
8
+ - @ai-sdk/provider-utils@5.0.0-beta.21
9
+ - ai@7.0.0-beta.100
10
+
11
+ ## 3.0.0-beta.100
12
+
13
+ ### Patch Changes
14
+
15
+ - Updated dependencies [2a9c144]
16
+ - ai@7.0.0-beta.99
17
+
18
+ ## 3.0.0-beta.99
19
+
20
+ ### Patch Changes
21
+
22
+ - ai@7.0.0-beta.98
23
+
24
+ ## 3.0.0-beta.98
25
+
26
+ ### Patch Changes
27
+
28
+ - Updated dependencies [208d045]
29
+ - ai@7.0.0-beta.97
30
+
31
+ ## 3.0.0-beta.97
32
+
33
+ ### Patch Changes
34
+
35
+ - ai@7.0.0-beta.96
36
+
37
+ ## 3.0.0-beta.96
38
+
39
+ ### Patch Changes
40
+
41
+ - Updated dependencies [c4f4b5f]
42
+ - ai@7.0.0-beta.95
43
+
44
+ ## 3.0.0-beta.95
45
+
46
+ ### Patch Changes
47
+
48
+ - Updated dependencies [1582efa]
49
+ - ai@7.0.0-beta.94
50
+
51
+ ## 3.0.0-beta.94
52
+
53
+ ### Patch Changes
54
+
55
+ - Updated dependencies [bc47739]
56
+ - ai@7.0.0-beta.93
57
+
58
+ ## 3.0.0-beta.93
59
+
60
+ ### Patch Changes
61
+
62
+ - ai@7.0.0-beta.92
63
+
64
+ ## 3.0.0-beta.92
65
+
66
+ ### Patch Changes
67
+
68
+ - ai@7.0.0-beta.91
69
+
70
+ ## 3.0.0-beta.91
71
+
72
+ ### Patch Changes
73
+
74
+ - 1db29c8: feat(ai): break `CallSettings` apart into `LanguageModelCallOptions` and `RequestOptions`
75
+ - Updated dependencies [1db29c8]
76
+ - ai@7.0.0-beta.90
77
+
78
+ ## 3.0.0-beta.90
79
+
80
+ ### Patch Changes
81
+
82
+ - Updated dependencies [b3976a2]
83
+ - Updated dependencies [ff5eba1]
84
+ - @ai-sdk/provider-utils@5.0.0-beta.20
85
+ - @ai-sdk/provider@4.0.0-beta.12
86
+ - ai@7.0.0-beta.89
87
+
88
+ ## 3.0.0-beta.89
89
+
90
+ ### Major Changes
91
+
92
+ - ef992f8: Remove CommonJS exports from all packages. All packages are now ESM-only (`"type": "module"`). Consumers using `require()` must switch to ESM `import` syntax.
93
+
94
+ ### Patch Changes
95
+
96
+ - Updated dependencies [ef992f8]
97
+ - ai@7.0.0-beta.88
98
+ - @ai-sdk/provider@4.0.0-beta.11
99
+ - @ai-sdk/provider-utils@5.0.0-beta.19
100
+
101
+ ## 3.0.0-beta.88
102
+
103
+ ### Patch Changes
104
+
105
+ - ai@7.0.0-beta.87
106
+
107
+ ## 3.0.0-beta.87
108
+
109
+ ### Patch Changes
110
+
111
+ - Updated dependencies [5a6f514]
112
+ - ai@7.0.0-beta.86
113
+
114
+ ## 3.0.0-beta.86
115
+
116
+ ### Patch Changes
117
+
118
+ - Updated dependencies [57bf606]
119
+ - ai@7.0.0-beta.85
120
+
121
+ ## 3.0.0-beta.85
122
+
123
+ ### Patch Changes
124
+
125
+ - Updated dependencies [90e2d8a]
126
+ - @ai-sdk/provider-utils@5.0.0-beta.18
127
+ - ai@7.0.0-beta.84
128
+
129
+ ## 3.0.0-beta.84
130
+
131
+ ### Patch Changes
132
+
133
+ - ai@7.0.0-beta.83
134
+
135
+ ## 3.0.0-beta.83
136
+
137
+ ### Patch Changes
138
+
139
+ - Updated dependencies [e27ed76]
140
+ - ai@7.0.0-beta.82
141
+
142
+ ## 3.0.0-beta.82
143
+
144
+ ### Patch Changes
145
+
146
+ - Updated dependencies [2fe1099]
147
+ - Updated dependencies [f04adcb]
148
+ - ai@7.0.0-beta.81
149
+
150
+ ## 3.0.0-beta.81
151
+
152
+ ### Patch Changes
153
+
154
+ - Updated dependencies [3ae1786]
155
+ - @ai-sdk/provider-utils@5.0.0-beta.17
156
+ - ai@7.0.0-beta.80
157
+
158
+ ## 3.0.0-beta.80
159
+
160
+ ### Patch Changes
161
+
162
+ - Updated dependencies [6866afe]
163
+ - ai@7.0.0-beta.79
164
+
165
+ ## 3.0.0-beta.79
166
+
167
+ ### Patch Changes
168
+
169
+ - Updated dependencies [f372547]
170
+ - ai@7.0.0-beta.78
171
+
172
+ ## 3.0.0-beta.78
173
+
174
+ ### Patch Changes
175
+
176
+ - Updated dependencies [2add429]
177
+ - ai@7.0.0-beta.77
178
+
179
+ ## 3.0.0-beta.77
180
+
181
+ ### Patch Changes
182
+
183
+ - Updated dependencies [fcc6869]
184
+ - ai@7.0.0-beta.76
185
+
186
+ ## 3.0.0-beta.76
187
+
188
+ ### Patch Changes
189
+
190
+ - Updated dependencies [176466a]
191
+ - @ai-sdk/provider@4.0.0-beta.10
192
+ - ai@7.0.0-beta.75
193
+ - @ai-sdk/provider-utils@5.0.0-beta.16
194
+
195
+ ## 3.0.0-beta.75
196
+
197
+ ### Patch Changes
198
+
199
+ - Updated dependencies [e311194]
200
+ - ai@7.0.0-beta.74
201
+ - @ai-sdk/provider@4.0.0-beta.9
202
+ - @ai-sdk/provider-utils@5.0.0-beta.15
203
+
204
+ ## 3.0.0-beta.74
205
+
206
+ ### Patch Changes
207
+
208
+ - ai@7.0.0-beta.73
209
+
210
+ ## 3.0.0-beta.73
211
+
212
+ ### Patch Changes
213
+
214
+ - Updated dependencies [664a0eb]
215
+ - ai@7.0.0-beta.72
216
+
217
+ ## 3.0.0-beta.72
218
+
219
+ ### Patch Changes
220
+
221
+ - Updated dependencies [e68be55]
222
+ - ai@7.0.0-beta.71
223
+
224
+ ## 3.0.0-beta.71
225
+
226
+ ### Patch Changes
227
+
228
+ - ai@7.0.0-beta.70
229
+
230
+ ## 3.0.0-beta.70
231
+
232
+ ### Patch Changes
233
+
234
+ - Updated dependencies [34bd95d]
235
+ - Updated dependencies [008271d]
236
+ - Updated dependencies [72223e7]
237
+ - @ai-sdk/provider@4.0.0-beta.8
238
+ - ai@7.0.0-beta.69
239
+ - @ai-sdk/provider-utils@5.0.0-beta.14
240
+
241
+ ## 3.0.0-beta.69
242
+
243
+ ### Patch Changes
244
+
245
+ - Updated dependencies [b0c2869]
246
+ - Updated dependencies [7e26e81]
247
+ - @ai-sdk/provider-utils@5.0.0-beta.13
248
+ - ai@7.0.0-beta.68
249
+
250
+ ## 3.0.0-beta.68
251
+
252
+ ### Patch Changes
253
+
254
+ - Updated dependencies [d1a8bed]
255
+ - ai@7.0.0-beta.67
256
+
257
+ ## 3.0.0-beta.67
258
+
259
+ ### Patch Changes
260
+
261
+ - ai@7.0.0-beta.66
262
+
263
+ ## 3.0.0-beta.66
264
+
265
+ ### Patch Changes
266
+
267
+ - Updated dependencies [46d1149]
268
+ - @ai-sdk/provider-utils@5.0.0-beta.12
269
+ - ai@7.0.0-beta.65
270
+
271
+ ## 3.0.0-beta.65
272
+
273
+ ### Patch Changes
274
+
275
+ - ai@7.0.0-beta.64
276
+
277
+ ## 3.0.0-beta.64
278
+
279
+ ### Patch Changes
280
+
281
+ - Updated dependencies [6fd51c0]
282
+ - @ai-sdk/provider-utils@5.0.0-beta.11
283
+ - @ai-sdk/provider@4.0.0-beta.7
284
+ - ai@7.0.0-beta.63
285
+
286
+ ## 3.0.0-beta.63
287
+
288
+ ### Patch Changes
289
+
290
+ - ai@7.0.0-beta.62
291
+
292
+ ## 3.0.0-beta.62
293
+
294
+ ### Patch Changes
295
+
296
+ - Updated dependencies [c29a26f]
297
+ - @ai-sdk/provider-utils@5.0.0-beta.10
298
+ - @ai-sdk/provider@4.0.0-beta.6
299
+ - ai@7.0.0-beta.61
300
+
301
+ ## 3.0.0-beta.61
302
+
303
+ ### Patch Changes
304
+
305
+ - Updated dependencies [38fc777]
306
+ - ai@7.0.0-beta.60
307
+
308
+ ## 3.0.0-beta.60
309
+
310
+ ### Patch Changes
311
+
312
+ - ai@7.0.0-beta.59
313
+
314
+ ## 3.0.0-beta.59
315
+
316
+ ### Patch Changes
317
+
318
+ - Updated dependencies [2e17091]
319
+ - ai@7.0.0-beta.58
320
+ - @ai-sdk/provider-utils@5.0.0-beta.9
321
+
322
+ ## 3.0.0-beta.58
323
+
324
+ ### Patch Changes
325
+
326
+ - Updated dependencies [986c6fd]
327
+ - Updated dependencies [493295c]
328
+ - @ai-sdk/provider-utils@5.0.0-beta.8
329
+ - ai@7.0.0-beta.57
330
+
331
+ ## 3.0.0-beta.57
332
+
333
+ ### Patch Changes
334
+
335
+ - ai@7.0.0-beta.56
336
+
337
+ ## 3.0.0-beta.56
338
+
339
+ ### Patch Changes
340
+
341
+ - Updated dependencies [b3c9f6a]
342
+ - ai@7.0.0-beta.55
343
+
344
+ ## 3.0.0-beta.55
345
+
346
+ ### Patch Changes
347
+
348
+ - Updated dependencies [5d0f18e]
349
+ - ai@7.0.0-beta.54
350
+
351
+ ## 3.0.0-beta.54
352
+
353
+ ### Patch Changes
354
+
355
+ - Updated dependencies [9b47dea]
356
+ - ai@7.0.0-beta.53
357
+
358
+ ## 3.0.0-beta.53
359
+
360
+ ### Patch Changes
361
+
362
+ - Updated dependencies [b56301c]
363
+ - ai@7.0.0-beta.52
364
+
365
+ ## 3.0.0-beta.52
366
+
367
+ ### Patch Changes
368
+
369
+ - 6abd098: split `prepareToolsAndToolChoice()` into `prepareTools()` and `prepareToolChoice()`
370
+ - Updated dependencies [6abd098]
371
+ - ai@7.0.0-beta.51
372
+
373
+ ## 3.0.0-beta.51
374
+
375
+ ### Patch Changes
376
+
377
+ - Updated dependencies [3debdb7]
378
+ - ai@7.0.0-beta.50
379
+
380
+ ## 3.0.0-beta.50
381
+
382
+ ### Patch Changes
383
+
384
+ - ai@7.0.0-beta.49
385
+
386
+ ## 3.0.0-beta.49
387
+
388
+ ### Patch Changes
389
+
390
+ - Updated dependencies [5c4d910]
391
+ - ai@7.0.0-beta.48
392
+
393
+ ## 3.0.0-beta.48
394
+
395
+ ### Patch Changes
396
+
397
+ - Updated dependencies [bc67b4f]
398
+ - ai@7.0.0-beta.47
399
+
400
+ ## 3.0.0-beta.47
401
+
402
+ ### Patch Changes
403
+
404
+ - 31ee822: refactoring(ai): extract filterActiveTools and expose it as experimental_filterActiveTools
405
+ - Updated dependencies [31ee822]
406
+ - ai@7.0.0-beta.46
407
+
408
+ ## 3.0.0-beta.46
409
+
410
+ ### Patch Changes
411
+
412
+ - ai@7.0.0-beta.45
413
+
414
+ ## 3.0.0-beta.45
415
+
416
+ ### Patch Changes
417
+
418
+ - ai@7.0.0-beta.44
419
+
420
+ ## 3.0.0-beta.44
421
+
422
+ ### Patch Changes
423
+
424
+ - ai@7.0.0-beta.43
425
+
426
+ ## 3.0.0-beta.43
427
+
428
+ ### Patch Changes
429
+
430
+ - Updated dependencies [a3fd75b]
431
+ - ai@7.0.0-beta.42
432
+
433
+ ## 3.0.0-beta.42
434
+
435
+ ### Patch Changes
436
+
437
+ - ai@7.0.0-beta.41
438
+
439
+ ## 3.0.0-beta.41
440
+
441
+ ### Patch Changes
442
+
443
+ - Updated dependencies [989d3d2]
444
+ - ai@7.0.0-beta.40
445
+
446
+ ## 3.0.0-beta.40
447
+
448
+ ### Patch Changes
449
+
450
+ - Updated dependencies [f4cfccd]
451
+ - ai@7.0.0-beta.39
452
+
453
+ ## 3.0.0-beta.39
454
+
455
+ ### Patch Changes
456
+
457
+ - Updated dependencies [1f509d4]
458
+ - @ai-sdk/provider-utils@5.0.0-beta.7
459
+ - @ai-sdk/provider@4.0.0-beta.5
460
+ - ai@7.0.0-beta.38
461
+
462
+ ## 3.0.0-beta.38
463
+
464
+ ### Patch Changes
465
+
466
+ - ai@7.0.0-beta.37
467
+
468
+ ## 3.0.0-beta.37
469
+
470
+ ### Patch Changes
471
+
472
+ - Updated dependencies [118b953]
473
+ - ai@7.0.0-beta.36
474
+
475
+ ## 3.0.0-beta.36
476
+
477
+ ### Patch Changes
478
+
479
+ - Updated dependencies [99bf941]
480
+ - ai@7.0.0-beta.35
481
+
482
+ ## 3.0.0-beta.35
483
+
484
+ ### Patch Changes
485
+
486
+ - ai@7.0.0-beta.34
487
+
488
+ ## 3.0.0-beta.34
489
+
490
+ ### Patch Changes
491
+
492
+ - Updated dependencies [caf1b6f]
493
+ - ai@7.0.0-beta.33
494
+
495
+ ## 3.0.0-beta.33
496
+
497
+ ### Patch Changes
498
+
499
+ - Updated dependencies [4b46062]
500
+ - ai@7.0.0-beta.32
501
+
502
+ ## 3.0.0-beta.32
503
+
504
+ ### Patch Changes
505
+
506
+ - e79e644: chore(ai/core): remove `timeout` from `CallSettings` as it was effectively unused there
507
+ - Updated dependencies [e79e644]
508
+ - ai@7.0.0-beta.31
509
+
510
+ ## 3.0.0-beta.31
511
+
512
+ ### Patch Changes
513
+
514
+ - Updated dependencies [f5a6f89]
515
+ - ai@7.0.0-beta.30
516
+
517
+ ## 3.0.0-beta.30
518
+
519
+ ### Patch Changes
520
+
521
+ - Updated dependencies [877bf12]
522
+ - ai@7.0.0-beta.29
523
+
524
+ ## 3.0.0-beta.29
525
+
526
+ ### Patch Changes
527
+
528
+ - Updated dependencies [b9cf502]
529
+ - ai@7.0.0-beta.28
530
+
531
+ ## 3.0.0-beta.28
532
+
533
+ ### Patch Changes
534
+
535
+ - Updated dependencies [3887c70]
536
+ - @ai-sdk/provider-utils@5.0.0-beta.6
537
+ - @ai-sdk/provider@4.0.0-beta.4
538
+ - ai@7.0.0-beta.27
539
+
540
+ ## 3.0.0-beta.27
541
+
542
+ ### Patch Changes
543
+
544
+ - Updated dependencies [f0b0b20]
545
+ - ai@7.0.0-beta.26
546
+
547
+ ## 3.0.0-beta.26
548
+
549
+ ### Patch Changes
550
+
551
+ - Updated dependencies [ff9ce30]
552
+ - ai@7.0.0-beta.25
553
+
554
+ ## 3.0.0-beta.25
555
+
556
+ ### Patch Changes
557
+
558
+ - Updated dependencies [776b617]
559
+ - @ai-sdk/provider-utils@5.0.0-beta.5
560
+ - @ai-sdk/provider@4.0.0-beta.3
561
+ - ai@7.0.0-beta.24
562
+
563
+ ## 3.0.0-beta.24
564
+
565
+ ### Patch Changes
566
+
567
+ - Updated dependencies [80d4dde]
568
+ - Updated dependencies [61753c3]
569
+ - ai@7.0.0-beta.23
570
+ - @ai-sdk/provider-utils@5.0.0-beta.4
571
+
572
+ ## 3.0.0-beta.23
573
+
574
+ ### Patch Changes
575
+
576
+ - ai@7.0.0-beta.22
577
+
578
+ ## 3.0.0-beta.22
579
+
580
+ ### Patch Changes
581
+
582
+ - Updated dependencies [34fd051]
583
+ - ai@7.0.0-beta.21
584
+
585
+ ## 3.0.0-beta.21
586
+
587
+ ### Patch Changes
588
+
589
+ - ai@7.0.0-beta.20
590
+
591
+ ## 3.0.0-beta.20
592
+
593
+ ### Patch Changes
594
+
595
+ - Updated dependencies [f7d4f01]
596
+ - @ai-sdk/provider-utils@5.0.0-beta.3
597
+ - @ai-sdk/provider@4.0.0-beta.2
598
+ - ai@7.0.0-beta.19
599
+
600
+ ## 3.0.0-beta.19
601
+
602
+ ### Patch Changes
603
+
604
+ - Updated dependencies [5c2a5a2]
605
+ - @ai-sdk/provider@4.0.0-beta.1
606
+ - ai@7.0.0-beta.18
607
+ - @ai-sdk/provider-utils@5.0.0-beta.2
608
+
609
+ ## 3.0.0-beta.18
610
+
611
+ ### Patch Changes
612
+
613
+ - ai@7.0.0-beta.17
614
+
615
+ ## 3.0.0-beta.17
616
+
617
+ ### Patch Changes
618
+
619
+ - Updated dependencies [5b8c58f]
620
+ - ai@7.0.0-beta.16
621
+
622
+ ## 3.0.0-beta.16
623
+
624
+ ### Patch Changes
625
+
626
+ - ai@7.0.0-beta.15
627
+
628
+ ## 3.0.0-beta.15
629
+
630
+ ### Patch Changes
631
+
632
+ - ai@7.0.0-beta.14
633
+
634
+ ## 3.0.0-beta.14
635
+
636
+ ### Patch Changes
637
+
638
+ - Updated dependencies [c26ca8d]
639
+ - ai@7.0.0-beta.13
640
+
641
+ ## 3.0.0-beta.13
642
+
643
+ ### Patch Changes
644
+
645
+ - 83f9d04: feat(openai): upgrade v3 specs to v4
646
+
647
+ ## 3.0.0-beta.12
648
+
649
+ ### Patch Changes
650
+
651
+ - ai@7.0.0-beta.12
652
+
653
+ ## 3.0.0-beta.11
654
+
655
+ ### Patch Changes
656
+
657
+ - ai@7.0.0-beta.11
658
+
3
659
  ## 3.0.0-beta.10
4
660
 
5
661
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { LanguageModelV3, LanguageModelV3StreamResult } from '@ai-sdk/provider';
1
+ import { LanguageModelV4, LanguageModelV4StreamResult } from '@ai-sdk/provider';
2
2
  import { ProviderOptions, InferSchema } from '@ai-sdk/provider-utils';
3
- import { Schema, CallSettings, Prompt, ToolChoice, FinishReason, LanguageModelUsage, CallWarning } from 'ai';
3
+ import { Schema, LanguageModelCallOptions, RequestOptions, Prompt, ToolChoice, FinishReason, LanguageModelUsage, CallWarning } from 'ai';
4
4
  import { ReactNode } from 'react';
5
5
  import * as z3 from 'zod/v3';
6
6
  import * as z4 from 'zod/v4';
@@ -153,17 +153,17 @@ type RenderText = Renderer<[
153
153
  ]>;
154
154
  type RenderResult = {
155
155
  value: ReactNode;
156
- } & LanguageModelV3StreamResult;
156
+ } & LanguageModelV4StreamResult;
157
157
  /**
158
158
  * `streamUI` is a helper function to create a streamable UI from LLMs.
159
159
  */
160
160
  declare function streamUI<TOOLS extends {
161
161
  [name: string]: z4.core.$ZodType | z3.Schema | Schema;
162
- } = {}>({ model, tools, toolChoice, system, prompt, messages, maxRetries, abortSignal, headers, initial, text, providerOptions, onFinish, ...settings }: CallSettings & Prompt & {
162
+ } = {}>({ model, tools, toolChoice, system, prompt, messages, maxRetries, abortSignal, headers, initial, text, providerOptions, onFinish, ...settings }: LanguageModelCallOptions & Omit<RequestOptions, 'timeout'> & Prompt & {
163
163
  /**
164
164
  * The language model to use.
165
165
  */
166
- model: LanguageModelV3;
166
+ model: LanguageModelV4;
167
167
  /**
168
168
  * The tools that the model can call. The model needs to support calling tools.
169
169
  */
@@ -1,6 +1,6 @@
1
- import { LanguageModelV3, LanguageModelV3StreamResult } from '@ai-sdk/provider';
1
+ import { LanguageModelV4, LanguageModelV4StreamResult } from '@ai-sdk/provider';
2
2
  import { ProviderOptions, InferSchema } from '@ai-sdk/provider-utils';
3
- import { Schema, CallSettings, Prompt, ToolChoice, FinishReason, LanguageModelUsage, CallWarning } from 'ai';
3
+ import { Schema, LanguageModelCallOptions, RequestOptions, Prompt, ToolChoice, FinishReason, LanguageModelUsage, CallWarning } from 'ai';
4
4
  import { ReactNode } from 'react';
5
5
  import * as z3 from 'zod/v3';
6
6
  import * as z4 from 'zod/v4';
@@ -132,17 +132,17 @@ type RenderText = Renderer<[
132
132
  ]>;
133
133
  type RenderResult = {
134
134
  value: ReactNode;
135
- } & LanguageModelV3StreamResult;
135
+ } & LanguageModelV4StreamResult;
136
136
  /**
137
137
  * `streamUI` is a helper function to create a streamable UI from LLMs.
138
138
  */
139
139
  declare function streamUI<TOOLS extends {
140
140
  [name: string]: z4.core.$ZodType | z3.Schema | Schema;
141
- } = {}>({ model, tools, toolChoice, system, prompt, messages, maxRetries, abortSignal, headers, initial, text, providerOptions, onFinish, ...settings }: CallSettings & Prompt & {
141
+ } = {}>({ model, tools, toolChoice, system, prompt, messages, maxRetries, abortSignal, headers, initial, text, providerOptions, onFinish, ...settings }: LanguageModelCallOptions & Omit<RequestOptions, 'timeout'> & Prompt & {
142
142
  /**
143
143
  * The language model to use.
144
144
  */
145
- model: LanguageModelV3;
145
+ model: LanguageModelV4;
146
146
  /**
147
147
  * The tools that the model can call. The model needs to support calling tools.
148
148
  */
@@ -221,9 +221,10 @@ import {
221
221
  import {
222
222
  asLanguageModelUsage,
223
223
  convertToLanguageModelPrompt,
224
- prepareCallSettings,
224
+ prepareLanguageModelCallOptions,
225
225
  prepareRetries,
226
- prepareToolsAndToolChoice,
226
+ prepareToolChoice,
227
+ prepareTools,
227
228
  standardizePrompt
228
229
  } from "ai/internal";
229
230
 
@@ -431,18 +432,22 @@ async function streamUI({
431
432
  prompt,
432
433
  messages
433
434
  });
435
+ const languageModelTools = await prepareTools({
436
+ tools
437
+ });
438
+ const languageModelToolChoice = prepareToolChoice({
439
+ toolChoice
440
+ });
434
441
  const result = await retry(
435
442
  async () => model.doStream({
436
- ...prepareCallSettings(settings),
437
- ...prepareToolsAndToolChoice({
438
- tools,
439
- toolChoice,
440
- activeTools: void 0
441
- }),
443
+ ...prepareLanguageModelCallOptions(settings),
444
+ tools: languageModelTools,
445
+ toolChoice: languageModelToolChoice,
442
446
  prompt: await convertToLanguageModelPrompt({
443
447
  prompt: validatedPrompt,
444
448
  supportedUrls: await model.supportedUrls,
445
- download: void 0
449
+ download: void 0,
450
+ provider: model.provider.split(".")[0]
446
451
  }),
447
452
  providerOptions,
448
453
  abortSignal,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ai-state.tsx","../src/util/create-resolvable-promise.ts","../src/util/is-function.ts","../src/provider.tsx","../src/stream-ui/stream-ui.tsx","../src/util/constants.ts","../src/streamable-ui/create-suspended-chunk.tsx","../src/streamable-ui/create-streamable-ui.tsx","../src/util/is-async-generator.ts","../src/util/is-generator.ts","../src/streamable-value/streamable-value.ts","../src/streamable-value/create-streamable-value.ts"],"sourcesContent":["import * as jsondiffpatch from 'jsondiffpatch';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { createResolvablePromise } from './util/create-resolvable-promise';\nimport { isFunction } from './util/is-function';\nimport type {\n AIProvider,\n InferAIState,\n InternalAIStateStorageOptions,\n MutableAIState,\n ValueOrUpdater,\n} from './types';\n\n// It is possible that multiple AI requests get in concurrently, for different\n// AI instances. So ALS is necessary here for a simpler API.\nconst asyncAIStateStorage = new AsyncLocalStorage<{\n currentState: any;\n originalState: any;\n sealed: boolean;\n options: InternalAIStateStorageOptions;\n mutationDeltaPromise?: Promise<any>;\n mutationDeltaResolve?: (v: any) => void;\n}>();\n\nfunction getAIStateStoreOrThrow(message: string) {\n const store = asyncAIStateStorage.getStore();\n if (!store) {\n throw new Error(message);\n }\n return store;\n}\n\nexport function withAIState<S, T>(\n { state, options }: { state: S; options: InternalAIStateStorageOptions },\n fn: () => T,\n): T {\n return asyncAIStateStorage.run(\n {\n currentState: JSON.parse(JSON.stringify(state)), // deep clone object\n originalState: state,\n sealed: false,\n options,\n },\n fn,\n );\n}\n\nexport function getAIStateDeltaPromise() {\n const store = getAIStateStoreOrThrow('Internal error occurred.');\n return store.mutationDeltaPromise;\n}\n\n// Internal method. This will be called after the AI Action has been returned\n// and you can no longer call `getMutableAIState()` inside any async callbacks\n// created by that Action.\nexport function sealMutableAIState() {\n const store = getAIStateStoreOrThrow('Internal error occurred.');\n store.sealed = true;\n}\n\n/**\n * Get the current AI state.\n * If `key` is provided, it will return the value of the specified key in the\n * AI state, if it's an object. If it's not an object, it will throw an error.\n *\n * @example const state = getAIState() // Get the entire AI state\n * @example const field = getAIState('key') // Get the value of the key\n */\nfunction getAIState<AI extends AIProvider = any>(): Readonly<\n InferAIState<AI, any>\n>;\nfunction getAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): Readonly<InferAIState<AI, any>[typeof key]>;\nfunction getAIState<AI extends AIProvider = any>(\n ...args: [] | [key: keyof InferAIState<AI, any>]\n) {\n const store = getAIStateStoreOrThrow(\n '`getAIState` must be called within an AI Action.',\n );\n\n if (args.length > 0) {\n const key = args[0];\n if (typeof store.currentState !== 'object') {\n throw new Error(\n `You can't get the \"${String(\n key,\n )}\" field from the AI state because it's not an object.`,\n );\n }\n return store.currentState[key as keyof typeof store.currentState];\n }\n\n return store.currentState;\n}\n\n/**\n * Get the mutable AI state. Note that you must call `.done()` when finishing\n * updating the AI state.\n *\n * @example\n * ```tsx\n * const state = getMutableAIState()\n * state.update({ ...state.get(), key: 'value' })\n * state.update((currentState) => ({ ...currentState, key: 'value' }))\n * state.done()\n * ```\n *\n * @example\n * ```tsx\n * const state = getMutableAIState()\n * state.done({ ...state.get(), key: 'value' }) // Done with a new state\n * ```\n */\nfunction getMutableAIState<AI extends AIProvider = any>(): MutableAIState<\n InferAIState<AI, any>\n>;\nfunction getMutableAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): MutableAIState<InferAIState<AI, any>[typeof key]>;\nfunction getMutableAIState<AI extends AIProvider = any>(\n ...args: [] | [key: keyof InferAIState<AI, any>]\n) {\n type AIState = InferAIState<AI, any>;\n type AIStateWithKey = typeof args extends [key: keyof AIState]\n ? AIState[(typeof args)[0]]\n : AIState;\n type NewStateOrUpdater = ValueOrUpdater<AIStateWithKey>;\n\n const store = getAIStateStoreOrThrow(\n '`getMutableAIState` must be called within an AI Action.',\n );\n\n if (store.sealed) {\n throw new Error(\n \"`getMutableAIState` must be called before returning from an AI Action. Please move it to the top level of the Action's function body.\",\n );\n }\n\n if (!store.mutationDeltaPromise) {\n const { promise, resolve } = createResolvablePromise();\n store.mutationDeltaPromise = promise;\n store.mutationDeltaResolve = resolve;\n }\n\n function doUpdate(newState: NewStateOrUpdater, done: boolean) {\n if (args.length > 0) {\n if (typeof store.currentState !== 'object') {\n const key = args[0];\n throw new Error(\n `You can't modify the \"${String(\n key,\n )}\" field of the AI state because it's not an object.`,\n );\n }\n }\n\n if (isFunction(newState)) {\n if (args.length > 0) {\n store.currentState[args[0]] = newState(store.currentState[args[0]]);\n } else {\n store.currentState = newState(store.currentState);\n }\n } else {\n if (args.length > 0) {\n store.currentState[args[0]] = newState;\n } else {\n store.currentState = newState;\n }\n }\n\n store.options.onSetAIState?.({\n key: args.length > 0 ? args[0] : undefined,\n state: store.currentState,\n done,\n });\n }\n\n const mutableState = {\n get: () => {\n if (args.length > 0) {\n const key = args[0];\n if (typeof store.currentState !== 'object') {\n throw new Error(\n `You can't get the \"${String(\n key,\n )}\" field from the AI state because it's not an object.`,\n );\n }\n return store.currentState[key] as Readonly<AIStateWithKey>;\n }\n\n return store.currentState as Readonly<AIState>;\n },\n update: function update(newAIState: NewStateOrUpdater) {\n doUpdate(newAIState, false);\n },\n done: function done(...doneArgs: [] | [NewStateOrUpdater]) {\n if (doneArgs.length > 0) {\n doUpdate(doneArgs[0] as NewStateOrUpdater, true);\n }\n\n const delta = jsondiffpatch.diff(store.originalState, store.currentState);\n store.mutationDeltaResolve!(delta);\n },\n };\n\n return mutableState;\n}\n\nexport { getAIState, getMutableAIState };\n","/**\n * Creates a Promise with externally accessible resolve and reject functions.\n *\n * @template T - The type of the value that the Promise will resolve to.\n * @returns An object containing:\n * - promise: A Promise that can be resolved or rejected externally.\n * - resolve: A function to resolve the Promise with a value of type T.\n * - reject: A function to reject the Promise with an error.\n */\nexport function createResolvablePromise<T = any>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n} {\n let resolve: (value: T) => void;\n let reject: (error: unknown) => void;\n\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n return {\n promise,\n resolve: resolve!,\n reject: reject!,\n };\n}\n","/**\n * Checks if the given value is a function.\n *\n * @param {unknown} value - The value to check.\n * @returns {boolean} True if the value is a function, false otherwise.\n */\nexport const isFunction = (value: unknown): value is Function =>\n typeof value === 'function';\n","// This file provides the AI context to all AI Actions via AsyncLocalStorage.\n\nimport * as React from 'react';\nimport { InternalAIProvider } from './rsc-shared.mjs';\nimport {\n withAIState,\n getAIStateDeltaPromise,\n sealMutableAIState,\n} from './ai-state';\nimport type {\n ServerWrappedActions,\n AIAction,\n AIActions,\n AIProvider,\n InternalAIStateStorageOptions,\n OnSetAIState,\n OnGetUIState,\n} from './types';\n\nasync function innerAction<T>(\n {\n action,\n options,\n }: { action: AIAction; options: InternalAIStateStorageOptions },\n state: T,\n ...args: unknown[]\n) {\n 'use server';\n return await withAIState(\n {\n state,\n options,\n },\n async () => {\n const result = await action(...args);\n sealMutableAIState();\n return [getAIStateDeltaPromise() as Promise<T>, result];\n },\n );\n}\n\nfunction wrapAction<T = unknown>(\n action: AIAction,\n options: InternalAIStateStorageOptions,\n) {\n return innerAction.bind(null, { action, options }) as AIAction<T>;\n}\n\nexport function createAI<\n AIState = any,\n UIState = any,\n Actions extends AIActions = {},\n>({\n actions,\n initialAIState,\n initialUIState,\n\n onSetAIState,\n onGetUIState,\n}: {\n actions: Actions;\n initialAIState?: AIState;\n initialUIState?: UIState;\n\n /**\n * This function is called whenever the AI state is updated by an Action.\n * You can use this to persist the AI state to a database, or to send it to a\n * logging service.\n */\n onSetAIState?: OnSetAIState<AIState>;\n\n /**\n * This function is used to retrieve the UI state based on the AI state.\n * For example, to render the initial UI state based on a given AI state, or\n * to sync the UI state when the application is already loaded.\n *\n * If returning `undefined`, the client side UI state will not be updated.\n *\n * This function must be annotated with the `\"use server\"` directive.\n *\n * @example\n * ```tsx\n * onGetUIState: async () => {\n * 'use server';\n *\n * const currentAIState = getAIState();\n * const externalAIState = await loadAIStateFromDatabase();\n *\n * if (currentAIState === externalAIState) return undefined;\n *\n * // Update current AI state and return the new UI state\n * const state = getMutableAIState()\n * state.done(externalAIState)\n *\n * return <div>...</div>;\n * }\n * ```\n */\n onGetUIState?: OnGetUIState<UIState>;\n}) {\n // Wrap all actions with our HoC.\n const wrappedActions: ServerWrappedActions = {};\n for (const name in actions) {\n wrappedActions[name] = wrapAction(actions[name], {\n onSetAIState,\n });\n }\n\n const wrappedSyncUIState = onGetUIState\n ? wrapAction(onGetUIState, {})\n : undefined;\n\n const AI: AIProvider<AIState, UIState, Actions> = async props => {\n if ('useState' in React) {\n // This file must be running on the React Server layer.\n // Ideally we should be using `import \"server-only\"` here but we can have a\n // more customized error message with this implementation.\n throw new Error(\n 'This component can only be used inside Server Components.',\n );\n }\n\n let uiState = props.initialUIState ?? initialUIState;\n let aiState = props.initialAIState ?? initialAIState;\n let aiStateDelta = undefined;\n\n if (wrappedSyncUIState) {\n const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);\n if (newUIState !== undefined) {\n aiStateDelta = newAIStateDelta;\n uiState = newUIState;\n }\n }\n\n return (\n <InternalAIProvider\n wrappedActions={wrappedActions}\n wrappedSyncUIState={wrappedSyncUIState}\n initialUIState={uiState}\n initialAIState={aiState}\n initialAIStatePatch={aiStateDelta}\n >\n {props.children}\n </InternalAIProvider>\n );\n };\n\n return AI;\n}\n","import {\n LanguageModelV3,\n LanguageModelV3StreamResult,\n LanguageModelV3Usage,\n SharedV3Warning,\n} from '@ai-sdk/provider';\nimport {\n InferSchema,\n ProviderOptions,\n safeParseJSON,\n} from '@ai-sdk/provider-utils';\nimport {\n CallSettings,\n CallWarning,\n FinishReason,\n InvalidToolInputError,\n LanguageModelUsage,\n NoSuchToolError,\n Prompt,\n Schema,\n ToolChoice,\n} from 'ai';\nimport {\n asLanguageModelUsage,\n convertToLanguageModelPrompt,\n prepareCallSettings,\n prepareRetries,\n prepareToolsAndToolChoice,\n standardizePrompt,\n} from 'ai/internal';\nimport { ReactNode } from 'react';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\nimport { createStreamableUI } from '../streamable-ui/create-streamable-ui';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport { isAsyncGenerator } from '../util/is-async-generator';\nimport { isGenerator } from '../util/is-generator';\n\ntype Streamable = ReactNode | Promise<ReactNode>;\n\ntype Renderer<T extends Array<any>> = (\n ...args: T\n) =>\n | Streamable\n | Generator<Streamable, Streamable, void>\n | AsyncGenerator<Streamable, Streamable, void>;\n\ntype RenderTool<\n INPUT_SCHEMA extends z4.core.$ZodType | z3.Schema | Schema = any,\n> = {\n description?: string;\n inputSchema: INPUT_SCHEMA;\n generate?: Renderer<\n [\n InferSchema<INPUT_SCHEMA>,\n {\n toolName: string;\n toolCallId: string;\n },\n ]\n >;\n};\n\ntype RenderText = Renderer<\n [\n {\n /**\n * The full text content from the model so far.\n */\n content: string;\n\n /**\n * The new appended text content from the model since the last `text` call.\n */\n delta: string;\n\n /**\n * Whether the model is done generating text.\n * If `true`, the `content` will be the final output and this call will be the last.\n */\n done: boolean;\n },\n ]\n>;\n\ntype RenderResult = {\n value: ReactNode;\n} & LanguageModelV3StreamResult;\n\nconst defaultTextRenderer: RenderText = ({ content }: { content: string }) =>\n content;\n\n/**\n * `streamUI` is a helper function to create a streamable UI from LLMs.\n */\nexport async function streamUI<\n TOOLS extends { [name: string]: z4.core.$ZodType | z3.Schema | Schema } = {},\n>({\n model,\n tools,\n toolChoice,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n headers,\n initial,\n text,\n providerOptions,\n onFinish,\n ...settings\n}: CallSettings &\n Prompt & {\n /**\n * The language model to use.\n */\n model: LanguageModelV3;\n\n /**\n * The tools that the model can call. The model needs to support calling tools.\n */\n tools?: {\n [name in keyof TOOLS]: RenderTool<TOOLS[name]>;\n };\n\n /**\n * The tool choice strategy. Default: 'auto'.\n */\n toolChoice?: ToolChoice<TOOLS>;\n\n text?: RenderText;\n initial?: ReactNode;\n\n /**\n * Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n * Callback that is called when the LLM response and the final object validation are finished.\n */\n onFinish?: (event: {\n /**\n * The reason why the generation finished.\n */\n finishReason: FinishReason;\n /**\n * The token usage of the generated response.\n */\n usage: LanguageModelUsage;\n /**\n * The final ui node that was generated.\n */\n value: ReactNode;\n /**\n * Warnings from the model provider (e.g. unsupported settings)\n */\n warnings?: CallWarning[];\n /**\n * Optional response data.\n */\n response?: {\n /**\n * Response headers.\n */\n headers?: Record<string, string>;\n };\n }) => Promise<void> | void;\n }): Promise<RenderResult> {\n // TODO: Remove these errors after the experimental phase.\n if (typeof model === 'string') {\n throw new Error(\n '`model` cannot be a string in `streamUI`. Use the actual model instance instead.',\n );\n }\n if ('functions' in settings) {\n throw new Error(\n '`functions` is not supported in `streamUI`, use `tools` instead.',\n );\n }\n if ('provider' in settings) {\n throw new Error(\n '`provider` is no longer needed in `streamUI`. Use `model` instead.',\n );\n }\n if (tools) {\n for (const [name, tool] of Object.entries(tools)) {\n if ('render' in tool) {\n throw new Error(\n 'Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: ' +\n name,\n );\n }\n }\n }\n\n const ui = createStreamableUI(initial);\n\n // The default text renderer just returns the content as string.\n const textRender = text || defaultTextRenderer;\n\n let finished: Promise<void> | undefined;\n\n let finishEvent: {\n finishReason: FinishReason;\n usage: LanguageModelV3Usage;\n warnings?: CallWarning[];\n response?: {\n headers?: Record<string, string>;\n };\n } | null = null;\n\n async function render({\n args,\n renderer,\n streamableUI,\n isLastCall = false,\n }: {\n renderer: undefined | Renderer<any>;\n args: [payload: any] | [payload: any, options: any];\n streamableUI: ReturnType<typeof createStreamableUI>;\n isLastCall?: boolean;\n }) {\n if (!renderer) return;\n\n // create a promise that will be resolved when the render call is finished.\n // it is appended to the `finished` promise chain to ensure the render call\n // is finished before the next render call starts.\n const renderFinished = createResolvablePromise<void>();\n finished = finished\n ? finished.then(() => renderFinished.promise)\n : renderFinished.promise;\n\n const rendererResult = renderer(...args);\n\n if (isAsyncGenerator(rendererResult) || isGenerator(rendererResult)) {\n while (true) {\n const { done, value } = await rendererResult.next();\n const node = await value;\n\n if (isLastCall && done) {\n streamableUI.done(node);\n } else {\n streamableUI.update(node);\n }\n\n if (done) break;\n }\n } else {\n const node = await rendererResult;\n\n if (isLastCall) {\n streamableUI.done(node);\n } else {\n streamableUI.update(node);\n }\n }\n\n // resolve the promise to signal that the render call is finished\n renderFinished.resolve(undefined);\n }\n\n const { retry } = prepareRetries({ maxRetries, abortSignal });\n\n const validatedPrompt = await standardizePrompt({\n system,\n prompt,\n messages,\n } as Prompt);\n const result = await retry(async () =>\n model.doStream({\n ...prepareCallSettings(settings),\n ...prepareToolsAndToolChoice({\n tools: tools as any,\n toolChoice,\n activeTools: undefined,\n }),\n prompt: await convertToLanguageModelPrompt({\n prompt: validatedPrompt,\n supportedUrls: await model.supportedUrls,\n download: undefined,\n }),\n providerOptions,\n abortSignal,\n headers,\n includeRawChunks: false,\n }),\n );\n\n // For the stream and consume it asynchronously:\n const [stream, forkedStream] = result.stream.tee();\n (async () => {\n try {\n let content = '';\n let hasToolCall = false;\n let warnings: SharedV3Warning[] | undefined;\n\n const reader = forkedStream.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n switch (value.type) {\n case 'stream-start': {\n warnings = value.warnings;\n break;\n }\n\n case 'text-delta': {\n content += value.delta;\n render({\n renderer: textRender,\n args: [{ content, done: false, delta: value.delta }],\n streamableUI: ui,\n });\n break;\n }\n\n case 'tool-input-start':\n case 'tool-input-delta': {\n hasToolCall = true;\n break;\n }\n\n case 'tool-call': {\n const toolName = value.toolName as keyof TOOLS & string;\n\n if (!tools) {\n throw new NoSuchToolError({ toolName });\n }\n\n const tool = tools[toolName];\n if (!tool) {\n throw new NoSuchToolError({\n toolName,\n availableTools: Object.keys(tools),\n });\n }\n\n hasToolCall = true;\n const parseResult = await safeParseJSON({\n text: value.input,\n schema: tool.inputSchema,\n });\n\n if (parseResult.success === false) {\n throw new InvalidToolInputError({\n toolName,\n toolInput: value.input,\n cause: parseResult.error,\n });\n }\n\n render({\n renderer: tool.generate,\n args: [\n parseResult.value,\n {\n toolName,\n toolCallId: value.toolCallId,\n },\n ],\n streamableUI: ui,\n isLastCall: true,\n });\n\n break;\n }\n\n case 'error': {\n throw value.error;\n }\n\n case 'finish': {\n finishEvent = {\n finishReason: value.finishReason?.unified,\n usage: value.usage,\n warnings,\n response: result.response,\n };\n break;\n }\n }\n }\n\n if (!hasToolCall) {\n render({\n renderer: textRender,\n args: [{ content, done: true }],\n streamableUI: ui,\n isLastCall: true,\n });\n }\n\n await finished;\n\n if (finishEvent && onFinish) {\n await onFinish({\n ...finishEvent,\n usage: asLanguageModelUsage(finishEvent.usage),\n value: ui.value,\n });\n }\n } catch (error) {\n // During the stream rendering, we don't want to throw the error to the\n // parent scope but only let the React's error boundary to catch it.\n ui.error(error);\n }\n })();\n\n return {\n ...result,\n stream,\n value: ui.value,\n };\n}\n","/**\n * Warning time for notifying developers that a stream is hanging in dev mode\n * using a console.warn.\n */\nexport const HANGING_STREAM_WARNING_TIME_MS = 15 * 1000;\n","import React, { Suspense } from 'react';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\n\n// Recursive type for the chunk.\ntype ChunkType =\n | {\n done: false;\n value: React.ReactNode;\n next: Promise<ChunkType>;\n append?: boolean;\n }\n | {\n done: true;\n value: React.ReactNode;\n };\n\n// Use single letter names for the variables to reduce the size of the RSC payload.\n// `R` for `Row`, `c` for `current`, `n` for `next`.\n// Note: Array construction is needed to access the name R.\nconst R = [\n (async ({\n c: current,\n n: next,\n }: {\n c: React.ReactNode;\n n: Promise<ChunkType>;\n }) => {\n const chunk = await next;\n\n if (chunk.done) {\n return chunk.value;\n }\n\n if (chunk.append) {\n return (\n <>\n {current}\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n </>\n );\n }\n\n return (\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n );\n }) as unknown as React.FC<{\n c: React.ReactNode;\n n: Promise<ChunkType>;\n }>,\n][0];\n\n/**\n * Creates a suspended chunk for React Server Components.\n *\n * This function generates a suspenseful React component that can be dynamically updated.\n * It's useful for streaming updates to the client in a React Server Components context.\n *\n * @param {React.ReactNode} initialValue - The initial value to render while the promise is pending.\n * @returns {Object} An object containing:\n * - row: A React node that renders the suspenseful content.\n * - resolve: A function to resolve the promise with a new value.\n * - reject: A function to reject the promise with an error.\n */\nexport function createSuspendedChunk(initialValue: React.ReactNode): {\n row: React.ReactNode;\n resolve: (value: ChunkType) => void;\n reject: (error: unknown) => void;\n} {\n const { promise, resolve, reject } = createResolvablePromise<ChunkType>();\n\n return {\n row: (\n <Suspense fallback={initialValue}>\n <R c={initialValue} n={promise} />\n </Suspense>\n ),\n resolve,\n reject,\n };\n}\n","import { HANGING_STREAM_WARNING_TIME_MS } from '../util/constants';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport { createSuspendedChunk } from './create-suspended-chunk';\n\n// It's necessary to define the type manually here, otherwise TypeScript compiler\n// will not be able to infer the correct return type as it's circular.\ntype StreamableUIWrapper = {\n /**\n * The value of the streamable UI. This can be returned from a Server Action and received by the client.\n */\n readonly value: React.ReactNode;\n\n /**\n * This method updates the current UI node. It takes a new UI node and replaces the old one.\n */\n update(value: React.ReactNode): StreamableUIWrapper;\n\n /**\n * This method is used to append a new UI node to the end of the old one.\n * Once appended a new UI node, the previous UI node cannot be updated anymore.\n *\n * @example\n * ```jsx\n * const ui = createStreamableUI(<div>hello</div>)\n * ui.append(<div>world</div>)\n *\n * // The UI node will be:\n * // <>\n * // <div>hello</div>\n * // <div>world</div>\n * // </>\n * ```\n */\n append(value: React.ReactNode): StreamableUIWrapper;\n\n /**\n * This method is used to signal that there is an error in the UI stream.\n * It will be thrown on the client side and caught by the nearest error boundary component.\n */\n error(error: any): StreamableUIWrapper;\n\n /**\n * This method marks the UI node as finalized. You can either call it without any parameters or with a new UI node as the final state.\n * Once called, the UI node cannot be updated or appended anymore.\n *\n * This method is always **required** to be called, otherwise the response will be stuck in a loading state.\n */\n done(...args: [React.ReactNode] | []): StreamableUIWrapper;\n};\n\n/**\n * Create a piece of changeable UI that can be streamed to the client.\n * On the client side, it can be rendered as a normal React node.\n */\nfunction createStreamableUI(initialValue?: React.ReactNode) {\n let currentValue = initialValue;\n let closed = false;\n let { row, resolve, reject } = createSuspendedChunk(initialValue);\n\n function assertStream(method: string) {\n if (closed) {\n throw new Error(method + ': UI stream is already closed.');\n }\n }\n\n let warningTimeout: NodeJS.Timeout | undefined;\n function warnUnclosedStream() {\n if (process.env.NODE_ENV === 'development') {\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n warningTimeout = setTimeout(() => {\n console.warn(\n 'The streamable UI has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`.',\n );\n }, HANGING_STREAM_WARNING_TIME_MS);\n }\n }\n warnUnclosedStream();\n\n const streamable: StreamableUIWrapper = {\n value: row,\n update(value: React.ReactNode) {\n assertStream('.update()');\n\n // There is no need to update the value if it's referentially equal.\n if (value === currentValue) {\n warnUnclosedStream();\n return streamable;\n }\n\n const resolvable = createResolvablePromise();\n currentValue = value;\n\n resolve({ value: currentValue, done: false, next: resolvable.promise });\n resolve = resolvable.resolve;\n reject = resolvable.reject;\n\n warnUnclosedStream();\n\n return streamable;\n },\n append(value: React.ReactNode) {\n assertStream('.append()');\n\n const resolvable = createResolvablePromise();\n currentValue = value;\n\n resolve({ value, done: false, append: true, next: resolvable.promise });\n resolve = resolvable.resolve;\n reject = resolvable.reject;\n\n warnUnclosedStream();\n\n return streamable;\n },\n error(error: any) {\n assertStream('.error()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n reject(error);\n\n return streamable;\n },\n done(...args: [] | [React.ReactNode]) {\n assertStream('.done()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n if (args.length) {\n resolve({ value: args[0], done: true });\n return streamable;\n }\n resolve({ value: currentValue, done: true });\n\n return streamable;\n },\n };\n\n return streamable;\n}\n\nexport { createStreamableUI };\n","export function isAsyncGenerator<T, TReturn, TNext>(\n value: unknown,\n): value is AsyncGenerator<T, TReturn, TNext> {\n return (\n value != null && typeof value === 'object' && Symbol.asyncIterator in value\n );\n}\n","export function isGenerator<T, TReturn, TNext>(\n value: unknown,\n): value is Generator<T, TReturn, TNext> {\n return value != null && typeof value === 'object' && Symbol.iterator in value;\n}\n","export const STREAMABLE_VALUE_TYPE = Symbol.for('ui.streamable.value');\n\nexport type StreamablePatch = undefined | [0, string]; // Append string.\n\ndeclare const __internal_curr: unique symbol;\ndeclare const __internal_error: unique symbol;\n\n/**\n * StreamableValue is a value that can be streamed over the network via AI Actions.\n * To read the streamed values, use the `readStreamableValue` or `useStreamableValue` APIs.\n */\nexport type StreamableValue<T = any, E = any> = {\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n type?: typeof STREAMABLE_VALUE_TYPE;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n curr?: T;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n error?: E;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n diff?: StreamablePatch;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n next?: Promise<StreamableValue<T, E>>;\n\n // branded types to maintain type signature after internal properties are stripped.\n [__internal_curr]?: T;\n [__internal_error]?: E;\n};\n","import { HANGING_STREAM_WARNING_TIME_MS } from '../util/constants';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport {\n STREAMABLE_VALUE_TYPE,\n StreamablePatch,\n StreamableValue,\n} from './streamable-value';\n\nconst STREAMABLE_VALUE_INTERNAL_LOCK = Symbol('streamable.value.lock');\n\n/**\n * Create a wrapped, changeable value that can be streamed to the client.\n * On the client side, the value can be accessed via the readStreamableValue() API.\n */\nfunction createStreamableValue<T = any, E = any>(\n initialValue?: T | ReadableStream<T>,\n) {\n const isReadableStream =\n initialValue instanceof ReadableStream ||\n (typeof initialValue === 'object' &&\n initialValue !== null &&\n 'getReader' in initialValue &&\n typeof initialValue.getReader === 'function' &&\n 'locked' in initialValue &&\n typeof initialValue.locked === 'boolean');\n\n if (!isReadableStream) {\n return createStreamableValueImpl<T, E>(initialValue);\n }\n\n const streamableValue = createStreamableValueImpl<T, E>();\n\n // Since the streamable value will be from a readable stream, it's not allowed\n // to update the value manually as that introduces race conditions and\n // unexpected behavior.\n // We lock the value to prevent any updates from the user.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;\n\n (async () => {\n try {\n // Consume the readable stream and update the value.\n const reader = initialValue.getReader();\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n\n // Unlock the value to allow updates.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n if (typeof value === 'string') {\n streamableValue.append(value);\n } else {\n streamableValue.update(value);\n }\n // Lock the value again.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;\n }\n\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n streamableValue.done();\n } catch (e) {\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n streamableValue.error(e);\n }\n })();\n\n return streamableValue;\n}\n\n// It's necessary to define the type manually here, otherwise TypeScript compiler\n// will not be able to infer the correct return type as it's circular.\ntype StreamableValueWrapper<T, E> = {\n /**\n * The value of the streamable. This can be returned from a Server Action and\n * received by the client. To read the streamed values, use the\n * `readStreamableValue` or `useStreamableValue` APIs.\n */\n readonly value: StreamableValue<T, E>;\n\n /**\n * This method updates the current value with a new one.\n */\n update(value: T): StreamableValueWrapper<T, E>;\n\n /**\n * This method is used to append a delta string to the current value. It\n * requires the current value of the streamable to be a string.\n *\n * @example\n * ```jsx\n * const streamable = createStreamableValue('hello');\n * streamable.append(' world');\n *\n * // The value will be 'hello world'\n * ```\n */\n append(value: T): StreamableValueWrapper<T, E>;\n\n /**\n * This method is used to signal that there is an error in the value stream.\n * It will be thrown on the client side when consumed via\n * `readStreamableValue` or `useStreamableValue`.\n */\n error(error: any): StreamableValueWrapper<T, E>;\n\n /**\n * This method marks the value as finalized. You can either call it without\n * any parameters or with a new value as the final state.\n * Once called, the value cannot be updated or appended anymore.\n *\n * This method is always **required** to be called, otherwise the response\n * will be stuck in a loading state.\n */\n done(...args: [T] | []): StreamableValueWrapper<T, E>;\n\n /**\n * @internal This is an internal lock to prevent the value from being\n * updated by the user.\n */\n [STREAMABLE_VALUE_INTERNAL_LOCK]: boolean;\n};\n\nfunction createStreamableValueImpl<T = any, E = any>(initialValue?: T) {\n let closed = false;\n let locked = false;\n let resolvable = createResolvablePromise<StreamableValue<T, E>>();\n\n let currentValue = initialValue;\n let currentError: E | undefined;\n let currentPromise: typeof resolvable.promise | undefined =\n resolvable.promise;\n let currentPatchValue: StreamablePatch;\n\n function assertStream(method: string) {\n if (closed) {\n throw new Error(method + ': Value stream is already closed.');\n }\n if (locked) {\n throw new Error(\n method + ': Value stream is locked and cannot be updated.',\n );\n }\n }\n\n let warningTimeout: NodeJS.Timeout | undefined;\n function warnUnclosedStream() {\n if (process.env.NODE_ENV === 'development') {\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n warningTimeout = setTimeout(() => {\n console.warn(\n 'The streamable value has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`.',\n );\n }, HANGING_STREAM_WARNING_TIME_MS);\n }\n }\n warnUnclosedStream();\n\n function createWrapped(initialChunk?: boolean): StreamableValue<T, E> {\n // This makes the payload much smaller if there're mutative updates before the first read.\n let init: Partial<StreamableValue<T, E>>;\n\n if (currentError !== undefined) {\n init = { error: currentError };\n } else {\n if (currentPatchValue && !initialChunk) {\n init = { diff: currentPatchValue };\n } else {\n init = { curr: currentValue };\n }\n }\n\n if (currentPromise) {\n init.next = currentPromise;\n }\n\n if (initialChunk) {\n init.type = STREAMABLE_VALUE_TYPE;\n }\n\n return init;\n }\n\n // Update the internal `currentValue` and `currentPatchValue` if needed.\n function updateValueStates(value: T) {\n // If we can only send a patch over the wire, it's better to do so.\n currentPatchValue = undefined;\n if (typeof value === 'string') {\n if (typeof currentValue === 'string') {\n if (value.startsWith(currentValue)) {\n currentPatchValue = [0, value.slice(currentValue.length)];\n }\n }\n }\n\n currentValue = value;\n }\n\n const streamable: StreamableValueWrapper<T, E> = {\n set [STREAMABLE_VALUE_INTERNAL_LOCK](state: boolean) {\n locked = state;\n },\n get value() {\n return createWrapped(true);\n },\n update(value: T) {\n assertStream('.update()');\n\n const resolvePrevious = resolvable.resolve;\n resolvable = createResolvablePromise();\n\n updateValueStates(value);\n currentPromise = resolvable.promise;\n resolvePrevious(createWrapped());\n\n warnUnclosedStream();\n\n return streamable;\n },\n append(value: T) {\n assertStream('.append()');\n\n if (\n typeof currentValue !== 'string' &&\n typeof currentValue !== 'undefined'\n ) {\n throw new Error(\n `.append(): The current value is not a string. Received: ${typeof currentValue}`,\n );\n }\n if (typeof value !== 'string') {\n throw new Error(\n `.append(): The value is not a string. Received: ${typeof value}`,\n );\n }\n\n const resolvePrevious = resolvable.resolve;\n resolvable = createResolvablePromise();\n\n if (typeof currentValue === 'string') {\n currentPatchValue = [0, value];\n (currentValue as string) = currentValue + value;\n } else {\n currentPatchValue = undefined;\n currentValue = value;\n }\n\n currentPromise = resolvable.promise;\n resolvePrevious(createWrapped());\n\n warnUnclosedStream();\n\n return streamable;\n },\n error(error: any) {\n assertStream('.error()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n currentError = error;\n currentPromise = undefined;\n\n resolvable.resolve({ error });\n\n return streamable;\n },\n done(...args: [] | [T]) {\n assertStream('.done()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n currentPromise = undefined;\n\n if (args.length) {\n updateValueStates(args[0]);\n resolvable.resolve(createWrapped());\n return streamable;\n }\n\n resolvable.resolve({});\n\n return streamable;\n },\n };\n\n return streamable;\n}\n\nexport { createStreamableValue };\n"],"mappings":";AAAA,YAAY,mBAAmB;AAC/B,SAAS,yBAAyB;;;ACQ3B,SAAS,0BAId;AACA,MAAI;AACJ,MAAI;AAEJ,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU;AACV,aAAS;AAAA,EACX,CAAC;AAED,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACrBO,IAAM,aAAa,CAAC,UACzB,OAAO,UAAU;;;AFOnB,IAAM,sBAAsB,IAAI,kBAO7B;AAEH,SAAS,uBAAuB,SAAiB;AAC/C,QAAM,QAAQ,oBAAoB,SAAS;AAC3C,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,OAAO;AAAA,EACzB;AACA,SAAO;AACT;AAEO,SAAS,YACd,EAAE,OAAO,QAAQ,GACjB,IACG;AACH,SAAO,oBAAoB;AAAA,IACzB;AAAA,MACE,cAAc,KAA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f,0BAAkB,KAAK,CAAC,CAAC;AACzB,mBAAW,QAAQ,cAAc,CAAC;AAClC,eAAO;AAAA,MACT;AAEA,iBAAW,QAAQ,CAAC,CAAC;AAErB,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["jsx"]}
1
+ {"version":3,"sources":["../src/ai-state.tsx","../src/util/create-resolvable-promise.ts","../src/util/is-function.ts","../src/provider.tsx","../src/stream-ui/stream-ui.tsx","../src/util/constants.ts","../src/streamable-ui/create-suspended-chunk.tsx","../src/streamable-ui/create-streamable-ui.tsx","../src/util/is-async-generator.ts","../src/util/is-generator.ts","../src/streamable-value/streamable-value.ts","../src/streamable-value/create-streamable-value.ts"],"sourcesContent":["import * as jsondiffpatch from 'jsondiffpatch';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { createResolvablePromise } from './util/create-resolvable-promise';\nimport { isFunction } from './util/is-function';\nimport type {\n AIProvider,\n InferAIState,\n InternalAIStateStorageOptions,\n MutableAIState,\n ValueOrUpdater,\n} from './types';\n\n// It is possible that multiple AI requests get in concurrently, for different\n// AI instances. So ALS is necessary here for a simpler API.\nconst asyncAIStateStorage = new AsyncLocalStorage<{\n currentState: any;\n originalState: any;\n sealed: boolean;\n options: InternalAIStateStorageOptions;\n mutationDeltaPromise?: Promise<any>;\n mutationDeltaResolve?: (v: any) => void;\n}>();\n\nfunction getAIStateStoreOrThrow(message: string) {\n const store = asyncAIStateStorage.getStore();\n if (!store) {\n throw new Error(message);\n }\n return store;\n}\n\nexport function withAIState<S, T>(\n { state, options }: { state: S; options: InternalAIStateStorageOptions },\n fn: () => T,\n): T {\n return asyncAIStateStorage.run(\n {\n currentState: JSON.parse(JSON.stringify(state)), // deep clone object\n originalState: state,\n sealed: false,\n options,\n },\n fn,\n );\n}\n\nexport function getAIStateDeltaPromise() {\n const store = getAIStateStoreOrThrow('Internal error occurred.');\n return store.mutationDeltaPromise;\n}\n\n// Internal method. This will be called after the AI Action has been returned\n// and you can no longer call `getMutableAIState()` inside any async callbacks\n// created by that Action.\nexport function sealMutableAIState() {\n const store = getAIStateStoreOrThrow('Internal error occurred.');\n store.sealed = true;\n}\n\n/**\n * Get the current AI state.\n * If `key` is provided, it will return the value of the specified key in the\n * AI state, if it's an object. If it's not an object, it will throw an error.\n *\n * @example const state = getAIState() // Get the entire AI state\n * @example const field = getAIState('key') // Get the value of the key\n */\nfunction getAIState<AI extends AIProvider = any>(): Readonly<\n InferAIState<AI, any>\n>;\nfunction getAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): Readonly<InferAIState<AI, any>[typeof key]>;\nfunction getAIState<AI extends AIProvider = any>(\n ...args: [] | [key: keyof InferAIState<AI, any>]\n) {\n const store = getAIStateStoreOrThrow(\n '`getAIState` must be called within an AI Action.',\n );\n\n if (args.length > 0) {\n const key = args[0];\n if (typeof store.currentState !== 'object') {\n throw new Error(\n `You can't get the \"${String(\n key,\n )}\" field from the AI state because it's not an object.`,\n );\n }\n return store.currentState[key as keyof typeof store.currentState];\n }\n\n return store.currentState;\n}\n\n/**\n * Get the mutable AI state. Note that you must call `.done()` when finishing\n * updating the AI state.\n *\n * @example\n * ```tsx\n * const state = getMutableAIState()\n * state.update({ ...state.get(), key: 'value' })\n * state.update((currentState) => ({ ...currentState, key: 'value' }))\n * state.done()\n * ```\n *\n * @example\n * ```tsx\n * const state = getMutableAIState()\n * state.done({ ...state.get(), key: 'value' }) // Done with a new state\n * ```\n */\nfunction getMutableAIState<AI extends AIProvider = any>(): MutableAIState<\n InferAIState<AI, any>\n>;\nfunction getMutableAIState<AI extends AIProvider = any>(\n key: keyof InferAIState<AI, any>,\n): MutableAIState<InferAIState<AI, any>[typeof key]>;\nfunction getMutableAIState<AI extends AIProvider = any>(\n ...args: [] | [key: keyof InferAIState<AI, any>]\n) {\n type AIState = InferAIState<AI, any>;\n type AIStateWithKey = typeof args extends [key: keyof AIState]\n ? AIState[(typeof args)[0]]\n : AIState;\n type NewStateOrUpdater = ValueOrUpdater<AIStateWithKey>;\n\n const store = getAIStateStoreOrThrow(\n '`getMutableAIState` must be called within an AI Action.',\n );\n\n if (store.sealed) {\n throw new Error(\n \"`getMutableAIState` must be called before returning from an AI Action. Please move it to the top level of the Action's function body.\",\n );\n }\n\n if (!store.mutationDeltaPromise) {\n const { promise, resolve } = createResolvablePromise();\n store.mutationDeltaPromise = promise;\n store.mutationDeltaResolve = resolve;\n }\n\n function doUpdate(newState: NewStateOrUpdater, done: boolean) {\n if (args.length > 0) {\n if (typeof store.currentState !== 'object') {\n const key = args[0];\n throw new Error(\n `You can't modify the \"${String(\n key,\n )}\" field of the AI state because it's not an object.`,\n );\n }\n }\n\n if (isFunction(newState)) {\n if (args.length > 0) {\n store.currentState[args[0]] = newState(store.currentState[args[0]]);\n } else {\n store.currentState = newState(store.currentState);\n }\n } else {\n if (args.length > 0) {\n store.currentState[args[0]] = newState;\n } else {\n store.currentState = newState;\n }\n }\n\n store.options.onSetAIState?.({\n key: args.length > 0 ? args[0] : undefined,\n state: store.currentState,\n done,\n });\n }\n\n const mutableState = {\n get: () => {\n if (args.length > 0) {\n const key = args[0];\n if (typeof store.currentState !== 'object') {\n throw new Error(\n `You can't get the \"${String(\n key,\n )}\" field from the AI state because it's not an object.`,\n );\n }\n return store.currentState[key] as Readonly<AIStateWithKey>;\n }\n\n return store.currentState as Readonly<AIState>;\n },\n update: function update(newAIState: NewStateOrUpdater) {\n doUpdate(newAIState, false);\n },\n done: function done(...doneArgs: [] | [NewStateOrUpdater]) {\n if (doneArgs.length > 0) {\n doUpdate(doneArgs[0] as NewStateOrUpdater, true);\n }\n\n const delta = jsondiffpatch.diff(store.originalState, store.currentState);\n store.mutationDeltaResolve!(delta);\n },\n };\n\n return mutableState;\n}\n\nexport { getAIState, getMutableAIState };\n","/**\n * Creates a Promise with externally accessible resolve and reject functions.\n *\n * @template T - The type of the value that the Promise will resolve to.\n * @returns An object containing:\n * - promise: A Promise that can be resolved or rejected externally.\n * - resolve: A function to resolve the Promise with a value of type T.\n * - reject: A function to reject the Promise with an error.\n */\nexport function createResolvablePromise<T = any>(): {\n promise: Promise<T>;\n resolve: (value: T) => void;\n reject: (error: unknown) => void;\n} {\n let resolve: (value: T) => void;\n let reject: (error: unknown) => void;\n\n const promise = new Promise<T>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n\n return {\n promise,\n resolve: resolve!,\n reject: reject!,\n };\n}\n","/**\n * Checks if the given value is a function.\n *\n * @param {unknown} value - The value to check.\n * @returns {boolean} True if the value is a function, false otherwise.\n */\nexport const isFunction = (value: unknown): value is Function =>\n typeof value === 'function';\n","// This file provides the AI context to all AI Actions via AsyncLocalStorage.\n\nimport * as React from 'react';\nimport { InternalAIProvider } from './rsc-shared.mjs';\nimport {\n withAIState,\n getAIStateDeltaPromise,\n sealMutableAIState,\n} from './ai-state';\nimport type {\n ServerWrappedActions,\n AIAction,\n AIActions,\n AIProvider,\n InternalAIStateStorageOptions,\n OnSetAIState,\n OnGetUIState,\n} from './types';\n\nasync function innerAction<T>(\n {\n action,\n options,\n }: { action: AIAction; options: InternalAIStateStorageOptions },\n state: T,\n ...args: unknown[]\n) {\n 'use server';\n return await withAIState(\n {\n state,\n options,\n },\n async () => {\n const result = await action(...args);\n sealMutableAIState();\n return [getAIStateDeltaPromise() as Promise<T>, result];\n },\n );\n}\n\nfunction wrapAction<T = unknown>(\n action: AIAction,\n options: InternalAIStateStorageOptions,\n) {\n return innerAction.bind(null, { action, options }) as AIAction<T>;\n}\n\nexport function createAI<\n AIState = any,\n UIState = any,\n Actions extends AIActions = {},\n>({\n actions,\n initialAIState,\n initialUIState,\n\n onSetAIState,\n onGetUIState,\n}: {\n actions: Actions;\n initialAIState?: AIState;\n initialUIState?: UIState;\n\n /**\n * This function is called whenever the AI state is updated by an Action.\n * You can use this to persist the AI state to a database, or to send it to a\n * logging service.\n */\n onSetAIState?: OnSetAIState<AIState>;\n\n /**\n * This function is used to retrieve the UI state based on the AI state.\n * For example, to render the initial UI state based on a given AI state, or\n * to sync the UI state when the application is already loaded.\n *\n * If returning `undefined`, the client side UI state will not be updated.\n *\n * This function must be annotated with the `\"use server\"` directive.\n *\n * @example\n * ```tsx\n * onGetUIState: async () => {\n * 'use server';\n *\n * const currentAIState = getAIState();\n * const externalAIState = await loadAIStateFromDatabase();\n *\n * if (currentAIState === externalAIState) return undefined;\n *\n * // Update current AI state and return the new UI state\n * const state = getMutableAIState()\n * state.done(externalAIState)\n *\n * return <div>...</div>;\n * }\n * ```\n */\n onGetUIState?: OnGetUIState<UIState>;\n}) {\n // Wrap all actions with our HoC.\n const wrappedActions: ServerWrappedActions = {};\n for (const name in actions) {\n wrappedActions[name] = wrapAction(actions[name], {\n onSetAIState,\n });\n }\n\n const wrappedSyncUIState = onGetUIState\n ? wrapAction(onGetUIState, {})\n : undefined;\n\n const AI: AIProvider<AIState, UIState, Actions> = async props => {\n if ('useState' in React) {\n // This file must be running on the React Server layer.\n // Ideally we should be using `import \"server-only\"` here but we can have a\n // more customized error message with this implementation.\n throw new Error(\n 'This component can only be used inside Server Components.',\n );\n }\n\n let uiState = props.initialUIState ?? initialUIState;\n let aiState = props.initialAIState ?? initialAIState;\n let aiStateDelta = undefined;\n\n if (wrappedSyncUIState) {\n const [newAIStateDelta, newUIState] = await wrappedSyncUIState(aiState);\n if (newUIState !== undefined) {\n aiStateDelta = newAIStateDelta;\n uiState = newUIState;\n }\n }\n\n return (\n <InternalAIProvider\n wrappedActions={wrappedActions}\n wrappedSyncUIState={wrappedSyncUIState}\n initialUIState={uiState}\n initialAIState={aiState}\n initialAIStatePatch={aiStateDelta}\n >\n {props.children}\n </InternalAIProvider>\n );\n };\n\n return AI;\n}\n","import {\n LanguageModelV4,\n LanguageModelV4StreamResult,\n LanguageModelV4Usage,\n SharedV4Warning,\n} from '@ai-sdk/provider';\nimport {\n InferSchema,\n ProviderOptions,\n safeParseJSON,\n} from '@ai-sdk/provider-utils';\nimport {\n CallWarning,\n FinishReason,\n InvalidToolInputError,\n LanguageModelUsage,\n LanguageModelCallOptions,\n NoSuchToolError,\n Prompt,\n RequestOptions,\n Schema,\n ToolChoice,\n} from 'ai';\nimport {\n asLanguageModelUsage,\n convertToLanguageModelPrompt,\n prepareLanguageModelCallOptions,\n prepareRetries,\n prepareToolChoice,\n prepareTools,\n standardizePrompt,\n} from 'ai/internal';\nimport { ReactNode } from 'react';\nimport * as z3 from 'zod/v3';\nimport * as z4 from 'zod/v4';\nimport { createStreamableUI } from '../streamable-ui/create-streamable-ui';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport { isAsyncGenerator } from '../util/is-async-generator';\nimport { isGenerator } from '../util/is-generator';\n\ntype Streamable = ReactNode | Promise<ReactNode>;\n\ntype Renderer<T extends Array<any>> = (\n ...args: T\n) =>\n | Streamable\n | Generator<Streamable, Streamable, void>\n | AsyncGenerator<Streamable, Streamable, void>;\n\ntype RenderTool<\n INPUT_SCHEMA extends z4.core.$ZodType | z3.Schema | Schema = any,\n> = {\n description?: string;\n inputSchema: INPUT_SCHEMA;\n generate?: Renderer<\n [\n InferSchema<INPUT_SCHEMA>,\n {\n toolName: string;\n toolCallId: string;\n },\n ]\n >;\n};\n\ntype RenderText = Renderer<\n [\n {\n /**\n * The full text content from the model so far.\n */\n content: string;\n\n /**\n * The new appended text content from the model since the last `text` call.\n */\n delta: string;\n\n /**\n * Whether the model is done generating text.\n * If `true`, the `content` will be the final output and this call will be the last.\n */\n done: boolean;\n },\n ]\n>;\n\ntype RenderResult = {\n value: ReactNode;\n} & LanguageModelV4StreamResult;\n\nconst defaultTextRenderer: RenderText = ({ content }: { content: string }) =>\n content;\n\n/**\n * `streamUI` is a helper function to create a streamable UI from LLMs.\n */\nexport async function streamUI<\n TOOLS extends { [name: string]: z4.core.$ZodType | z3.Schema | Schema } = {},\n>({\n model,\n tools,\n toolChoice,\n system,\n prompt,\n messages,\n maxRetries,\n abortSignal,\n headers,\n initial,\n text,\n providerOptions,\n onFinish,\n ...settings\n}: LanguageModelCallOptions &\n Omit<RequestOptions, 'timeout'> &\n Prompt & {\n /**\n * The language model to use.\n */\n model: LanguageModelV4;\n\n /**\n * The tools that the model can call. The model needs to support calling tools.\n */\n tools?: {\n [name in keyof TOOLS]: RenderTool<TOOLS[name]>;\n };\n\n /**\n * The tool choice strategy. Default: 'auto'.\n */\n toolChoice?: ToolChoice<TOOLS>;\n\n text?: RenderText;\n initial?: ReactNode;\n\n /**\n * Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n\n /**\n * Callback that is called when the LLM response and the final object validation are finished.\n */\n onFinish?: (event: {\n /**\n * The reason why the generation finished.\n */\n finishReason: FinishReason;\n /**\n * The token usage of the generated response.\n */\n usage: LanguageModelUsage;\n /**\n * The final ui node that was generated.\n */\n value: ReactNode;\n /**\n * Warnings from the model provider (e.g. unsupported settings)\n */\n warnings?: CallWarning[];\n /**\n * Optional response data.\n */\n response?: {\n /**\n * Response headers.\n */\n headers?: Record<string, string>;\n };\n }) => Promise<void> | void;\n }): Promise<RenderResult> {\n // TODO: Remove these errors after the experimental phase.\n if (typeof model === 'string') {\n throw new Error(\n '`model` cannot be a string in `streamUI`. Use the actual model instance instead.',\n );\n }\n if ('functions' in settings) {\n throw new Error(\n '`functions` is not supported in `streamUI`, use `tools` instead.',\n );\n }\n if ('provider' in settings) {\n throw new Error(\n '`provider` is no longer needed in `streamUI`. Use `model` instead.',\n );\n }\n if (tools) {\n for (const [name, tool] of Object.entries(tools)) {\n if ('render' in tool) {\n throw new Error(\n 'Tool definition in `streamUI` should not have `render` property. Use `generate` instead. Found in tool: ' +\n name,\n );\n }\n }\n }\n\n const ui = createStreamableUI(initial);\n\n // The default text renderer just returns the content as string.\n const textRender = text || defaultTextRenderer;\n\n let finished: Promise<void> | undefined;\n\n let finishEvent: {\n finishReason: FinishReason;\n usage: LanguageModelV4Usage;\n warnings?: CallWarning[];\n response?: {\n headers?: Record<string, string>;\n };\n } | null = null;\n\n async function render({\n args,\n renderer,\n streamableUI,\n isLastCall = false,\n }: {\n renderer: undefined | Renderer<any>;\n args: [payload: any] | [payload: any, options: any];\n streamableUI: ReturnType<typeof createStreamableUI>;\n isLastCall?: boolean;\n }) {\n if (!renderer) return;\n\n // create a promise that will be resolved when the render call is finished.\n // it is appended to the `finished` promise chain to ensure the render call\n // is finished before the next render call starts.\n const renderFinished = createResolvablePromise<void>();\n finished = finished\n ? finished.then(() => renderFinished.promise)\n : renderFinished.promise;\n\n const rendererResult = renderer(...args);\n\n if (isAsyncGenerator(rendererResult) || isGenerator(rendererResult)) {\n while (true) {\n const { done, value } = await rendererResult.next();\n const node = await value;\n\n if (isLastCall && done) {\n streamableUI.done(node);\n } else {\n streamableUI.update(node);\n }\n\n if (done) break;\n }\n } else {\n const node = await rendererResult;\n\n if (isLastCall) {\n streamableUI.done(node);\n } else {\n streamableUI.update(node);\n }\n }\n\n // resolve the promise to signal that the render call is finished\n renderFinished.resolve(undefined);\n }\n\n const { retry } = prepareRetries({ maxRetries, abortSignal });\n\n const validatedPrompt = await standardizePrompt({\n system,\n prompt,\n messages,\n } as Prompt);\n const languageModelTools = await prepareTools({\n tools: tools,\n });\n const languageModelToolChoice = prepareToolChoice({\n toolChoice,\n });\n\n const result = await retry(async () =>\n model.doStream({\n ...prepareLanguageModelCallOptions(settings),\n tools: languageModelTools,\n toolChoice: languageModelToolChoice,\n prompt: await convertToLanguageModelPrompt({\n prompt: validatedPrompt,\n supportedUrls: await model.supportedUrls,\n download: undefined,\n provider: model.provider.split('.')[0],\n }),\n providerOptions,\n abortSignal,\n headers,\n includeRawChunks: false,\n }),\n );\n\n // For the stream and consume it asynchronously:\n const [stream, forkedStream] = result.stream.tee();\n (async () => {\n try {\n let content = '';\n let hasToolCall = false;\n let warnings: SharedV4Warning[] | undefined;\n\n const reader = forkedStream.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n switch (value.type) {\n case 'stream-start': {\n warnings = value.warnings;\n break;\n }\n\n case 'text-delta': {\n content += value.delta;\n render({\n renderer: textRender,\n args: [{ content, done: false, delta: value.delta }],\n streamableUI: ui,\n });\n break;\n }\n\n case 'tool-input-start':\n case 'tool-input-delta': {\n hasToolCall = true;\n break;\n }\n\n case 'tool-call': {\n const toolName = value.toolName as keyof TOOLS & string;\n\n if (!tools) {\n throw new NoSuchToolError({ toolName });\n }\n\n const tool = tools[toolName];\n if (!tool) {\n throw new NoSuchToolError({\n toolName,\n availableTools: Object.keys(tools),\n });\n }\n\n hasToolCall = true;\n const parseResult = await safeParseJSON({\n text: value.input,\n schema: tool.inputSchema,\n });\n\n if (parseResult.success === false) {\n throw new InvalidToolInputError({\n toolName,\n toolInput: value.input,\n cause: parseResult.error,\n });\n }\n\n render({\n renderer: tool.generate,\n args: [\n parseResult.value,\n {\n toolName,\n toolCallId: value.toolCallId,\n },\n ],\n streamableUI: ui,\n isLastCall: true,\n });\n\n break;\n }\n\n case 'error': {\n throw value.error;\n }\n\n case 'finish': {\n finishEvent = {\n finishReason: value.finishReason?.unified,\n usage: value.usage,\n warnings,\n response: result.response,\n };\n break;\n }\n }\n }\n\n if (!hasToolCall) {\n render({\n renderer: textRender,\n args: [{ content, done: true }],\n streamableUI: ui,\n isLastCall: true,\n });\n }\n\n await finished;\n\n if (finishEvent && onFinish) {\n await onFinish({\n ...finishEvent,\n usage: asLanguageModelUsage(finishEvent.usage),\n value: ui.value,\n });\n }\n } catch (error) {\n // During the stream rendering, we don't want to throw the error to the\n // parent scope but only let the React's error boundary to catch it.\n ui.error(error);\n }\n })();\n\n return {\n ...result,\n stream,\n value: ui.value,\n };\n}\n","/**\n * Warning time for notifying developers that a stream is hanging in dev mode\n * using a console.warn.\n */\nexport const HANGING_STREAM_WARNING_TIME_MS = 15 * 1000;\n","import React, { Suspense } from 'react';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\n\n// Recursive type for the chunk.\ntype ChunkType =\n | {\n done: false;\n value: React.ReactNode;\n next: Promise<ChunkType>;\n append?: boolean;\n }\n | {\n done: true;\n value: React.ReactNode;\n };\n\n// Use single letter names for the variables to reduce the size of the RSC payload.\n// `R` for `Row`, `c` for `current`, `n` for `next`.\n// Note: Array construction is needed to access the name R.\nconst R = [\n (async ({\n c: current,\n n: next,\n }: {\n c: React.ReactNode;\n n: Promise<ChunkType>;\n }) => {\n const chunk = await next;\n\n if (chunk.done) {\n return chunk.value;\n }\n\n if (chunk.append) {\n return (\n <>\n {current}\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n </>\n );\n }\n\n return (\n <Suspense fallback={chunk.value}>\n <R c={chunk.value} n={chunk.next} />\n </Suspense>\n );\n }) as unknown as React.FC<{\n c: React.ReactNode;\n n: Promise<ChunkType>;\n }>,\n][0];\n\n/**\n * Creates a suspended chunk for React Server Components.\n *\n * This function generates a suspenseful React component that can be dynamically updated.\n * It's useful for streaming updates to the client in a React Server Components context.\n *\n * @param {React.ReactNode} initialValue - The initial value to render while the promise is pending.\n * @returns {Object} An object containing:\n * - row: A React node that renders the suspenseful content.\n * - resolve: A function to resolve the promise with a new value.\n * - reject: A function to reject the promise with an error.\n */\nexport function createSuspendedChunk(initialValue: React.ReactNode): {\n row: React.ReactNode;\n resolve: (value: ChunkType) => void;\n reject: (error: unknown) => void;\n} {\n const { promise, resolve, reject } = createResolvablePromise<ChunkType>();\n\n return {\n row: (\n <Suspense fallback={initialValue}>\n <R c={initialValue} n={promise} />\n </Suspense>\n ),\n resolve,\n reject,\n };\n}\n","import { HANGING_STREAM_WARNING_TIME_MS } from '../util/constants';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport { createSuspendedChunk } from './create-suspended-chunk';\n\n// It's necessary to define the type manually here, otherwise TypeScript compiler\n// will not be able to infer the correct return type as it's circular.\ntype StreamableUIWrapper = {\n /**\n * The value of the streamable UI. This can be returned from a Server Action and received by the client.\n */\n readonly value: React.ReactNode;\n\n /**\n * This method updates the current UI node. It takes a new UI node and replaces the old one.\n */\n update(value: React.ReactNode): StreamableUIWrapper;\n\n /**\n * This method is used to append a new UI node to the end of the old one.\n * Once appended a new UI node, the previous UI node cannot be updated anymore.\n *\n * @example\n * ```jsx\n * const ui = createStreamableUI(<div>hello</div>)\n * ui.append(<div>world</div>)\n *\n * // The UI node will be:\n * // <>\n * // <div>hello</div>\n * // <div>world</div>\n * // </>\n * ```\n */\n append(value: React.ReactNode): StreamableUIWrapper;\n\n /**\n * This method is used to signal that there is an error in the UI stream.\n * It will be thrown on the client side and caught by the nearest error boundary component.\n */\n error(error: any): StreamableUIWrapper;\n\n /**\n * This method marks the UI node as finalized. You can either call it without any parameters or with a new UI node as the final state.\n * Once called, the UI node cannot be updated or appended anymore.\n *\n * This method is always **required** to be called, otherwise the response will be stuck in a loading state.\n */\n done(...args: [React.ReactNode] | []): StreamableUIWrapper;\n};\n\n/**\n * Create a piece of changeable UI that can be streamed to the client.\n * On the client side, it can be rendered as a normal React node.\n */\nfunction createStreamableUI(initialValue?: React.ReactNode) {\n let currentValue = initialValue;\n let closed = false;\n let { row, resolve, reject } = createSuspendedChunk(initialValue);\n\n function assertStream(method: string) {\n if (closed) {\n throw new Error(method + ': UI stream is already closed.');\n }\n }\n\n let warningTimeout: NodeJS.Timeout | undefined;\n function warnUnclosedStream() {\n if (process.env.NODE_ENV === 'development') {\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n warningTimeout = setTimeout(() => {\n console.warn(\n 'The streamable UI has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`.',\n );\n }, HANGING_STREAM_WARNING_TIME_MS);\n }\n }\n warnUnclosedStream();\n\n const streamable: StreamableUIWrapper = {\n value: row,\n update(value: React.ReactNode) {\n assertStream('.update()');\n\n // There is no need to update the value if it's referentially equal.\n if (value === currentValue) {\n warnUnclosedStream();\n return streamable;\n }\n\n const resolvable = createResolvablePromise();\n currentValue = value;\n\n resolve({ value: currentValue, done: false, next: resolvable.promise });\n resolve = resolvable.resolve;\n reject = resolvable.reject;\n\n warnUnclosedStream();\n\n return streamable;\n },\n append(value: React.ReactNode) {\n assertStream('.append()');\n\n const resolvable = createResolvablePromise();\n currentValue = value;\n\n resolve({ value, done: false, append: true, next: resolvable.promise });\n resolve = resolvable.resolve;\n reject = resolvable.reject;\n\n warnUnclosedStream();\n\n return streamable;\n },\n error(error: any) {\n assertStream('.error()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n reject(error);\n\n return streamable;\n },\n done(...args: [] | [React.ReactNode]) {\n assertStream('.done()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n if (args.length) {\n resolve({ value: args[0], done: true });\n return streamable;\n }\n resolve({ value: currentValue, done: true });\n\n return streamable;\n },\n };\n\n return streamable;\n}\n\nexport { createStreamableUI };\n","export function isAsyncGenerator<T, TReturn, TNext>(\n value: unknown,\n): value is AsyncGenerator<T, TReturn, TNext> {\n return (\n value != null && typeof value === 'object' && Symbol.asyncIterator in value\n );\n}\n","export function isGenerator<T, TReturn, TNext>(\n value: unknown,\n): value is Generator<T, TReturn, TNext> {\n return value != null && typeof value === 'object' && Symbol.iterator in value;\n}\n","export const STREAMABLE_VALUE_TYPE = Symbol.for('ui.streamable.value');\n\nexport type StreamablePatch = undefined | [0, string]; // Append string.\n\ndeclare const __internal_curr: unique symbol;\ndeclare const __internal_error: unique symbol;\n\n/**\n * StreamableValue is a value that can be streamed over the network via AI Actions.\n * To read the streamed values, use the `readStreamableValue` or `useStreamableValue` APIs.\n */\nexport type StreamableValue<T = any, E = any> = {\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n type?: typeof STREAMABLE_VALUE_TYPE;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n curr?: T;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n error?: E;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n diff?: StreamablePatch;\n /**\n * @internal Use `readStreamableValue` to read the values.\n */\n next?: Promise<StreamableValue<T, E>>;\n\n // branded types to maintain type signature after internal properties are stripped.\n [__internal_curr]?: T;\n [__internal_error]?: E;\n};\n","import { HANGING_STREAM_WARNING_TIME_MS } from '../util/constants';\nimport { createResolvablePromise } from '../util/create-resolvable-promise';\nimport {\n STREAMABLE_VALUE_TYPE,\n StreamablePatch,\n StreamableValue,\n} from './streamable-value';\n\nconst STREAMABLE_VALUE_INTERNAL_LOCK = Symbol('streamable.value.lock');\n\n/**\n * Create a wrapped, changeable value that can be streamed to the client.\n * On the client side, the value can be accessed via the readStreamableValue() API.\n */\nfunction createStreamableValue<T = any, E = any>(\n initialValue?: T | ReadableStream<T>,\n) {\n const isReadableStream =\n initialValue instanceof ReadableStream ||\n (typeof initialValue === 'object' &&\n initialValue !== null &&\n 'getReader' in initialValue &&\n typeof initialValue.getReader === 'function' &&\n 'locked' in initialValue &&\n typeof initialValue.locked === 'boolean');\n\n if (!isReadableStream) {\n return createStreamableValueImpl<T, E>(initialValue);\n }\n\n const streamableValue = createStreamableValueImpl<T, E>();\n\n // Since the streamable value will be from a readable stream, it's not allowed\n // to update the value manually as that introduces race conditions and\n // unexpected behavior.\n // We lock the value to prevent any updates from the user.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;\n\n (async () => {\n try {\n // Consume the readable stream and update the value.\n const reader = initialValue.getReader();\n\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n break;\n }\n\n // Unlock the value to allow updates.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n if (typeof value === 'string') {\n streamableValue.append(value);\n } else {\n streamableValue.update(value);\n }\n // Lock the value again.\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = true;\n }\n\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n streamableValue.done();\n } catch (e) {\n streamableValue[STREAMABLE_VALUE_INTERNAL_LOCK] = false;\n streamableValue.error(e);\n }\n })();\n\n return streamableValue;\n}\n\n// It's necessary to define the type manually here, otherwise TypeScript compiler\n// will not be able to infer the correct return type as it's circular.\ntype StreamableValueWrapper<T, E> = {\n /**\n * The value of the streamable. This can be returned from a Server Action and\n * received by the client. To read the streamed values, use the\n * `readStreamableValue` or `useStreamableValue` APIs.\n */\n readonly value: StreamableValue<T, E>;\n\n /**\n * This method updates the current value with a new one.\n */\n update(value: T): StreamableValueWrapper<T, E>;\n\n /**\n * This method is used to append a delta string to the current value. It\n * requires the current value of the streamable to be a string.\n *\n * @example\n * ```jsx\n * const streamable = createStreamableValue('hello');\n * streamable.append(' world');\n *\n * // The value will be 'hello world'\n * ```\n */\n append(value: T): StreamableValueWrapper<T, E>;\n\n /**\n * This method is used to signal that there is an error in the value stream.\n * It will be thrown on the client side when consumed via\n * `readStreamableValue` or `useStreamableValue`.\n */\n error(error: any): StreamableValueWrapper<T, E>;\n\n /**\n * This method marks the value as finalized. You can either call it without\n * any parameters or with a new value as the final state.\n * Once called, the value cannot be updated or appended anymore.\n *\n * This method is always **required** to be called, otherwise the response\n * will be stuck in a loading state.\n */\n done(...args: [T] | []): StreamableValueWrapper<T, E>;\n\n /**\n * @internal This is an internal lock to prevent the value from being\n * updated by the user.\n */\n [STREAMABLE_VALUE_INTERNAL_LOCK]: boolean;\n};\n\nfunction createStreamableValueImpl<T = any, E = any>(initialValue?: T) {\n let closed = false;\n let locked = false;\n let resolvable = createResolvablePromise<StreamableValue<T, E>>();\n\n let currentValue = initialValue;\n let currentError: E | undefined;\n let currentPromise: typeof resolvable.promise | undefined =\n resolvable.promise;\n let currentPatchValue: StreamablePatch;\n\n function assertStream(method: string) {\n if (closed) {\n throw new Error(method + ': Value stream is already closed.');\n }\n if (locked) {\n throw new Error(\n method + ': Value stream is locked and cannot be updated.',\n );\n }\n }\n\n let warningTimeout: NodeJS.Timeout | undefined;\n function warnUnclosedStream() {\n if (process.env.NODE_ENV === 'development') {\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n warningTimeout = setTimeout(() => {\n console.warn(\n 'The streamable value has been slow to update. This may be a bug or a performance issue or you forgot to call `.done()`.',\n );\n }, HANGING_STREAM_WARNING_TIME_MS);\n }\n }\n warnUnclosedStream();\n\n function createWrapped(initialChunk?: boolean): StreamableValue<T, E> {\n // This makes the payload much smaller if there're mutative updates before the first read.\n let init: Partial<StreamableValue<T, E>>;\n\n if (currentError !== undefined) {\n init = { error: currentError };\n } else {\n if (currentPatchValue && !initialChunk) {\n init = { diff: currentPatchValue };\n } else {\n init = { curr: currentValue };\n }\n }\n\n if (currentPromise) {\n init.next = currentPromise;\n }\n\n if (initialChunk) {\n init.type = STREAMABLE_VALUE_TYPE;\n }\n\n return init;\n }\n\n // Update the internal `currentValue` and `currentPatchValue` if needed.\n function updateValueStates(value: T) {\n // If we can only send a patch over the wire, it's better to do so.\n currentPatchValue = undefined;\n if (typeof value === 'string') {\n if (typeof currentValue === 'string') {\n if (value.startsWith(currentValue)) {\n currentPatchValue = [0, value.slice(currentValue.length)];\n }\n }\n }\n\n currentValue = value;\n }\n\n const streamable: StreamableValueWrapper<T, E> = {\n set [STREAMABLE_VALUE_INTERNAL_LOCK](state: boolean) {\n locked = state;\n },\n get value() {\n return createWrapped(true);\n },\n update(value: T) {\n assertStream('.update()');\n\n const resolvePrevious = resolvable.resolve;\n resolvable = createResolvablePromise();\n\n updateValueStates(value);\n currentPromise = resolvable.promise;\n resolvePrevious(createWrapped());\n\n warnUnclosedStream();\n\n return streamable;\n },\n append(value: T) {\n assertStream('.append()');\n\n if (\n typeof currentValue !== 'string' &&\n typeof currentValue !== 'undefined'\n ) {\n throw new Error(\n `.append(): The current value is not a string. Received: ${typeof currentValue}`,\n );\n }\n if (typeof value !== 'string') {\n throw new Error(\n `.append(): The value is not a string. Received: ${typeof value}`,\n );\n }\n\n const resolvePrevious = resolvable.resolve;\n resolvable = createResolvablePromise();\n\n if (typeof currentValue === 'string') {\n currentPatchValue = [0, value];\n (currentValue as string) = currentValue + value;\n } else {\n currentPatchValue = undefined;\n currentValue = value;\n }\n\n currentPromise = resolvable.promise;\n resolvePrevious(createWrapped());\n\n warnUnclosedStream();\n\n return streamable;\n },\n error(error: any) {\n assertStream('.error()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n currentError = error;\n currentPromise = undefined;\n\n resolvable.resolve({ error });\n\n return streamable;\n },\n done(...args: [] | [T]) {\n assertStream('.done()');\n\n if (warningTimeout) {\n clearTimeout(warningTimeout);\n }\n closed = true;\n currentPromise = undefined;\n\n if (args.length) {\n updateValueStates(args[0]);\n resolvable.resolve(createWrapped());\n return streamable;\n }\n\n resolvable.resolve({});\n\n return streamable;\n },\n };\n\n return streamable;\n}\n\nexport { createStreamableValue };\n"],"mappings":";AAAA,YAAY,mBAAmB;AAC/B,SAAS,yBAAyB;;;ACQ3B,SAAS,0BAId;AACA,MAAI;AACJ,MAAI;AAEJ,QAAM,UAAU,IAAI,QAAW,CAAC,KAAK,QAAQ;AAC3C,cAAU;AACV,aAAS;AAAA,EACX,CAAC;AAED,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;ACrBO,IAAM,aAAa,CAAC,UACzB,OAAO,UAAU;;;AFOnB,IAAM,sBAAsB,IAAI,kBAO7B;AAEH,SAAS,uBAAuB,SAAiB;AAC/C,QAAM,QAAQ,oBAAoB,SAAS;AAC3C,MAAI,CAAC,OAAO;AACV,UAAM,IAAI,MAAM,OAAO;AAAA,EACzB;AACA,SAAO;AACT;AAEO,SAAS,YACd,EAAE,OAAO,QAAQ,GACjB,IACG;AACH,SAAO,oBAAoB;AAAA,IACzB;AAAA,MACE,cAAc,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAAA;AAAA,MAC9C,eAAe;AAAA,MACf,QAAQ;AAAA,MACR;AAAA,IACF;AAAA,IACA;AAAA,EACF;AACF;AAEO,SAAS,yBAAyB;AACvC,QAAM,QAAQ,uBAAuB,0BAA0B;AAC/D,SAAO,MAAM;AACf;AAKO,SAAS,qBAAqB;AACnC,QAAM,QAAQ,uBAAuB,0BAA0B;AAC/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AA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":["jsx"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/rsc",
3
- "version": "3.0.0-beta.10",
3
+ "version": "3.0.0-beta.101",
4
4
  "license": "Apache-2.0",
5
5
  "sideEffects": false,
6
6
  "main": "./dist/rsc-client.mjs",
@@ -28,9 +28,9 @@
28
28
  ],
29
29
  "dependencies": {
30
30
  "jsondiffpatch": "0.7.3",
31
- "ai": "7.0.0-beta.10",
32
- "@ai-sdk/provider": "4.0.0-beta.0",
33
- "@ai-sdk/provider-utils": "5.0.0-beta.1"
31
+ "ai": "7.0.0-beta.100",
32
+ "@ai-sdk/provider": "4.0.0-beta.12",
33
+ "@ai-sdk/provider-utils": "5.0.0-beta.21"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@testing-library/jest-dom": "^6.6.3",
@@ -43,14 +43,12 @@
43
43
  "react-dom": "^18",
44
44
  "react": "^18",
45
45
  "react-server-dom-webpack": "18.3.0-canary-eb33bd747-20240312",
46
- "eslint": "8.57.1",
47
46
  "jsdom": "^24.0.0",
48
47
  "msw": "2.6.4",
49
48
  "tsup": "^7.2.0",
50
49
  "typescript": "5.8.3",
51
50
  "zod": "3.25.76",
52
- "@vercel/ai-tsconfig": "0.0.0",
53
- "eslint-config-vercel-ai": "0.0.0"
51
+ "@vercel/ai-tsconfig": "0.0.0"
54
52
  },
55
53
  "peerDependencies": {
56
54
  "react": "^18 || ~19.0.1 || ~19.1.2 || ^19.2.1",
@@ -85,9 +83,7 @@
85
83
  "build": "tsup --tsconfig tsconfig.build.json",
86
84
  "build:watch": "pnpm build --watch",
87
85
  "clean": "del-cli dist",
88
- "lint": "eslint \"./**/*.ts*\"",
89
86
  "type-check": "tsc --noEmit",
90
- "prettier-check": "prettier --check \"./**/*.ts*\"",
91
87
  "test:watch": "vitest --config vitest.config.js",
92
88
  "test": "pnpm test:node && pnpm test:ui && pnpm test:e2e && pnpm test:edge",
93
89
  "test:e2e": "playwright test",
@@ -1,8 +1,8 @@
1
1
  import {
2
- LanguageModelV3,
3
- LanguageModelV3StreamResult,
4
- LanguageModelV3Usage,
5
- SharedV3Warning,
2
+ LanguageModelV4,
3
+ LanguageModelV4StreamResult,
4
+ LanguageModelV4Usage,
5
+ SharedV4Warning,
6
6
  } from '@ai-sdk/provider';
7
7
  import {
8
8
  InferSchema,
@@ -10,22 +10,24 @@ import {
10
10
  safeParseJSON,
11
11
  } from '@ai-sdk/provider-utils';
12
12
  import {
13
- CallSettings,
14
13
  CallWarning,
15
14
  FinishReason,
16
15
  InvalidToolInputError,
17
16
  LanguageModelUsage,
17
+ LanguageModelCallOptions,
18
18
  NoSuchToolError,
19
19
  Prompt,
20
+ RequestOptions,
20
21
  Schema,
21
22
  ToolChoice,
22
23
  } from 'ai';
23
24
  import {
24
25
  asLanguageModelUsage,
25
26
  convertToLanguageModelPrompt,
26
- prepareCallSettings,
27
+ prepareLanguageModelCallOptions,
27
28
  prepareRetries,
28
- prepareToolsAndToolChoice,
29
+ prepareToolChoice,
30
+ prepareTools,
29
31
  standardizePrompt,
30
32
  } from 'ai/internal';
31
33
  import { ReactNode } from 'react';
@@ -85,7 +87,7 @@ type RenderText = Renderer<
85
87
 
86
88
  type RenderResult = {
87
89
  value: ReactNode;
88
- } & LanguageModelV3StreamResult;
90
+ } & LanguageModelV4StreamResult;
89
91
 
90
92
  const defaultTextRenderer: RenderText = ({ content }: { content: string }) =>
91
93
  content;
@@ -110,12 +112,13 @@ export async function streamUI<
110
112
  providerOptions,
111
113
  onFinish,
112
114
  ...settings
113
- }: CallSettings &
115
+ }: LanguageModelCallOptions &
116
+ Omit<RequestOptions, 'timeout'> &
114
117
  Prompt & {
115
118
  /**
116
119
  * The language model to use.
117
120
  */
118
- model: LanguageModelV3;
121
+ model: LanguageModelV4;
119
122
 
120
123
  /**
121
124
  * The tools that the model can call. The model needs to support calling tools.
@@ -206,7 +209,7 @@ export async function streamUI<
206
209
 
207
210
  let finishEvent: {
208
211
  finishReason: FinishReason;
209
- usage: LanguageModelV3Usage;
212
+ usage: LanguageModelV4Usage;
210
213
  warnings?: CallWarning[];
211
214
  response?: {
212
215
  headers?: Record<string, string>;
@@ -270,18 +273,23 @@ export async function streamUI<
270
273
  prompt,
271
274
  messages,
272
275
  } as Prompt);
276
+ const languageModelTools = await prepareTools({
277
+ tools: tools,
278
+ });
279
+ const languageModelToolChoice = prepareToolChoice({
280
+ toolChoice,
281
+ });
282
+
273
283
  const result = await retry(async () =>
274
284
  model.doStream({
275
- ...prepareCallSettings(settings),
276
- ...prepareToolsAndToolChoice({
277
- tools: tools as any,
278
- toolChoice,
279
- activeTools: undefined,
280
- }),
285
+ ...prepareLanguageModelCallOptions(settings),
286
+ tools: languageModelTools,
287
+ toolChoice: languageModelToolChoice,
281
288
  prompt: await convertToLanguageModelPrompt({
282
289
  prompt: validatedPrompt,
283
290
  supportedUrls: await model.supportedUrls,
284
291
  download: undefined,
292
+ provider: model.provider.split('.')[0],
285
293
  }),
286
294
  providerOptions,
287
295
  abortSignal,
@@ -296,7 +304,7 @@ export async function streamUI<
296
304
  try {
297
305
  let content = '';
298
306
  let hasToolCall = false;
299
- let warnings: SharedV3Warning[] | undefined;
307
+ let warnings: SharedV4Warning[] | undefined;
300
308
 
301
309
  const reader = forkedStream.getReader();
302
310
  while (true) {