ai 3.0.8 → 3.1.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +10 -4
  2. package/core/dist/index.d.mts +480 -0
  3. package/core/dist/index.d.ts +480 -0
  4. package/core/dist/index.js +1528 -0
  5. package/core/dist/index.js.map +1 -0
  6. package/core/dist/index.mjs +1479 -0
  7. package/core/dist/index.mjs.map +1 -0
  8. package/package.json +20 -3
  9. package/provider/dist/chunk-3DTRVHCT.mjs +5046 -0
  10. package/provider/dist/chunk-3DTRVHCT.mjs.map +1 -0
  11. package/provider/dist/chunk-4OUDS3CP.mjs +30 -0
  12. package/provider/dist/chunk-4OUDS3CP.mjs.map +1 -0
  13. package/provider/dist/chunk-5IYCPJBV.mjs +56 -0
  14. package/provider/dist/chunk-5IYCPJBV.mjs.map +1 -0
  15. package/provider/dist/chunk-VB2TCVQ4.mjs +6746 -0
  16. package/provider/dist/chunk-VB2TCVQ4.mjs.map +1 -0
  17. package/provider/dist/chunk-VYIXVZ6L.mjs +317 -0
  18. package/provider/dist/chunk-VYIXVZ6L.mjs.map +1 -0
  19. package/provider/dist/chunk-WTOUHN6A.mjs +2251 -0
  20. package/provider/dist/chunk-WTOUHN6A.mjs.map +1 -0
  21. package/provider/dist/client-22WAAXR7.mjs +10 -0
  22. package/provider/dist/client-22WAAXR7.mjs.map +1 -0
  23. package/provider/dist/fileFromPath-23RINPB2.mjs +115 -0
  24. package/provider/dist/fileFromPath-23RINPB2.mjs.map +1 -0
  25. package/provider/dist/index.d.mts +387 -0
  26. package/provider/dist/index.d.ts +387 -0
  27. package/provider/dist/index.js +26487 -0
  28. package/provider/dist/index.js.map +1 -0
  29. package/provider/dist/index.mjs +8087 -0
  30. package/provider/dist/index.mjs.map +1 -0
  31. package/provider/dist/lib-BZMMM4HX.mjs +20 -0
  32. package/provider/dist/lib-BZMMM4HX.mjs.map +1 -0
  33. package/provider/dist/openai-3YL4AWLI.mjs +3451 -0
  34. package/provider/dist/openai-3YL4AWLI.mjs.map +1 -0
  35. package/rsc/dist/index.d.ts +4 -3
  36. package/rsc/dist/rsc-server.d.mts +3 -2
  37. package/rsc/dist/rsc-server.mjs.map +1 -1
