ai 3.0.9 → 3.1.0-canary.1

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