@@ -0,0 +1,1479 @@
1
+ // core/util/uint8-utils.ts
2
+ function convertBase64ToUint8Array(base64String) {
3
+ const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/");
4
+ const latin1string = globalThis.atob(base64Url);
5
+ return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0));
6
+ }
7
+ function convertUint8ArrayToBase64(array) {
8
+ let latin1string = "";
9
+ for (const value of array) {
10
+ latin1string += String.fromCodePoint(value);
11
+ }
12
+ return globalThis.btoa(latin1string);
13
+ }
14
+
15
+ // core/prompt/data-content.ts
16
+ function convertDataContentToBase64String(content) {
17
+ if (typeof content === "string") {
18
+ return content;
19
+ }
20
+ if (content instanceof ArrayBuffer) {
21
+ return convertUint8ArrayToBase64(new Uint8Array(content));
22
+ }
23
+ return convertUint8ArrayToBase64(content);
24
+ }
25
+ function convertDataContentToUint8Array(content) {
26
+ if (content instanceof Uint8Array) {
27
+ return content;
28
+ }
29
+ if (typeof content === "string") {
30
+ return convertBase64ToUint8Array(content);
31
+ }
32
+ if (content instanceof ArrayBuffer) {
33
+ return new Uint8Array(content);
34
+ }
35
+ throw new Error(
36
+ `Invalid data content. Expected a string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
37
+ );
38
+ }
39
+
40
+ // core/prompt/convert-to-language-model-prompt.ts
41
+ function convertToLanguageModelPrompt({
42
+ system,
43
+ prompt,
44
+ messages
45
+ }) {
46
+ if (prompt == null && messages == null) {
47
+ throw new Error("prompt or messages must be defined");
48
+ }
49
+ if (prompt != null && messages != null) {
50
+ throw new Error("prompt and messages cannot be defined at the same time");
51
+ }
52
+ const languageModelMessages = [];
53
+ if (system != null) {
54
+ languageModelMessages.push({ role: "system", content: system });
55
+ }
56
+ if (typeof prompt === "string") {
57
+ languageModelMessages.push({
58
+ role: "user",
59
+ content: [{ type: "text", text: prompt }]
60
+ });
61
+ } else {
62
+ messages = messages;
63
+ languageModelMessages.push(
64
+ ...messages.map((message) => {
65
+ switch (message.role) {
66
+ case "user": {
67
+ if (typeof message.content === "string") {
68
+ return {
69
+ role: "user",
70
+ content: [{ type: "text", text: message.content }]
71
+ };
72
+ }
73
+ return {
74
+ role: "user",
75
+ content: message.content.map(
76
+ (part) => {
77
+ switch (part.type) {
78
+ case "text": {
79
+ return part;
80
+ }
81
+ case "image": {
82
+ return {
83
+ type: "image",
84
+ image: convertDataContentToUint8Array(part.image),
85
+ mimeType: part.mimeType
86
+ };
87
+ }
88
+ }
89
+ }
90
+ )
91
+ };
92
+ }
93
+ case "assistant": {
94
+ if (typeof message.content === "string") {
95
+ return {
96
+ role: "assistant",
97
+ content: [{ type: "text", text: message.content }]
98
+ };
99
+ }
100
+ return { role: "assistant", content: message.content };
101
+ }
102
+ case "tool": {
103
+ return message;
104
+ }
105
+ }
106
+ })
107
+ );
108
+ }
109
+ return languageModelMessages;
110
+ }
111
+
112
+ // core/prompt/get-input-format.ts
113
+ function getInputFormat({
114
+ prompt,
115
+ messages
116
+ }) {
117
+ if (prompt == null && messages == null) {
118
+ throw new Error("prompt or messages must be defined");
119
+ }
120
+ if (prompt != null && messages != null) {
121
+ throw new Error("prompt and messages cannot be defined at the same time");
122
+ }
123
+ return prompt != null ? "prompt" : "messages";
124
+ }
125
+
126
+ // core/schema/parse-json.ts
127
+ import SecureJSON from "secure-json-parse";
128
+
129
+ // core/language-model/errors/get-error-message.ts
130
+ function getErrorMessage(error) {
131
+ if (error == null) {
132
+ return "unknown error";
133
+ }
134
+ if (typeof error === "string") {
135
+ return error;
136
+ }
137
+ if (error instanceof Error) {
138
+ return error.message;
139
+ }
140
+ return JSON.stringify(error);
141
+ }
142
+
143
+ // core/language-model/errors/json-parse-error.ts
144
+ var JSONParseError = class extends Error {
145
+ constructor({ text, cause }) {
146
+ super(
147
+ `JSON parsing failed: Text: ${text}.
148
+ Error message: ${getErrorMessage(cause)}`
149
+ );
150
+ this.name = "JSONParseError";
151
+ this.cause = cause;
152
+ this.text = text;
153
+ }
154
+ toJSON() {
155
+ return {
156
+ name: this.name,
157
+ message: this.message,
158
+ cause: this.cause,
159
+ stack: this.stack,
160
+ valueText: this.text
161
+ };
162
+ }
163
+ };
164
+
165
+ // core/language-model/errors/type-validation-error.ts
166
+ var TypeValidationError = class extends Error {
167
+ constructor({ value, cause }) {
168
+ super(
169
+ `Type validation failed: Value: ${JSON.stringify(value)}.
170
+ Error message: ${getErrorMessage(cause)}`
171
+ );
172
+ this.name = "TypeValidationError";
173
+ this.cause = cause;
174
+ this.value = value;
175
+ }
176
+ toJSON() {
177
+ return {
178
+ name: this.name,
179
+ message: this.message,
180
+ cause: this.cause,
181
+ stack: this.stack,
182
+ value: this.value
183
+ };
184
+ }
185
+ };
186
+
187
+ // core/schema/validate-types.ts
188
+ function safeValidateTypes({
189
+ value,
190
+ schema
191
+ }) {
192
+ try {
193
+ const validationResult = schema.validate(value);
194
+ if (validationResult.success) {
195
+ return validationResult;
196
+ }
197
+ return {
198
+ success: false,
199
+ error: new TypeValidationError({
200
+ value,
201
+ cause: validationResult.error
202
+ })
203
+ };
204
+ } catch (error) {
205
+ return {
206
+ success: false,
207
+ error: error instanceof TypeValidationError ? error : new TypeValidationError({ value, cause: error })
208
+ };
209
+ }
210
+ }
211
+
212
+ // core/schema/parse-json.ts
213
+ function safeParseJSON({
214
+ text,
215
+ schema
216
+ }) {
217
+ try {
218
+ const value = SecureJSON.parse(text);
219
+ if (schema == null) {
220
+ return {
221
+ success: true,
222
+ value
223
+ };
224
+ }
225
+ return safeValidateTypes({ value, schema });
226
+ } catch (error) {
227
+ return {
228
+ success: false,
229
+ error: error instanceof JSONParseError ? error : new JSONParseError({ text, cause: error })
230
+ };
231
+ }
232
+ }
233
+
234
+ // core/schema/zod-schema.ts
235
+ import { zodToJsonSchema } from "zod-to-json-schema";
236
+ var ZodSchema = class {
237
+ constructor(zodSchema) {
238
+ this.zodSchema = zodSchema;
239
+ }
240
+ validate(value) {
241
+ const result = this.zodSchema.safeParse(value);
242
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
243
+ }
244
+ getJsonSchema() {
245
+ return zodToJsonSchema(this.zodSchema);
246
+ }
247
+ };
248
+
249
+ // core/generate-object/inject-json-schema-into-system.ts
250
+ var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
251
+ var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
252
+ function injectJsonSchemaIntoSystem({
253
+ system,
254
+ schema,
255
+ schemaPrefix = DEFAULT_SCHEMA_PREFIX,
256
+ schemaSuffix = DEFAULT_SCHEMA_SUFFIX
257
+ }) {
258
+ return [
259
+ system,
260
+ system != null ? "" : null,
261
+ // add a newline if system is not null
262
+ schemaPrefix,
263
+ JSON.stringify(schema),
264
+ schemaSuffix
265
+ ].filter((line) => line != null).join("\n");
266
+ }
267
+
268
+ // core/language-model/errors/no-object-generated-error.ts
269
+ var NoTextGeneratedError = class extends Error {
270
+ constructor() {
271
+ super(`No text generated.`);
272
+ this.name = "NoTextGeneratedError";
273
+ }
274
+ toJSON() {
275
+ return {
276
+ name: this.name,
277
+ cause: this.cause,
278
+ message: this.message,
279
+ stack: this.stack
280
+ };
281
+ }
282
+ };
283
+
284
+ // core/generate-object/generate-object.ts
285
+ async function generateObject({
286
+ model,
287
+ schema: zodSchema,
288
+ mode,
289
+ system,
290
+ prompt,
291
+ messages,
292
+ ...settings
293
+ }) {
294
+ var _a, _b;
295
+ const schema = new ZodSchema(zodSchema);
296
+ const jsonSchema = schema.getJsonSchema();
297
+ let result;
298
+ mode = mode != null ? mode : model.defaultObjectGenerationMode;
299
+ switch (mode) {
300
+ case "json": {
301
+ const generateResult = await model.doGenerate({
302
+ mode: { type: "object-json" },
303
+ ...settings,
304
+ inputFormat: getInputFormat({ prompt, messages }),
305
+ prompt: convertToLanguageModelPrompt({
306
+ system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
307
+ prompt,
308
+ messages
309
+ })
310
+ });
311
+ if (generateResult.text === void 0) {
312
+ throw new NoTextGeneratedError();
313
+ }
314
+ result = generateResult.text;
315
+ break;
316
+ }
317
+ case "grammar": {
318
+ const generateResult = await model.doGenerate({
319
+ mode: { type: "object-grammar", schema: jsonSchema },
320
+ ...settings,
321
+ inputFormat: getInputFormat({ prompt, messages }),
322
+ prompt: convertToLanguageModelPrompt({
323
+ system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
324
+ prompt,
325
+ messages
326
+ })
327
+ });
328
+ if (generateResult.text === void 0) {
329
+ throw new NoTextGeneratedError();
330
+ }
331
+ result = generateResult.text;
332
+ break;
333
+ }
334
+ case "tool": {
335
+ const generateResult = await model.doGenerate({
336
+ mode: {
337
+ type: "object-tool",
338
+ tool: {
339
+ type: "function",
340
+ name: "json",
341
+ description: "Respond with a JSON object.",
342
+ parameters: jsonSchema
343
+ }
344
+ },
345
+ ...settings,
346
+ inputFormat: getInputFormat({ prompt, messages }),
347
+ prompt: convertToLanguageModelPrompt({ system, prompt, messages })
348
+ });
349
+ const functionArgs = (_b = (_a = generateResult.toolCalls) == null ? void 0 : _a[0]) == null ? void 0 : _b.args;
350
+ if (functionArgs === void 0) {
351
+ throw new NoTextGeneratedError();
352
+ }
353
+ result = functionArgs;
354
+ break;
355
+ }
356
+ case void 0: {
357
+ throw new Error("Model does not have a default object generation mode.");
358
+ }
359
+ default: {
360
+ const _exhaustiveCheck = mode;
361
+ throw new Error(`Unsupported mode: ${_exhaustiveCheck}`);
362
+ }
363
+ }
364
+ const parseResult = safeParseJSON({ text: result, schema });
365
+ if (!parseResult.success) {
366
+ throw parseResult.error;
367
+ }
368
+ return new GenerateObjectResult({
369
+ object: parseResult.value
370
+ });
371
+ }
372
+ var GenerateObjectResult = class {
373
+ constructor(options) {
374
+ this.object = options.object;
375
+ }
376
+ };
377
+
378
+ // core/util/is-deep-equal-data.ts
379
+ function isDeepEqualData(obj1, obj2) {
380
+ if (obj1 === obj2)
381
+ return true;
382
+ if (obj1 == null || obj2 == null)
383
+ return false;
384
+ if (typeof obj1 !== "object" && typeof obj2 !== "object")
385
+ return obj1 === obj2;
386
+ if (obj1.constructor !== obj2.constructor)
387
+ return false;
388
+ if (obj1 instanceof Date && obj2 instanceof Date) {
389
+ return obj1.getTime() === obj2.getTime();
390
+ }
391
+ if (Array.isArray(obj1)) {
392
+ if (obj1.length !== obj2.length)
393
+ return false;
394
+ for (let i = 0; i < obj1.length; i++) {
395
+ if (!isDeepEqualData(obj1[i], obj2[i]))
396
+ return false;
397
+ }
398
+ return true;
399
+ }
400
+ const keys1 = Object.keys(obj1);
401
+ const keys2 = Object.keys(obj2);
402
+ if (keys1.length !== keys2.length)
403
+ return false;
404
+ for (const key of keys1) {
405
+ if (!keys2.includes(key))
406
+ return false;
407
+ if (!isDeepEqualData(obj1[key], obj2[key]))
408
+ return false;
409
+ }
410
+ return true;
411
+ }
412
+
413
+ // core/util/parse-partial-json.ts
414
+ import SecureJSON2 from "secure-json-parse";
415
+
416
+ // core/util/fix-json.ts
417
+ function fixJson(input) {
418
+ const stack = ["ROOT"];
419
+ let lastValidIndex = -1;
420
+ let literalStart = null;
421
+ function processValueStart(char, i, swapState) {
422
+ {
423
+ switch (char) {
424
+ case '"': {
425
+ lastValidIndex = i;
426
+ stack.pop();
427
+ stack.push(swapState);
428
+ stack.push("INSIDE_STRING");
429
+ break;
430
+ }
431
+ case "f":
432
+ case "t":
433
+ case "n": {
434
+ lastValidIndex = i;
435
+ literalStart = i;
436
+ stack.pop();
437
+ stack.push(swapState);
438
+ stack.push("INSIDE_LITERAL");
439
+ break;
440
+ }
441
+ case "-": {
442
+ stack.pop();
443
+ stack.push(swapState);
444
+ stack.push("INSIDE_NUMBER");
445
+ break;
446
+ }
447
+ case "0":
448
+ case "1":
449
+ case "2":
450
+ case "3":
451
+ case "4":
452
+ case "5":
453
+ case "6":
454
+ case "7":
455
+ case "8":
456
+ case "9": {
457
+ lastValidIndex = i;
458
+ stack.pop();
459
+ stack.push(swapState);
460
+ stack.push("INSIDE_NUMBER");
461
+ break;
462
+ }
463
+ case "{": {
464
+ lastValidIndex = i;
465
+ stack.pop();
466
+ stack.push(swapState);
467
+ stack.push("INSIDE_OBJECT_START");
468
+ break;
469
+ }
470
+ case "[": {
471
+ lastValidIndex = i;
472
+ stack.pop();
473
+ stack.push(swapState);
474
+ stack.push("INSIDE_ARRAY_START");
475
+ break;
476
+ }
477
+ }
478
+ }
479
+ }
480
+ function processAfterObjectValue(char, i) {
481
+ switch (char) {
482
+ case ",": {
483
+ stack.pop();
484
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
485
+ break;
486
+ }
487
+ case "}": {
488
+ lastValidIndex = i;
489
+ stack.pop();
490
+ break;
491
+ }
492
+ }
493
+ }
494
+ function processAfterArrayValue(char, i) {
495
+ switch (char) {
496
+ case ",": {
497
+ stack.pop();
498
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
499
+ break;
500
+ }
501
+ case "]": {
502
+ lastValidIndex = i;
503
+ stack.pop();
504
+ break;
505
+ }
506
+ }
507
+ }
508
+ for (let i = 0; i < input.length; i++) {
509
+ const char = input[i];
510
+ const currentState = stack[stack.length - 1];
511
+ switch (currentState) {
512
+ case "ROOT":
513
+ processValueStart(char, i, "FINISH");
514
+ break;
515
+ case "INSIDE_OBJECT_START": {
516
+ switch (char) {
517
+ case '"': {
518
+ stack.pop();
519
+ stack.push("INSIDE_OBJECT_KEY");
520
+ break;
521
+ }
522
+ case "}": {
523
+ stack.pop();
524
+ break;
525
+ }
526
+ }
527
+ break;
528
+ }
529
+ case "INSIDE_OBJECT_AFTER_COMMA": {
530
+ switch (char) {
531
+ case '"': {
532
+ stack.pop();
533
+ stack.push("INSIDE_OBJECT_KEY");
534
+ break;
535
+ }
536
+ }
537
+ break;
538
+ }
539
+ case "INSIDE_OBJECT_KEY": {
540
+ switch (char) {
541
+ case '"': {
542
+ stack.pop();
543
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
544
+ break;
545
+ }
546
+ }
547
+ break;
548
+ }
549
+ case "INSIDE_OBJECT_AFTER_KEY": {
550
+ switch (char) {
551
+ case ":": {
552
+ stack.pop();
553
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
554
+ break;
555
+ }
556
+ }
557
+ break;
558
+ }
559
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
560
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
561
+ break;
562
+ }
563
+ case "INSIDE_OBJECT_AFTER_VALUE": {
564
+ processAfterObjectValue(char, i);
565
+ break;
566
+ }
567
+ case "INSIDE_STRING": {
568
+ switch (char) {
569
+ case '"': {
570
+ stack.pop();
571
+ lastValidIndex = i;
572
+ break;
573
+ }
574
+ case "\\": {
575
+ stack.push("INSIDE_STRING_ESCAPE");
576
+ break;
577
+ }
578
+ default: {
579
+ lastValidIndex = i;
580
+ }
581
+ }
582
+ break;
583
+ }
584
+ case "INSIDE_ARRAY_START": {
585
+ switch (char) {
586
+ case "]": {
587
+ lastValidIndex = i;
588
+ stack.pop();
589
+ break;
590
+ }
591
+ default: {
592
+ lastValidIndex = i;
593
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
594
+ break;
595
+ }
596
+ }
597
+ break;
598
+ }
599
+ case "INSIDE_ARRAY_AFTER_VALUE": {
600
+ switch (char) {
601
+ case ",": {
602
+ stack.pop();
603
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
604
+ break;
605
+ }
606
+ case "]": {
607
+ lastValidIndex = i;
608
+ stack.pop();
609
+ break;
610
+ }
611
+ default: {
612
+ lastValidIndex = i;
613
+ break;
614
+ }
615
+ }
616
+ break;
617
+ }
618
+ case "INSIDE_ARRAY_AFTER_COMMA": {
619
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
620
+ break;
621
+ }
622
+ case "INSIDE_STRING_ESCAPE": {
623
+ stack.pop();
624
+ lastValidIndex = i;
625
+ break;
626
+ }
627
+ case "INSIDE_NUMBER": {
628
+ switch (char) {
629
+ case "0":
630
+ case "1":
631
+ case "2":
632
+ case "3":
633
+ case "4":
634
+ case "5":
635
+ case "6":
636
+ case "7":
637
+ case "8":
638
+ case "9": {
639
+ lastValidIndex = i;
640
+ break;
641
+ }
642
+ case "e":
643
+ case "E":
644
+ case "-":
645
+ case ".": {
646
+ break;
647
+ }
648
+ case ",": {
649
+ stack.pop();
650
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
651
+ processAfterArrayValue(char, i);
652
+ }
653
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
654
+ processAfterObjectValue(char, i);
655
+ }
656
+ break;
657
+ }
658
+ case "}": {
659
+ stack.pop();
660
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
661
+ processAfterObjectValue(char, i);
662
+ }
663
+ break;
664
+ }
665
+ case "]": {
666
+ stack.pop();
667
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
668
+ processAfterArrayValue(char, i);
669
+ }
670
+ break;
671
+ }
672
+ default: {
673
+ stack.pop();
674
+ break;
675
+ }
676
+ }
677
+ break;
678
+ }
679
+ case "INSIDE_LITERAL": {
680
+ const partialLiteral = input.substring(literalStart, i + 1);
681
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
682
+ stack.pop();
683
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
684
+ processAfterObjectValue(char, i);
685
+ } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
686
+ processAfterArrayValue(char, i);
687
+ }
688
+ } else {
689
+ lastValidIndex = i;
690
+ }
691
+ break;
692
+ }
693
+ }
694
+ }
695
+ let result = input.slice(0, lastValidIndex + 1);
696
+ for (let i = stack.length - 1; i >= 0; i--) {
697
+ const state = stack[i];
698
+ switch (state) {
699
+ case "INSIDE_STRING": {
700
+ result += '"';
701
+ break;
702
+ }
703
+ case "INSIDE_OBJECT_KEY":
704
+ case "INSIDE_OBJECT_AFTER_KEY":
705
+ case "INSIDE_OBJECT_AFTER_COMMA":
706
+ case "INSIDE_OBJECT_START":
707
+ case "INSIDE_OBJECT_BEFORE_VALUE":
708
+ case "INSIDE_OBJECT_AFTER_VALUE": {
709
+ result += "}";
710
+ break;
711
+ }
712
+ case "INSIDE_ARRAY_START":
713
+ case "INSIDE_ARRAY_AFTER_COMMA":
714
+ case "INSIDE_ARRAY_AFTER_VALUE": {
715
+ result += "]";
716
+ break;
717
+ }
718
+ case "INSIDE_LITERAL": {
719
+ const partialLiteral = input.substring(literalStart, input.length);
720
+ if ("true".startsWith(partialLiteral)) {
721
+ result += "true".slice(partialLiteral.length);
722
+ } else if ("false".startsWith(partialLiteral)) {
723
+ result += "false".slice(partialLiteral.length);
724
+ } else if ("null".startsWith(partialLiteral)) {
725
+ result += "null".slice(partialLiteral.length);
726
+ }
727
+ }
728
+ }
729
+ }
730
+ return result;
731
+ }
732
+
733
+ // core/util/parse-partial-json.ts
734
+ function parsePartialJson(jsonText) {
735
+ if (jsonText == null) {
736
+ return void 0;
737
+ }
738
+ try {
739
+ return SecureJSON2.parse(jsonText);
740
+ } catch (ignored) {
741
+ try {
742
+ const fixedJsonText = fixJson(jsonText);
743
+ return SecureJSON2.parse(fixedJsonText);
744
+ } catch (ignored2) {
745
+ }
746
+ }
747
+ return void 0;
748
+ }
749
+
750
+ // core/generate-object/stream-object.ts
751
+ async function streamObject({
752
+ model,
753
+ schema: zodSchema,
754
+ mode,
755
+ system,
756
+ prompt,
757
+ messages,
758
+ ...settings
759
+ }) {
760
+ const schema = new ZodSchema(zodSchema);
761
+ const jsonSchema = schema.getJsonSchema();
762
+ let modelStream;
763
+ mode = mode != null ? mode : model.defaultObjectGenerationMode;
764
+ switch (mode) {
765
+ case "json": {
766
+ const { stream, warnings } = await model.doStream({
767
+ mode: { type: "object-json" },
768
+ ...settings,
769
+ inputFormat: getInputFormat({ prompt, messages }),
770
+ prompt: convertToLanguageModelPrompt({
771
+ system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
772
+ prompt,
773
+ messages
774
+ })
775
+ });
776
+ modelStream = stream.pipeThrough(
777
+ new TransformStream({
778
+ transform(chunk, controller) {
779
+ switch (chunk.type) {
780
+ case "text-delta":
781
+ controller.enqueue(chunk.textDelta);
782
+ break;
783
+ case "error":
784
+ controller.enqueue(chunk);
785
+ break;
786
+ }
787
+ }
788
+ })
789
+ );
790
+ break;
791
+ }
792
+ case "grammar": {
793
+ const { stream, warnings } = await model.doStream({
794
+ mode: { type: "object-grammar", schema: jsonSchema },
795
+ ...settings,
796
+ inputFormat: getInputFormat({ prompt, messages }),
797
+ prompt: convertToLanguageModelPrompt({
798
+ system: injectJsonSchemaIntoSystem({ system, schema: jsonSchema }),
799
+ prompt,
800
+ messages
801
+ })
802
+ });
803
+ modelStream = stream.pipeThrough(
804
+ new TransformStream({
805
+ transform(chunk, controller) {
806
+ switch (chunk.type) {
807
+ case "text-delta":
808
+ controller.enqueue(chunk.textDelta);
809
+ break;
810
+ case "error":
811
+ controller.enqueue(chunk);
812
+ break;
813
+ }
814
+ }
815
+ })
816
+ );
817
+ break;
818
+ }
819
+ case "tool": {
820
+ const { stream, warnings } = await model.doStream({
821
+ mode: {
822
+ type: "object-tool",
823
+ tool: {
824
+ type: "function",
825
+ name: "json",
826
+ description: "Respond with a JSON object.",
827
+ parameters: jsonSchema
828
+ }
829
+ },
830
+ ...settings,
831
+ inputFormat: getInputFormat({ prompt, messages }),
832
+ prompt: convertToLanguageModelPrompt({ system, prompt, messages })
833
+ });
834
+ modelStream = stream.pipeThrough(
835
+ new TransformStream({
836
+ transform(chunk, controller) {
837
+ switch (chunk.type) {
838
+ case "tool-call-delta":
839
+ controller.enqueue(chunk.argsTextDelta);
840
+ break;
841
+ case "error":
842
+ controller.enqueue(chunk);
843
+ break;
844
+ }
845
+ }
846
+ })
847
+ );
848
+ break;
849
+ }
850
+ case void 0: {
851
+ throw new Error("Model does not have a default object generation mode.");
852
+ }
853
+ default: {
854
+ const _exhaustiveCheck = mode;
855
+ throw new Error(`Unsupported mode: ${_exhaustiveCheck}`);
856
+ }
857
+ }
858
+ return new StreamObjectResult(modelStream);
859
+ }
860
+ var StreamObjectResult = class {
861
+ constructor(modelStream) {
862
+ let accumulatedText = "";
863
+ let latestObject = void 0;
864
+ this.objectStream = {
865
+ [Symbol.asyncIterator]() {
866
+ const reader = modelStream.getReader();
867
+ return {
868
+ next: async () => {
869
+ while (true) {
870
+ const { done, value } = await reader.read();
871
+ if (done) {
872
+ return { value: null, done: true };
873
+ }
874
+ if (typeof value === "string") {
875
+ accumulatedText += value;
876
+ const currentObject = parsePartialJson(
877
+ accumulatedText
878
+ );
879
+ if (!isDeepEqualData(latestObject, currentObject)) {
880
+ latestObject = currentObject;
881
+ return { value: currentObject, done: false };
882
+ }
883
+ }
884
+ }
885
+ }
886
+ };
887
+ }
888
+ };
889
+ }
890
+ };
891
+
892
+ // core/generate-text/generate-text.ts
893
+ import zodToJsonSchema2 from "zod-to-json-schema";
894
+
895
+ // core/generate-text/tool-call.ts
896
+ function parseToolCall({
897
+ toolCall,
898
+ tools
899
+ }) {
900
+ const toolName = toolCall.toolName;
901
+ if (tools == null) {
902
+ throw new Error(`Tool not found: ${toolName}`);
903
+ }
904
+ const tool2 = tools[toolName];
905
+ if (tool2 == null) {
906
+ throw new Error(`Tool not found: ${toolName}`);
907
+ }
908
+ const parseResult = safeParseJSON({
909
+ text: toolCall.args,
910
+ schema: new ZodSchema(tool2.parameters)
911
+ });
912
+ if (parseResult.success === false) {
913
+ throw new Error(
914
+ `Tool call ${toolName} has invalid arguments: ${parseResult.error}`
915
+ );
916
+ }
917
+ const toolArgs = parseResult.value;
918
+ return {
919
+ toolCallId: toolCall.toolCallId,
920
+ toolName,
921
+ args: toolArgs
922
+ };
923
+ }
924
+
925
+ // core/generate-text/generate-text.ts
926
+ async function generateText({
927
+ model,
928
+ tools,
929
+ system,
930
+ prompt,
931
+ messages,
932
+ ...settings
933
+ }) {
934
+ var _a, _b;
935
+ const modelResponse = await model.doGenerate({
936
+ mode: {
937
+ type: "regular",
938
+ tools: tools == null ? void 0 : Object.entries(tools).map(([name, tool2]) => ({
939
+ type: "function",
940
+ name,
941
+ description: tool2.description,
942
+ parameters: zodToJsonSchema2(tool2.parameters)
943
+ }))
944
+ },
945
+ ...settings,
946
+ inputFormat: getInputFormat({ prompt, messages }),
947
+ prompt: convertToLanguageModelPrompt({
948
+ system,
949
+ prompt,
950
+ messages
951
+ })
952
+ });
953
+ const toolCalls = [];
954
+ for (const modelToolCall of (_a = modelResponse.toolCalls) != null ? _a : []) {
955
+ toolCalls.push(parseToolCall({ toolCall: modelToolCall, tools }));
956
+ }
957
+ const toolResults = tools == null ? [] : await executeTools({ toolCalls, tools });
958
+ return new GenerateTextResult({
959
+ // Always return a string so that the caller doesn't have to check for undefined.
960
+ // If they need to check if the model did not return any text,
961
+ // they can check the length of the string:
962
+ text: (_b = modelResponse.text) != null ? _b : "",
963
+ toolCalls,
964
+ toolResults
965
+ });
966
+ }
967
+ async function executeTools({
968
+ toolCalls,
969
+ tools
970
+ }) {
971
+ const toolResults = await Promise.all(
972
+ toolCalls.map(async (toolCall) => {
973
+ const tool2 = tools[toolCall.toolName];
974
+ if ((tool2 == null ? void 0 : tool2.execute) == null) {
975
+ return void 0;
976
+ }
977
+ const result = await tool2.execute(toolCall.args);
978
+ return {
979
+ toolCallId: toolCall.toolCallId,
980
+ toolName: toolCall.toolName,
981
+ args: toolCall.args,
982
+ result
983
+ };
984
+ })
985
+ );
986
+ return toolResults.filter(
987
+ (result) => result != null
988
+ );
989
+ }
990
+ var GenerateTextResult = class {
991
+ constructor(options) {
992
+ this.text = options.text;
993
+ this.toolCalls = options.toolCalls;
994
+ this.toolResults = options.toolResults;
995
+ }
996
+ };
997
+
998
+ // core/generate-text/stream-text.ts
999
+ import zodToJsonSchema3 from "zod-to-json-schema";
1000
+
1001
+ // core/generate-text/run-tools-transformation.ts
1002
+ import { nanoid } from "nanoid";
1003
+ function runToolsTransformation({
1004
+ tools,
1005
+ generatorStream
1006
+ }) {
1007
+ let canClose = false;
1008
+ const outstandingToolCalls = /* @__PURE__ */ new Set();
1009
+ let toolResultsStreamController = null;
1010
+ const toolResultsStream = new ReadableStream({
1011
+ start(controller) {
1012
+ toolResultsStreamController = controller;
1013
+ }
1014
+ });
1015
+ const forwardStream = new TransformStream({
1016
+ transform(chunk, controller) {
1017
+ const chunkType = chunk.type;
1018
+ switch (chunkType) {
1019
+ case "text-delta":
1020
+ case "error": {
1021
+ controller.enqueue(chunk);
1022
+ break;
1023
+ }
1024
+ case "tool-call": {
1025
+ const toolName = chunk.toolName;
1026
+ if (tools == null) {
1027
+ toolResultsStreamController.enqueue({
1028
+ type: "error",
1029
+ error: `Tool ${chunk.toolName} not found (no tools provided)`
1030
+ });
1031
+ break;
1032
+ }
1033
+ const tool2 = tools[toolName];
1034
+ if (tool2 == null) {
1035
+ toolResultsStreamController.enqueue({
1036
+ type: "error",
1037
+ error: `Tool ${chunk.toolName} not found`
1038
+ });
1039
+ break;
1040
+ }
1041
+ const toolCall = parseToolCall({
1042
+ toolCall: chunk,
1043
+ tools
1044
+ });
1045
+ controller.enqueue({
1046
+ type: "tool-call",
1047
+ ...toolCall
1048
+ });
1049
+ if (tool2.execute != null) {
1050
+ const toolExecutionId = nanoid();
1051
+ outstandingToolCalls.add(toolExecutionId);
1052
+ tool2.execute(toolCall.args).then(
1053
+ (result) => {
1054
+ toolResultsStreamController.enqueue({
1055
+ type: "tool-result",
1056
+ ...toolCall,
1057
+ result
1058
+ });
1059
+ outstandingToolCalls.delete(toolExecutionId);
1060
+ if (canClose && outstandingToolCalls.size === 0) {
1061
+ toolResultsStreamController.close();
1062
+ }
1063
+ },
1064
+ (error) => {
1065
+ toolResultsStreamController.enqueue({
1066
+ type: "error",
1067
+ error
1068
+ });
1069
+ outstandingToolCalls.delete(toolExecutionId);
1070
+ if (canClose && outstandingToolCalls.size === 0) {
1071
+ toolResultsStreamController.close();
1072
+ }
1073
+ }
1074
+ );
1075
+ }
1076
+ break;
1077
+ }
1078
+ case "tool-call-delta": {
1079
+ break;
1080
+ }
1081
+ default: {
1082
+ const _exhaustiveCheck = chunkType;
1083
+ throw new Error(`Unhandled chunk type: ${_exhaustiveCheck}`);
1084
+ }
1085
+ }
1086
+ },
1087
+ flush() {
1088
+ canClose = true;
1089
+ if (outstandingToolCalls.size === 0) {
1090
+ toolResultsStreamController.close();
1091
+ }
1092
+ }
1093
+ });
1094
+ return new ReadableStream({
1095
+ async start(controller) {
1096
+ generatorStream.pipeThrough(forwardStream).pipeTo(
1097
+ new WritableStream({
1098
+ write(chunk) {
1099
+ controller.enqueue(chunk);
1100
+ },
1101
+ close() {
1102
+ }
1103
+ })
1104
+ );
1105
+ toolResultsStream.pipeTo(
1106
+ new WritableStream({
1107
+ write(chunk) {
1108
+ controller.enqueue(chunk);
1109
+ },
1110
+ close() {
1111
+ controller.close();
1112
+ }
1113
+ })
1114
+ );
1115
+ }
1116
+ });
1117
+ }
1118
+
1119
+ // shared/stream-parts.ts
1120
+ var textStreamPart = {
1121
+ code: "0",
1122
+ name: "text",
1123
+ parse: (value) => {
1124
+ if (typeof value !== "string") {
1125
+ throw new Error('"text" parts expect a string value.');
1126
+ }
1127
+ return { type: "text", value };
1128
+ }
1129
+ };
1130
+ var functionCallStreamPart = {
1131
+ code: "1",
1132
+ name: "function_call",
1133
+ parse: (value) => {
1134
+ if (value == null || typeof value !== "object" || !("function_call" in value) || typeof value.function_call !== "object" || value.function_call == null || !("name" in value.function_call) || !("arguments" in value.function_call) || typeof value.function_call.name !== "string" || typeof value.function_call.arguments !== "string") {
1135
+ throw new Error(
1136
+ '"function_call" parts expect an object with a "function_call" property.'
1137
+ );
1138
+ }
1139
+ return {
1140
+ type: "function_call",
1141
+ value
1142
+ };
1143
+ }
1144
+ };
1145
+ var dataStreamPart = {
1146
+ code: "2",
1147
+ name: "data",
1148
+ parse: (value) => {
1149
+ if (!Array.isArray(value)) {
1150
+ throw new Error('"data" parts expect an array value.');
1151
+ }
1152
+ return { type: "data", value };
1153
+ }
1154
+ };
1155
+ var errorStreamPart = {
1156
+ code: "3",
1157
+ name: "error",
1158
+ parse: (value) => {
1159
+ if (typeof value !== "string") {
1160
+ throw new Error('"error" parts expect a string value.');
1161
+ }
1162
+ return { type: "error", value };
1163
+ }
1164
+ };
1165
+ var assistantMessageStreamPart = {
1166
+ code: "4",
1167
+ name: "assistant_message",
1168
+ parse: (value) => {
1169
+ if (value == null || typeof value !== "object" || !("id" in value) || !("role" in value) || !("content" in value) || typeof value.id !== "string" || typeof value.role !== "string" || value.role !== "assistant" || !Array.isArray(value.content) || !value.content.every(
1170
+ (item) => item != null && typeof item === "object" && "type" in item && item.type === "text" && "text" in item && item.text != null && typeof item.text === "object" && "value" in item.text && typeof item.text.value === "string"
1171
+ )) {
1172
+ throw new Error(
1173
+ '"assistant_message" parts expect an object with an "id", "role", and "content" property.'
1174
+ );
1175
+ }
1176
+ return {
1177
+ type: "assistant_message",
1178
+ value
1179
+ };
1180
+ }
1181
+ };
1182
+ var assistantControlDataStreamPart = {
1183
+ code: "5",
1184
+ name: "assistant_control_data",
1185
+ parse: (value) => {
1186
+ if (value == null || typeof value !== "object" || !("threadId" in value) || !("messageId" in value) || typeof value.threadId !== "string" || typeof value.messageId !== "string") {
1187
+ throw new Error(
1188
+ '"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
1189
+ );
1190
+ }
1191
+ return {
1192
+ type: "assistant_control_data",
1193
+ value: {
1194
+ threadId: value.threadId,
1195
+ messageId: value.messageId
1196
+ }
1197
+ };
1198
+ }
1199
+ };
1200
+ var dataMessageStreamPart = {
1201
+ code: "6",
1202
+ name: "data_message",
1203
+ parse: (value) => {
1204
+ if (value == null || typeof value !== "object" || !("role" in value) || !("data" in value) || typeof value.role !== "string" || value.role !== "data") {
1205
+ throw new Error(
1206
+ '"data_message" parts expect an object with a "role" and "data" property.'
1207
+ );
1208
+ }
1209
+ return {
1210
+ type: "data_message",
1211
+ value
1212
+ };
1213
+ }
1214
+ };
1215
+ var toolCallStreamPart = {
1216
+ code: "7",
1217
+ name: "tool_calls",
1218
+ parse: (value) => {
1219
+ if (value == null || typeof value !== "object" || !("tool_calls" in value) || typeof value.tool_calls !== "object" || value.tool_calls == null || !Array.isArray(value.tool_calls) || value.tool_calls.some((tc) => {
1220
+ tc == null || typeof tc !== "object" || !("id" in tc) || typeof tc.id !== "string" || !("type" in tc) || typeof tc.type !== "string" || !("function" in tc) || tc.function == null || typeof tc.function !== "object" || !("arguments" in tc.function) || typeof tc.function.name !== "string" || typeof tc.function.arguments !== "string";
1221
+ })) {
1222
+ throw new Error(
1223
+ '"tool_calls" parts expect an object with a ToolCallPayload.'
1224
+ );
1225
+ }
1226
+ return {
1227
+ type: "tool_calls",
1228
+ value
1229
+ };
1230
+ }
1231
+ };
1232
+ var messageAnnotationsStreamPart = {
1233
+ code: "8",
1234
+ name: "message_annotations",
1235
+ parse: (value) => {
1236
+ if (!Array.isArray(value)) {
1237
+ throw new Error('"message_annotations" parts expect an array value.');
1238
+ }
1239
+ return { type: "message_annotations", value };
1240
+ }
1241
+ };
1242
+ var streamParts = [
1243
+ textStreamPart,
1244
+ functionCallStreamPart,
1245
+ dataStreamPart,
1246
+ errorStreamPart,
1247
+ assistantMessageStreamPart,
1248
+ assistantControlDataStreamPart,
1249
+ dataMessageStreamPart,
1250
+ toolCallStreamPart,
1251
+ messageAnnotationsStreamPart
1252
+ ];
1253
+ var streamPartsByCode = {
1254
+ [textStreamPart.code]: textStreamPart,
1255
+ [functionCallStreamPart.code]: functionCallStreamPart,
1256
+ [dataStreamPart.code]: dataStreamPart,
1257
+ [errorStreamPart.code]: errorStreamPart,
1258
+ [assistantMessageStreamPart.code]: assistantMessageStreamPart,
1259
+ [assistantControlDataStreamPart.code]: assistantControlDataStreamPart,
1260
+ [dataMessageStreamPart.code]: dataMessageStreamPart,
1261
+ [toolCallStreamPart.code]: toolCallStreamPart,
1262
+ [messageAnnotationsStreamPart.code]: messageAnnotationsStreamPart
1263
+ };
1264
+ var StreamStringPrefixes = {
1265
+ [textStreamPart.name]: textStreamPart.code,
1266
+ [functionCallStreamPart.name]: functionCallStreamPart.code,
1267
+ [dataStreamPart.name]: dataStreamPart.code,
1268
+ [errorStreamPart.name]: errorStreamPart.code,
1269
+ [assistantMessageStreamPart.name]: assistantMessageStreamPart.code,
1270
+ [assistantControlDataStreamPart.name]: assistantControlDataStreamPart.code,
1271
+ [dataMessageStreamPart.name]: dataMessageStreamPart.code,
1272
+ [toolCallStreamPart.name]: toolCallStreamPart.code,
1273
+ [messageAnnotationsStreamPart.name]: messageAnnotationsStreamPart.code
1274
+ };
1275
+ var validCodes = streamParts.map((part) => part.code);
1276
+ function formatStreamPart(type, value) {
1277
+ const streamPart = streamParts.find((part) => part.name === type);
1278
+ if (!streamPart) {
1279
+ throw new Error(`Invalid stream part type: ${type}`);
1280
+ }
1281
+ return `${streamPart.code}:${JSON.stringify(value)}
1282
+ `;
1283
+ }
1284
+
1285
+ // shared/utils.ts
1286
+ import { customAlphabet } from "nanoid/non-secure";
1287
+ var nanoid2 = customAlphabet(
1288
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
1289
+ 7
1290
+ );
1291
+ var COMPLEX_HEADER = "X-Experimental-Stream-Data";
1292
+
1293
+ // core/generate-text/stream-text-http-response.ts
1294
+ var StreamTextHttpResponse = class extends Response {
1295
+ constructor(messageStream) {
1296
+ super(
1297
+ messageStream.pipeThrough(
1298
+ new TransformStream({
1299
+ transform(chunk, controller) {
1300
+ var _a;
1301
+ switch (chunk.type) {
1302
+ case "error": {
1303
+ break;
1304
+ }
1305
+ case "text-delta": {
1306
+ controller.enqueue(formatStreamPart("text", chunk.textDelta));
1307
+ break;
1308
+ }
1309
+ case "tool-call": {
1310
+ controller.enqueue(
1311
+ formatStreamPart("tool_calls", {
1312
+ tool_calls: [
1313
+ {
1314
+ type: "function",
1315
+ id: (_a = chunk.toolCallId) != null ? _a : "",
1316
+ // TODO client need to support null id
1317
+ function: {
1318
+ name: chunk.toolName,
1319
+ arguments: JSON.stringify(chunk.args)
1320
+ }
1321
+ }
1322
+ ]
1323
+ })
1324
+ );
1325
+ break;
1326
+ }
1327
+ case "tool-result": {
1328
+ break;
1329
+ }
1330
+ default: {
1331
+ const exhaustiveCheck = chunk;
1332
+ throw new Error(
1333
+ `Unhandled stream part type: ${exhaustiveCheck}`
1334
+ );
1335
+ }
1336
+ }
1337
+ }
1338
+ })
1339
+ ),
1340
+ {
1341
+ status: 200,
1342
+ headers: {
1343
+ "Content-Type": "text/plain; charset=utf-8",
1344
+ [COMPLEX_HEADER]: "true"
1345
+ }
1346
+ }
1347
+ );
1348
+ }
1349
+ };
1350
+
1351
+ // core/generate-text/stream-text.ts
1352
+ async function streamText({
1353
+ model,
1354
+ tools,
1355
+ system,
1356
+ prompt,
1357
+ messages,
1358
+ ...settings
1359
+ }) {
1360
+ const { stream, warnings } = await model.doStream({
1361
+ mode: {
1362
+ type: "regular",
1363
+ tools: tools == null ? void 0 : Object.entries(tools).map(([name, tool2]) => ({
1364
+ type: "function",
1365
+ name,
1366
+ description: tool2.description,
1367
+ parameters: zodToJsonSchema3(tool2.parameters)
1368
+ }))
1369
+ },
1370
+ ...settings,
1371
+ inputFormat: getInputFormat({ prompt, messages }),
1372
+ prompt: convertToLanguageModelPrompt({
1373
+ system,
1374
+ prompt,
1375
+ messages
1376
+ })
1377
+ });
1378
+ const toolStream = runToolsTransformation({
1379
+ tools,
1380
+ generatorStream: stream
1381
+ });
1382
+ return new StreamTextResult(toolStream);
1383
+ }
1384
+ var StreamTextResult = class {
1385
+ constructor(stream) {
1386
+ this.rootStream = stream;
1387
+ this.textStream = {
1388
+ [Symbol.asyncIterator]() {
1389
+ const reader = stream.getReader();
1390
+ return {
1391
+ next: async () => {
1392
+ while (true) {
1393
+ const { done, value } = await reader.read();
1394
+ if (done) {
1395
+ return { value: null, done: true };
1396
+ }
1397
+ if (value.type === "text-delta") {
1398
+ if (value.textDelta.length > 0) {
1399
+ return { value: value.textDelta, done: false };
1400
+ }
1401
+ }
1402
+ }
1403
+ }
1404
+ };
1405
+ }
1406
+ };
1407
+ this.fullStream = {
1408
+ [Symbol.asyncIterator]() {
1409
+ const reader = stream.getReader();
1410
+ return {
1411
+ next: async () => {
1412
+ while (true) {
1413
+ const { done, value } = await reader.read();
1414
+ if (done) {
1415
+ return { value: null, done: true };
1416
+ }
1417
+ if (value.type === "text-delta") {
1418
+ if (value.textDelta.length > 0) {
1419
+ return { value, done: false };
1420
+ }
1421
+ } else {
1422
+ return { value, done: false };
1423
+ }
1424
+ }
1425
+ }
1426
+ };
1427
+ }
1428
+ };
1429
+ }
1430
+ toResponse() {
1431
+ return new StreamTextHttpResponse(this.rootStream);
1432
+ }
1433
+ };
1434
+
1435
+ // core/tool/tool.ts
1436
+ function tool(tool2) {
1437
+ return tool2;
1438
+ }
1439
+
1440
+ // core/language-model/errors/unsupported-functionality-error.ts
1441
+ var UnsupportedFunctionalityError = class extends Error {
1442
+ constructor({
1443
+ provider,
1444
+ functionality
1445
+ }) {
1446
+ super(
1447
+ `Functionality not supported by the provider. Provider: ${provider}.
1448
+ Functionality: ${functionality}`
1449
+ );
1450
+ this.name = "UnsupportedFunctionalityError";
1451
+ this.provider = provider;
1452
+ this.functionality = functionality;
1453
+ }
1454
+ toJSON() {
1455
+ return {
1456
+ name: this.name,
1457
+ message: this.message,
1458
+ stack: this.stack,
1459
+ provider: this.provider,
1460
+ functionality: this.functionality
1461
+ };
1462
+ }
1463
+ };
1464
+ export {
1465
+ GenerateObjectResult,
1466
+ GenerateTextResult,
1467
+ StreamObjectResult,
1468
+ StreamTextHttpResponse,
1469
+ StreamTextResult,
1470
+ UnsupportedFunctionalityError,
1471
+ convertDataContentToBase64String,
1472
+ convertDataContentToUint8Array,
1473
+ generateObject,
1474
+ generateText,
1475
+ streamObject,
1476
+ streamText,
1477
+ tool
1478
+ };
1479
+ //# sourceMappingURL=index.mjs.map