@mastra/ai-sdk 0.0.0-feat-improve-processors-20251205191721 → 0.0.0-feat-mcp-embedded-docs-tools-clean-20260102135536

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 (46) hide show
  1. package/CHANGELOG.md +425 -8
  2. package/dist/_types/@ai-sdk_provider/dist/index.d.ts +1719 -0
  3. package/dist/chat-route.d.ts +16 -11
  4. package/dist/chat-route.d.ts.map +1 -1
  5. package/dist/chunk-AAQDCHJY.js +293 -0
  6. package/dist/chunk-AAQDCHJY.js.map +1 -0
  7. package/dist/chunk-CCJXHQQO.cjs +296 -0
  8. package/dist/chunk-CCJXHQQO.cjs.map +1 -0
  9. package/dist/chunk-DES3K4SD.cjs +17 -0
  10. package/dist/chunk-DES3K4SD.cjs.map +1 -0
  11. package/dist/chunk-VUNV25KB.js +14 -0
  12. package/dist/chunk-VUNV25KB.js.map +1 -0
  13. package/dist/convert-messages.d.ts +83 -3
  14. package/dist/convert-messages.d.ts.map +1 -1
  15. package/dist/convert-streams.d.ts +1 -2
  16. package/dist/convert-streams.d.ts.map +1 -1
  17. package/dist/helpers.d.ts +8 -2
  18. package/dist/helpers.d.ts.map +1 -1
  19. package/dist/index.cjs +3396 -58
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.ts +2 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +3372 -54
  24. package/dist/index.js.map +1 -1
  25. package/dist/middleware.d.ts +157 -0
  26. package/dist/middleware.d.ts.map +1 -0
  27. package/dist/network-route.d.ts +41 -8
  28. package/dist/network-route.d.ts.map +1 -1
  29. package/dist/token-36YTPVWD.cjs +63 -0
  30. package/dist/token-36YTPVWD.cjs.map +1 -0
  31. package/dist/token-ZFKXETJY.js +61 -0
  32. package/dist/token-ZFKXETJY.js.map +1 -0
  33. package/dist/token-util-737PGIQA.cjs +9 -0
  34. package/dist/token-util-737PGIQA.cjs.map +1 -0
  35. package/dist/token-util-SD2EI4DD.js +7 -0
  36. package/dist/token-util-SD2EI4DD.js.map +1 -0
  37. package/dist/transformers.d.ts +9 -7
  38. package/dist/transformers.d.ts.map +1 -1
  39. package/dist/ui.cjs +0 -1
  40. package/dist/ui.cjs.map +1 -1
  41. package/dist/ui.js +0 -1
  42. package/dist/ui.js.map +1 -1
  43. package/dist/utils.d.ts.map +1 -1
  44. package/dist/workflow-route.d.ts +34 -4
  45. package/dist/workflow-route.d.ts.map +1 -1
  46. package/package.json +8 -8
package/dist/index.cjs CHANGED
@@ -1,10 +1,2823 @@
1
1
  'use strict';
2
2
 
3
3
  var server = require('@mastra/core/server');
4
- var ai = require('ai');
4
+ var z4 = require('zod/v4');
5
+ var v3 = require('zod/v3');
5
6
  var stream = require('@mastra/core/stream');
7
+ var agent = require('@mastra/core/agent');
8
+ var di = require('@mastra/core/di');
9
+ var processors = require('@mastra/core/processors');
6
10
 
7
- // src/chat-route.ts
11
+ function _interopNamespace(e) {
12
+ if (e && e.__esModule) return e;
13
+ var n = Object.create(null);
14
+ if (e) {
15
+ Object.keys(e).forEach(function (k) {
16
+ if (k !== 'default') {
17
+ var d = Object.getOwnPropertyDescriptor(e, k);
18
+ Object.defineProperty(n, k, d.get ? d : {
19
+ enumerable: true,
20
+ get: function () { return e[k]; }
21
+ });
22
+ }
23
+ });
24
+ }
25
+ n.default = e;
26
+ return Object.freeze(n);
27
+ }
28
+
29
+ var z4__namespace = /*#__PURE__*/_interopNamespace(z4);
30
+
31
+ // ../../node_modules/.pnpm/@ai-sdk+provider@2.0.0/node_modules/@ai-sdk/provider/dist/index.mjs
32
+ var marker = "vercel.ai.error";
33
+ var symbol = Symbol.for(marker);
34
+ var _a;
35
+ var _AISDKError = class _AISDKError2 extends Error {
36
+ /**
37
+ * Creates an AI SDK Error.
38
+ *
39
+ * @param {Object} params - The parameters for creating the error.
40
+ * @param {string} params.name - The name of the error.
41
+ * @param {string} params.message - The error message.
42
+ * @param {unknown} [params.cause] - The underlying cause of the error.
43
+ */
44
+ constructor({
45
+ name: name143,
46
+ message,
47
+ cause
48
+ }) {
49
+ super(message);
50
+ this[_a] = true;
51
+ this.name = name143;
52
+ this.cause = cause;
53
+ }
54
+ /**
55
+ * Checks if the given error is an AI SDK Error.
56
+ * @param {unknown} error - The error to check.
57
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
58
+ */
59
+ static isInstance(error) {
60
+ return _AISDKError2.hasMarker(error, marker);
61
+ }
62
+ static hasMarker(error, marker153) {
63
+ const markerSymbol = Symbol.for(marker153);
64
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
65
+ }
66
+ };
67
+ _a = symbol;
68
+ var AISDKError = _AISDKError;
69
+ function getErrorMessage(error) {
70
+ if (error == null) {
71
+ return "unknown error";
72
+ }
73
+ if (typeof error === "string") {
74
+ return error;
75
+ }
76
+ if (error instanceof Error) {
77
+ return error.message;
78
+ }
79
+ return JSON.stringify(error);
80
+ }
81
+ var name3 = "AI_InvalidArgumentError";
82
+ var marker4 = `vercel.ai.error.${name3}`;
83
+ var symbol4 = Symbol.for(marker4);
84
+ var _a4;
85
+ var InvalidArgumentError = class extends AISDKError {
86
+ constructor({
87
+ message,
88
+ cause,
89
+ argument
90
+ }) {
91
+ super({ name: name3, message, cause });
92
+ this[_a4] = true;
93
+ this.argument = argument;
94
+ }
95
+ static isInstance(error) {
96
+ return AISDKError.hasMarker(error, marker4);
97
+ }
98
+ };
99
+ _a4 = symbol4;
100
+ var name6 = "AI_JSONParseError";
101
+ var marker7 = `vercel.ai.error.${name6}`;
102
+ var symbol7 = Symbol.for(marker7);
103
+ var _a7;
104
+ var JSONParseError = class extends AISDKError {
105
+ constructor({ text: text2, cause }) {
106
+ super({
107
+ name: name6,
108
+ message: `JSON parsing failed: Text: ${text2}.
109
+ Error message: ${getErrorMessage(cause)}`,
110
+ cause
111
+ });
112
+ this[_a7] = true;
113
+ this.text = text2;
114
+ }
115
+ static isInstance(error) {
116
+ return AISDKError.hasMarker(error, marker7);
117
+ }
118
+ };
119
+ _a7 = symbol7;
120
+ var name12 = "AI_TypeValidationError";
121
+ var marker13 = `vercel.ai.error.${name12}`;
122
+ var symbol13 = Symbol.for(marker13);
123
+ var _a13;
124
+ var _TypeValidationError = class _TypeValidationError2 extends AISDKError {
125
+ constructor({ value, cause }) {
126
+ super({
127
+ name: name12,
128
+ message: `Type validation failed: Value: ${JSON.stringify(value)}.
129
+ Error message: ${getErrorMessage(cause)}`,
130
+ cause
131
+ });
132
+ this[_a13] = true;
133
+ this.value = value;
134
+ }
135
+ static isInstance(error) {
136
+ return AISDKError.hasMarker(error, marker13);
137
+ }
138
+ /**
139
+ * Wraps an error into a TypeValidationError.
140
+ * If the cause is already a TypeValidationError with the same value, it returns the cause.
141
+ * Otherwise, it creates a new TypeValidationError.
142
+ *
143
+ * @param {Object} params - The parameters for wrapping the error.
144
+ * @param {unknown} params.value - The value that failed validation.
145
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
146
+ * @returns {TypeValidationError} A TypeValidationError instance.
147
+ */
148
+ static wrap({
149
+ value,
150
+ cause
151
+ }) {
152
+ return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause });
153
+ }
154
+ };
155
+ _a13 = symbol13;
156
+ var TypeValidationError = _TypeValidationError;
157
+ var createIdGenerator = ({
158
+ prefix,
159
+ size = 16,
160
+ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
161
+ separator = "-"
162
+ } = {}) => {
163
+ const generator = () => {
164
+ const alphabetLength = alphabet.length;
165
+ const chars = new Array(size);
166
+ for (let i = 0; i < size; i++) {
167
+ chars[i] = alphabet[Math.random() * alphabetLength | 0];
168
+ }
169
+ return chars.join("");
170
+ };
171
+ if (prefix == null) {
172
+ return generator;
173
+ }
174
+ if (alphabet.includes(separator)) {
175
+ throw new InvalidArgumentError({
176
+ argument: "separator",
177
+ message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".`
178
+ });
179
+ }
180
+ return () => `${prefix}${separator}${generator()}`;
181
+ };
182
+ var generateId = createIdGenerator();
183
+ function getErrorMessage2(error) {
184
+ if (error == null) {
185
+ return "unknown error";
186
+ }
187
+ if (typeof error === "string") {
188
+ return error;
189
+ }
190
+ if (error instanceof Error) {
191
+ return error.message;
192
+ }
193
+ return JSON.stringify(error);
194
+ }
195
+ var suspectProtoRx = /"__proto__"\s*:/;
196
+ var suspectConstructorRx = /"constructor"\s*:/;
197
+ function _parse(text2) {
198
+ const obj = JSON.parse(text2);
199
+ if (obj === null || typeof obj !== "object") {
200
+ return obj;
201
+ }
202
+ if (suspectProtoRx.test(text2) === false && suspectConstructorRx.test(text2) === false) {
203
+ return obj;
204
+ }
205
+ return filter(obj);
206
+ }
207
+ function filter(obj) {
208
+ let next = [obj];
209
+ while (next.length) {
210
+ const nodes = next;
211
+ next = [];
212
+ for (const node of nodes) {
213
+ if (Object.prototype.hasOwnProperty.call(node, "__proto__")) {
214
+ throw new SyntaxError("Object contains forbidden prototype property");
215
+ }
216
+ if (Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) {
217
+ throw new SyntaxError("Object contains forbidden prototype property");
218
+ }
219
+ for (const key in node) {
220
+ const value = node[key];
221
+ if (value && typeof value === "object") {
222
+ next.push(value);
223
+ }
224
+ }
225
+ }
226
+ }
227
+ return obj;
228
+ }
229
+ function secureJsonParse(text2) {
230
+ const { stackTraceLimit } = Error;
231
+ try {
232
+ Error.stackTraceLimit = 0;
233
+ } catch (e) {
234
+ return _parse(text2);
235
+ }
236
+ try {
237
+ return _parse(text2);
238
+ } finally {
239
+ Error.stackTraceLimit = stackTraceLimit;
240
+ }
241
+ }
242
+ var validatorSymbol = Symbol.for("vercel.ai.validator");
243
+ function validator(validate) {
244
+ return { [validatorSymbol]: true, validate };
245
+ }
246
+ function isValidator(value) {
247
+ return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
248
+ }
249
+ function asValidator(value) {
250
+ return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
251
+ }
252
+ function standardSchemaValidator(standardSchema) {
253
+ return validator(async (value) => {
254
+ const result = await standardSchema["~standard"].validate(value);
255
+ return result.issues == null ? { success: true, value: result.value } : {
256
+ success: false,
257
+ error: new TypeValidationError({
258
+ value,
259
+ cause: result.issues
260
+ })
261
+ };
262
+ });
263
+ }
264
+ async function validateTypes({
265
+ value,
266
+ schema
267
+ }) {
268
+ const result = await safeValidateTypes({ value, schema });
269
+ if (!result.success) {
270
+ throw TypeValidationError.wrap({ value, cause: result.error });
271
+ }
272
+ return result.value;
273
+ }
274
+ async function safeValidateTypes({
275
+ value,
276
+ schema
277
+ }) {
278
+ const validator2 = asValidator(schema);
279
+ try {
280
+ if (validator2.validate == null) {
281
+ return { success: true, value, rawValue: value };
282
+ }
283
+ const result = await validator2.validate(value);
284
+ if (result.success) {
285
+ return { success: true, value: result.value, rawValue: value };
286
+ }
287
+ return {
288
+ success: false,
289
+ error: TypeValidationError.wrap({ value, cause: result.error }),
290
+ rawValue: value
291
+ };
292
+ } catch (error) {
293
+ return {
294
+ success: false,
295
+ error: TypeValidationError.wrap({ value, cause: error }),
296
+ rawValue: value
297
+ };
298
+ }
299
+ }
300
+ async function safeParseJSON({
301
+ text: text2,
302
+ schema
303
+ }) {
304
+ try {
305
+ const value = secureJsonParse(text2);
306
+ if (schema == null) {
307
+ return { success: true, value, rawValue: value };
308
+ }
309
+ return await safeValidateTypes({ value, schema });
310
+ } catch (error) {
311
+ return {
312
+ success: false,
313
+ error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text: text2, cause: error }),
314
+ rawValue: void 0
315
+ };
316
+ }
317
+ }
318
+ var getRelativePath = (pathA, pathB) => {
319
+ let i = 0;
320
+ for (; i < pathA.length && i < pathB.length; i++) {
321
+ if (pathA[i] !== pathB[i]) break;
322
+ }
323
+ return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
324
+ };
325
+ var ignoreOverride = Symbol(
326
+ "Let zodToJsonSchema decide on which parser to use"
327
+ );
328
+ var defaultOptions = {
329
+ name: void 0,
330
+ $refStrategy: "root",
331
+ basePath: ["#"],
332
+ effectStrategy: "input",
333
+ pipeStrategy: "all",
334
+ dateStrategy: "format:date-time",
335
+ mapStrategy: "entries",
336
+ removeAdditionalStrategy: "passthrough",
337
+ allowedAdditionalProperties: true,
338
+ rejectedAdditionalProperties: false,
339
+ definitionPath: "definitions",
340
+ strictUnions: false,
341
+ definitions: {},
342
+ errorMessages: false,
343
+ patternStrategy: "escape",
344
+ applyRegexFlags: false,
345
+ emailStrategy: "format:email",
346
+ base64Strategy: "contentEncoding:base64",
347
+ nameStrategy: "ref"
348
+ };
349
+ var getDefaultOptions = (options) => typeof options === "string" ? {
350
+ ...defaultOptions,
351
+ name: options
352
+ } : {
353
+ ...defaultOptions,
354
+ ...options
355
+ };
356
+ function parseAnyDef() {
357
+ return {};
358
+ }
359
+ function parseArrayDef(def, refs) {
360
+ var _a16, _b, _c;
361
+ const res = {
362
+ type: "array"
363
+ };
364
+ if (((_a16 = def.type) == null ? void 0 : _a16._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== v3.ZodFirstPartyTypeKind.ZodAny) {
365
+ res.items = parseDef(def.type._def, {
366
+ ...refs,
367
+ currentPath: [...refs.currentPath, "items"]
368
+ });
369
+ }
370
+ if (def.minLength) {
371
+ res.minItems = def.minLength.value;
372
+ }
373
+ if (def.maxLength) {
374
+ res.maxItems = def.maxLength.value;
375
+ }
376
+ if (def.exactLength) {
377
+ res.minItems = def.exactLength.value;
378
+ res.maxItems = def.exactLength.value;
379
+ }
380
+ return res;
381
+ }
382
+ function parseBigintDef(def) {
383
+ const res = {
384
+ type: "integer",
385
+ format: "int64"
386
+ };
387
+ if (!def.checks) return res;
388
+ for (const check of def.checks) {
389
+ switch (check.kind) {
390
+ case "min":
391
+ if (check.inclusive) {
392
+ res.minimum = check.value;
393
+ } else {
394
+ res.exclusiveMinimum = check.value;
395
+ }
396
+ break;
397
+ case "max":
398
+ if (check.inclusive) {
399
+ res.maximum = check.value;
400
+ } else {
401
+ res.exclusiveMaximum = check.value;
402
+ }
403
+ break;
404
+ case "multipleOf":
405
+ res.multipleOf = check.value;
406
+ break;
407
+ }
408
+ }
409
+ return res;
410
+ }
411
+ function parseBooleanDef() {
412
+ return { type: "boolean" };
413
+ }
414
+ function parseBrandedDef(_def, refs) {
415
+ return parseDef(_def.type._def, refs);
416
+ }
417
+ var parseCatchDef = (def, refs) => {
418
+ return parseDef(def.innerType._def, refs);
419
+ };
420
+ function parseDateDef(def, refs, overrideDateStrategy) {
421
+ const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
422
+ if (Array.isArray(strategy)) {
423
+ return {
424
+ anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
425
+ };
426
+ }
427
+ switch (strategy) {
428
+ case "string":
429
+ case "format:date-time":
430
+ return {
431
+ type: "string",
432
+ format: "date-time"
433
+ };
434
+ case "format:date":
435
+ return {
436
+ type: "string",
437
+ format: "date"
438
+ };
439
+ case "integer":
440
+ return integerDateParser(def);
441
+ }
442
+ }
443
+ var integerDateParser = (def) => {
444
+ const res = {
445
+ type: "integer",
446
+ format: "unix-time"
447
+ };
448
+ for (const check of def.checks) {
449
+ switch (check.kind) {
450
+ case "min":
451
+ res.minimum = check.value;
452
+ break;
453
+ case "max":
454
+ res.maximum = check.value;
455
+ break;
456
+ }
457
+ }
458
+ return res;
459
+ };
460
+ function parseDefaultDef(_def, refs) {
461
+ return {
462
+ ...parseDef(_def.innerType._def, refs),
463
+ default: _def.defaultValue()
464
+ };
465
+ }
466
+ function parseEffectsDef(_def, refs) {
467
+ return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
468
+ }
469
+ function parseEnumDef(def) {
470
+ return {
471
+ type: "string",
472
+ enum: Array.from(def.values)
473
+ };
474
+ }
475
+ var isJsonSchema7AllOfType = (type) => {
476
+ if ("type" in type && type.type === "string") return false;
477
+ return "allOf" in type;
478
+ };
479
+ function parseIntersectionDef(def, refs) {
480
+ const allOf = [
481
+ parseDef(def.left._def, {
482
+ ...refs,
483
+ currentPath: [...refs.currentPath, "allOf", "0"]
484
+ }),
485
+ parseDef(def.right._def, {
486
+ ...refs,
487
+ currentPath: [...refs.currentPath, "allOf", "1"]
488
+ })
489
+ ].filter((x) => !!x);
490
+ const mergedAllOf = [];
491
+ allOf.forEach((schema) => {
492
+ if (isJsonSchema7AllOfType(schema)) {
493
+ mergedAllOf.push(...schema.allOf);
494
+ } else {
495
+ let nestedSchema = schema;
496
+ if ("additionalProperties" in schema && schema.additionalProperties === false) {
497
+ const { additionalProperties, ...rest } = schema;
498
+ nestedSchema = rest;
499
+ }
500
+ mergedAllOf.push(nestedSchema);
501
+ }
502
+ });
503
+ return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
504
+ }
505
+ function parseLiteralDef(def) {
506
+ const parsedType = typeof def.value;
507
+ if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
508
+ return {
509
+ type: Array.isArray(def.value) ? "array" : "object"
510
+ };
511
+ }
512
+ return {
513
+ type: parsedType === "bigint" ? "integer" : parsedType,
514
+ const: def.value
515
+ };
516
+ }
517
+ var emojiRegex = void 0;
518
+ var zodPatterns = {
519
+ /**
520
+ * `c` was changed to `[cC]` to replicate /i flag
521
+ */
522
+ cuid: /^[cC][^\s-]{8,}$/,
523
+ cuid2: /^[0-9a-z]+$/,
524
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
525
+ /**
526
+ * `a-z` was added to replicate /i flag
527
+ */
528
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
529
+ /**
530
+ * Constructed a valid Unicode RegExp
531
+ *
532
+ * Lazily instantiate since this type of regex isn't supported
533
+ * in all envs (e.g. React Native).
534
+ *
535
+ * See:
536
+ * https://github.com/colinhacks/zod/issues/2433
537
+ * Fix in Zod:
538
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
539
+ */
540
+ emoji: () => {
541
+ if (emojiRegex === void 0) {
542
+ emojiRegex = RegExp(
543
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
544
+ "u"
545
+ );
546
+ }
547
+ return emojiRegex;
548
+ },
549
+ /**
550
+ * Unused
551
+ */
552
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
553
+ /**
554
+ * Unused
555
+ */
556
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
557
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
558
+ /**
559
+ * Unused
560
+ */
561
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
562
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
563
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
564
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
565
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
566
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
567
+ };
568
+ function parseStringDef(def, refs) {
569
+ const res = {
570
+ type: "string"
571
+ };
572
+ if (def.checks) {
573
+ for (const check of def.checks) {
574
+ switch (check.kind) {
575
+ case "min":
576
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
577
+ break;
578
+ case "max":
579
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
580
+ break;
581
+ case "email":
582
+ switch (refs.emailStrategy) {
583
+ case "format:email":
584
+ addFormat(res, "email", check.message, refs);
585
+ break;
586
+ case "format:idn-email":
587
+ addFormat(res, "idn-email", check.message, refs);
588
+ break;
589
+ case "pattern:zod":
590
+ addPattern(res, zodPatterns.email, check.message, refs);
591
+ break;
592
+ }
593
+ break;
594
+ case "url":
595
+ addFormat(res, "uri", check.message, refs);
596
+ break;
597
+ case "uuid":
598
+ addFormat(res, "uuid", check.message, refs);
599
+ break;
600
+ case "regex":
601
+ addPattern(res, check.regex, check.message, refs);
602
+ break;
603
+ case "cuid":
604
+ addPattern(res, zodPatterns.cuid, check.message, refs);
605
+ break;
606
+ case "cuid2":
607
+ addPattern(res, zodPatterns.cuid2, check.message, refs);
608
+ break;
609
+ case "startsWith":
610
+ addPattern(
611
+ res,
612
+ RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
613
+ check.message,
614
+ refs
615
+ );
616
+ break;
617
+ case "endsWith":
618
+ addPattern(
619
+ res,
620
+ RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
621
+ check.message,
622
+ refs
623
+ );
624
+ break;
625
+ case "datetime":
626
+ addFormat(res, "date-time", check.message, refs);
627
+ break;
628
+ case "date":
629
+ addFormat(res, "date", check.message, refs);
630
+ break;
631
+ case "time":
632
+ addFormat(res, "time", check.message, refs);
633
+ break;
634
+ case "duration":
635
+ addFormat(res, "duration", check.message, refs);
636
+ break;
637
+ case "length":
638
+ res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
639
+ res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
640
+ break;
641
+ case "includes": {
642
+ addPattern(
643
+ res,
644
+ RegExp(escapeLiteralCheckValue(check.value, refs)),
645
+ check.message,
646
+ refs
647
+ );
648
+ break;
649
+ }
650
+ case "ip": {
651
+ if (check.version !== "v6") {
652
+ addFormat(res, "ipv4", check.message, refs);
653
+ }
654
+ if (check.version !== "v4") {
655
+ addFormat(res, "ipv6", check.message, refs);
656
+ }
657
+ break;
658
+ }
659
+ case "base64url":
660
+ addPattern(res, zodPatterns.base64url, check.message, refs);
661
+ break;
662
+ case "jwt":
663
+ addPattern(res, zodPatterns.jwt, check.message, refs);
664
+ break;
665
+ case "cidr": {
666
+ if (check.version !== "v6") {
667
+ addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
668
+ }
669
+ if (check.version !== "v4") {
670
+ addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
671
+ }
672
+ break;
673
+ }
674
+ case "emoji":
675
+ addPattern(res, zodPatterns.emoji(), check.message, refs);
676
+ break;
677
+ case "ulid": {
678
+ addPattern(res, zodPatterns.ulid, check.message, refs);
679
+ break;
680
+ }
681
+ case "base64": {
682
+ switch (refs.base64Strategy) {
683
+ case "format:binary": {
684
+ addFormat(res, "binary", check.message, refs);
685
+ break;
686
+ }
687
+ case "contentEncoding:base64": {
688
+ res.contentEncoding = "base64";
689
+ break;
690
+ }
691
+ case "pattern:zod": {
692
+ addPattern(res, zodPatterns.base64, check.message, refs);
693
+ break;
694
+ }
695
+ }
696
+ break;
697
+ }
698
+ case "nanoid": {
699
+ addPattern(res, zodPatterns.nanoid, check.message, refs);
700
+ }
701
+ }
702
+ }
703
+ }
704
+ return res;
705
+ }
706
+ function escapeLiteralCheckValue(literal, refs) {
707
+ return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
708
+ }
709
+ var ALPHA_NUMERIC = new Set(
710
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
711
+ );
712
+ function escapeNonAlphaNumeric(source) {
713
+ let result = "";
714
+ for (let i = 0; i < source.length; i++) {
715
+ if (!ALPHA_NUMERIC.has(source[i])) {
716
+ result += "\\";
717
+ }
718
+ result += source[i];
719
+ }
720
+ return result;
721
+ }
722
+ function addFormat(schema, value, message, refs) {
723
+ var _a16;
724
+ if (schema.format || ((_a16 = schema.anyOf) == null ? void 0 : _a16.some((x) => x.format))) {
725
+ if (!schema.anyOf) {
726
+ schema.anyOf = [];
727
+ }
728
+ if (schema.format) {
729
+ schema.anyOf.push({
730
+ format: schema.format
731
+ });
732
+ delete schema.format;
733
+ }
734
+ schema.anyOf.push({
735
+ format: value,
736
+ ...message && refs.errorMessages && { errorMessage: { format: message } }
737
+ });
738
+ } else {
739
+ schema.format = value;
740
+ }
741
+ }
742
+ function addPattern(schema, regex, message, refs) {
743
+ var _a16;
744
+ if (schema.pattern || ((_a16 = schema.allOf) == null ? void 0 : _a16.some((x) => x.pattern))) {
745
+ if (!schema.allOf) {
746
+ schema.allOf = [];
747
+ }
748
+ if (schema.pattern) {
749
+ schema.allOf.push({
750
+ pattern: schema.pattern
751
+ });
752
+ delete schema.pattern;
753
+ }
754
+ schema.allOf.push({
755
+ pattern: stringifyRegExpWithFlags(regex, refs),
756
+ ...message && refs.errorMessages && { errorMessage: { pattern: message } }
757
+ });
758
+ } else {
759
+ schema.pattern = stringifyRegExpWithFlags(regex, refs);
760
+ }
761
+ }
762
+ function stringifyRegExpWithFlags(regex, refs) {
763
+ var _a16;
764
+ if (!refs.applyRegexFlags || !regex.flags) {
765
+ return regex.source;
766
+ }
767
+ const flags = {
768
+ i: regex.flags.includes("i"),
769
+ // Case-insensitive
770
+ m: regex.flags.includes("m"),
771
+ // `^` and `$` matches adjacent to newline characters
772
+ s: regex.flags.includes("s")
773
+ // `.` matches newlines
774
+ };
775
+ const source = flags.i ? regex.source.toLowerCase() : regex.source;
776
+ let pattern = "";
777
+ let isEscaped = false;
778
+ let inCharGroup = false;
779
+ let inCharRange = false;
780
+ for (let i = 0; i < source.length; i++) {
781
+ if (isEscaped) {
782
+ pattern += source[i];
783
+ isEscaped = false;
784
+ continue;
785
+ }
786
+ if (flags.i) {
787
+ if (inCharGroup) {
788
+ if (source[i].match(/[a-z]/)) {
789
+ if (inCharRange) {
790
+ pattern += source[i];
791
+ pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
792
+ inCharRange = false;
793
+ } else if (source[i + 1] === "-" && ((_a16 = source[i + 2]) == null ? void 0 : _a16.match(/[a-z]/))) {
794
+ pattern += source[i];
795
+ inCharRange = true;
796
+ } else {
797
+ pattern += `${source[i]}${source[i].toUpperCase()}`;
798
+ }
799
+ continue;
800
+ }
801
+ } else if (source[i].match(/[a-z]/)) {
802
+ pattern += `[${source[i]}${source[i].toUpperCase()}]`;
803
+ continue;
804
+ }
805
+ }
806
+ if (flags.m) {
807
+ if (source[i] === "^") {
808
+ pattern += `(^|(?<=[\r
809
+ ]))`;
810
+ continue;
811
+ } else if (source[i] === "$") {
812
+ pattern += `($|(?=[\r
813
+ ]))`;
814
+ continue;
815
+ }
816
+ }
817
+ if (flags.s && source[i] === ".") {
818
+ pattern += inCharGroup ? `${source[i]}\r
819
+ ` : `[${source[i]}\r
820
+ ]`;
821
+ continue;
822
+ }
823
+ pattern += source[i];
824
+ if (source[i] === "\\") {
825
+ isEscaped = true;
826
+ } else if (inCharGroup && source[i] === "]") {
827
+ inCharGroup = false;
828
+ } else if (!inCharGroup && source[i] === "[") {
829
+ inCharGroup = true;
830
+ }
831
+ }
832
+ return pattern;
833
+ }
834
+ function parseRecordDef(def, refs) {
835
+ var _a16, _b, _c, _d, _e, _f;
836
+ const schema = {
837
+ type: "object",
838
+ additionalProperties: (_a16 = parseDef(def.valueType._def, {
839
+ ...refs,
840
+ currentPath: [...refs.currentPath, "additionalProperties"]
841
+ })) != null ? _a16 : refs.allowedAdditionalProperties
842
+ };
843
+ if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === v3.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
844
+ const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
845
+ return {
846
+ ...schema,
847
+ propertyNames: keyType
848
+ };
849
+ } else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === v3.ZodFirstPartyTypeKind.ZodEnum) {
850
+ return {
851
+ ...schema,
852
+ propertyNames: {
853
+ enum: def.keyType._def.values
854
+ }
855
+ };
856
+ } else if (((_e = def.keyType) == null ? void 0 : _e._def.typeName) === v3.ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === v3.ZodFirstPartyTypeKind.ZodString && ((_f = def.keyType._def.type._def.checks) == null ? void 0 : _f.length)) {
857
+ const { type, ...keyType } = parseBrandedDef(
858
+ def.keyType._def,
859
+ refs
860
+ );
861
+ return {
862
+ ...schema,
863
+ propertyNames: keyType
864
+ };
865
+ }
866
+ return schema;
867
+ }
868
+ function parseMapDef(def, refs) {
869
+ if (refs.mapStrategy === "record") {
870
+ return parseRecordDef(def, refs);
871
+ }
872
+ const keys = parseDef(def.keyType._def, {
873
+ ...refs,
874
+ currentPath: [...refs.currentPath, "items", "items", "0"]
875
+ }) || parseAnyDef();
876
+ const values = parseDef(def.valueType._def, {
877
+ ...refs,
878
+ currentPath: [...refs.currentPath, "items", "items", "1"]
879
+ }) || parseAnyDef();
880
+ return {
881
+ type: "array",
882
+ maxItems: 125,
883
+ items: {
884
+ type: "array",
885
+ items: [keys, values],
886
+ minItems: 2,
887
+ maxItems: 2
888
+ }
889
+ };
890
+ }
891
+ function parseNativeEnumDef(def) {
892
+ const object2 = def.values;
893
+ const actualKeys = Object.keys(def.values).filter((key) => {
894
+ return typeof object2[object2[key]] !== "number";
895
+ });
896
+ const actualValues = actualKeys.map((key) => object2[key]);
897
+ const parsedTypes = Array.from(
898
+ new Set(actualValues.map((values) => typeof values))
899
+ );
900
+ return {
901
+ type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
902
+ enum: actualValues
903
+ };
904
+ }
905
+ function parseNeverDef() {
906
+ return { not: parseAnyDef() };
907
+ }
908
+ function parseNullDef() {
909
+ return {
910
+ type: "null"
911
+ };
912
+ }
913
+ var primitiveMappings = {
914
+ ZodString: "string",
915
+ ZodNumber: "number",
916
+ ZodBigInt: "integer",
917
+ ZodBoolean: "boolean",
918
+ ZodNull: "null"
919
+ };
920
+ function parseUnionDef(def, refs) {
921
+ const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
922
+ if (options.every(
923
+ (x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
924
+ )) {
925
+ const types = options.reduce((types2, x) => {
926
+ const type = primitiveMappings[x._def.typeName];
927
+ return type && !types2.includes(type) ? [...types2, type] : types2;
928
+ }, []);
929
+ return {
930
+ type: types.length > 1 ? types : types[0]
931
+ };
932
+ } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
933
+ const types = options.reduce(
934
+ (acc, x) => {
935
+ const type = typeof x._def.value;
936
+ switch (type) {
937
+ case "string":
938
+ case "number":
939
+ case "boolean":
940
+ return [...acc, type];
941
+ case "bigint":
942
+ return [...acc, "integer"];
943
+ case "object":
944
+ if (x._def.value === null) return [...acc, "null"];
945
+ case "symbol":
946
+ case "undefined":
947
+ case "function":
948
+ default:
949
+ return acc;
950
+ }
951
+ },
952
+ []
953
+ );
954
+ if (types.length === options.length) {
955
+ const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
956
+ return {
957
+ type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
958
+ enum: options.reduce(
959
+ (acc, x) => {
960
+ return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
961
+ },
962
+ []
963
+ )
964
+ };
965
+ }
966
+ } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
967
+ return {
968
+ type: "string",
969
+ enum: options.reduce(
970
+ (acc, x) => [
971
+ ...acc,
972
+ ...x._def.values.filter((x2) => !acc.includes(x2))
973
+ ],
974
+ []
975
+ )
976
+ };
977
+ }
978
+ return asAnyOf(def, refs);
979
+ }
980
+ var asAnyOf = (def, refs) => {
981
+ const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
982
+ (x, i) => parseDef(x._def, {
983
+ ...refs,
984
+ currentPath: [...refs.currentPath, "anyOf", `${i}`]
985
+ })
986
+ ).filter(
987
+ (x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
988
+ );
989
+ return anyOf.length ? { anyOf } : void 0;
990
+ };
991
+ function parseNullableDef(def, refs) {
992
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
993
+ def.innerType._def.typeName
994
+ ) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
995
+ return {
996
+ type: [
997
+ primitiveMappings[def.innerType._def.typeName],
998
+ "null"
999
+ ]
1000
+ };
1001
+ }
1002
+ const base = parseDef(def.innerType._def, {
1003
+ ...refs,
1004
+ currentPath: [...refs.currentPath, "anyOf", "0"]
1005
+ });
1006
+ return base && { anyOf: [base, { type: "null" }] };
1007
+ }
1008
+ function parseNumberDef(def) {
1009
+ const res = {
1010
+ type: "number"
1011
+ };
1012
+ if (!def.checks) return res;
1013
+ for (const check of def.checks) {
1014
+ switch (check.kind) {
1015
+ case "int":
1016
+ res.type = "integer";
1017
+ break;
1018
+ case "min":
1019
+ if (check.inclusive) {
1020
+ res.minimum = check.value;
1021
+ } else {
1022
+ res.exclusiveMinimum = check.value;
1023
+ }
1024
+ break;
1025
+ case "max":
1026
+ if (check.inclusive) {
1027
+ res.maximum = check.value;
1028
+ } else {
1029
+ res.exclusiveMaximum = check.value;
1030
+ }
1031
+ break;
1032
+ case "multipleOf":
1033
+ res.multipleOf = check.value;
1034
+ break;
1035
+ }
1036
+ }
1037
+ return res;
1038
+ }
1039
+ function parseObjectDef(def, refs) {
1040
+ const result = {
1041
+ type: "object",
1042
+ properties: {}
1043
+ };
1044
+ const required = [];
1045
+ const shape = def.shape();
1046
+ for (const propName in shape) {
1047
+ let propDef = shape[propName];
1048
+ if (propDef === void 0 || propDef._def === void 0) {
1049
+ continue;
1050
+ }
1051
+ const propOptional = safeIsOptional(propDef);
1052
+ const parsedDef = parseDef(propDef._def, {
1053
+ ...refs,
1054
+ currentPath: [...refs.currentPath, "properties", propName],
1055
+ propertyPath: [...refs.currentPath, "properties", propName]
1056
+ });
1057
+ if (parsedDef === void 0) {
1058
+ continue;
1059
+ }
1060
+ result.properties[propName] = parsedDef;
1061
+ if (!propOptional) {
1062
+ required.push(propName);
1063
+ }
1064
+ }
1065
+ if (required.length) {
1066
+ result.required = required;
1067
+ }
1068
+ const additionalProperties = decideAdditionalProperties(def, refs);
1069
+ if (additionalProperties !== void 0) {
1070
+ result.additionalProperties = additionalProperties;
1071
+ }
1072
+ return result;
1073
+ }
1074
+ function decideAdditionalProperties(def, refs) {
1075
+ if (def.catchall._def.typeName !== "ZodNever") {
1076
+ return parseDef(def.catchall._def, {
1077
+ ...refs,
1078
+ currentPath: [...refs.currentPath, "additionalProperties"]
1079
+ });
1080
+ }
1081
+ switch (def.unknownKeys) {
1082
+ case "passthrough":
1083
+ return refs.allowedAdditionalProperties;
1084
+ case "strict":
1085
+ return refs.rejectedAdditionalProperties;
1086
+ case "strip":
1087
+ return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
1088
+ }
1089
+ }
1090
+ function safeIsOptional(schema) {
1091
+ try {
1092
+ return schema.isOptional();
1093
+ } catch (e) {
1094
+ return true;
1095
+ }
1096
+ }
1097
+ var parseOptionalDef = (def, refs) => {
1098
+ var _a16;
1099
+ if (refs.currentPath.toString() === ((_a16 = refs.propertyPath) == null ? void 0 : _a16.toString())) {
1100
+ return parseDef(def.innerType._def, refs);
1101
+ }
1102
+ const innerSchema = parseDef(def.innerType._def, {
1103
+ ...refs,
1104
+ currentPath: [...refs.currentPath, "anyOf", "1"]
1105
+ });
1106
+ return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
1107
+ };
1108
+ var parsePipelineDef = (def, refs) => {
1109
+ if (refs.pipeStrategy === "input") {
1110
+ return parseDef(def.in._def, refs);
1111
+ } else if (refs.pipeStrategy === "output") {
1112
+ return parseDef(def.out._def, refs);
1113
+ }
1114
+ const a = parseDef(def.in._def, {
1115
+ ...refs,
1116
+ currentPath: [...refs.currentPath, "allOf", "0"]
1117
+ });
1118
+ const b = parseDef(def.out._def, {
1119
+ ...refs,
1120
+ currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1121
+ });
1122
+ return {
1123
+ allOf: [a, b].filter((x) => x !== void 0)
1124
+ };
1125
+ };
1126
+ function parsePromiseDef(def, refs) {
1127
+ return parseDef(def.type._def, refs);
1128
+ }
1129
+ function parseSetDef(def, refs) {
1130
+ const items = parseDef(def.valueType._def, {
1131
+ ...refs,
1132
+ currentPath: [...refs.currentPath, "items"]
1133
+ });
1134
+ const schema = {
1135
+ type: "array",
1136
+ uniqueItems: true,
1137
+ items
1138
+ };
1139
+ if (def.minSize) {
1140
+ schema.minItems = def.minSize.value;
1141
+ }
1142
+ if (def.maxSize) {
1143
+ schema.maxItems = def.maxSize.value;
1144
+ }
1145
+ return schema;
1146
+ }
1147
+ function parseTupleDef(def, refs) {
1148
+ if (def.rest) {
1149
+ return {
1150
+ type: "array",
1151
+ minItems: def.items.length,
1152
+ items: def.items.map(
1153
+ (x, i) => parseDef(x._def, {
1154
+ ...refs,
1155
+ currentPath: [...refs.currentPath, "items", `${i}`]
1156
+ })
1157
+ ).reduce(
1158
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1159
+ []
1160
+ ),
1161
+ additionalItems: parseDef(def.rest._def, {
1162
+ ...refs,
1163
+ currentPath: [...refs.currentPath, "additionalItems"]
1164
+ })
1165
+ };
1166
+ } else {
1167
+ return {
1168
+ type: "array",
1169
+ minItems: def.items.length,
1170
+ maxItems: def.items.length,
1171
+ items: def.items.map(
1172
+ (x, i) => parseDef(x._def, {
1173
+ ...refs,
1174
+ currentPath: [...refs.currentPath, "items", `${i}`]
1175
+ })
1176
+ ).reduce(
1177
+ (acc, x) => x === void 0 ? acc : [...acc, x],
1178
+ []
1179
+ )
1180
+ };
1181
+ }
1182
+ }
1183
+ function parseUndefinedDef() {
1184
+ return {
1185
+ not: parseAnyDef()
1186
+ };
1187
+ }
1188
+ function parseUnknownDef() {
1189
+ return parseAnyDef();
1190
+ }
1191
+ var parseReadonlyDef = (def, refs) => {
1192
+ return parseDef(def.innerType._def, refs);
1193
+ };
1194
+ var selectParser = (def, typeName, refs) => {
1195
+ switch (typeName) {
1196
+ case v3.ZodFirstPartyTypeKind.ZodString:
1197
+ return parseStringDef(def, refs);
1198
+ case v3.ZodFirstPartyTypeKind.ZodNumber:
1199
+ return parseNumberDef(def);
1200
+ case v3.ZodFirstPartyTypeKind.ZodObject:
1201
+ return parseObjectDef(def, refs);
1202
+ case v3.ZodFirstPartyTypeKind.ZodBigInt:
1203
+ return parseBigintDef(def);
1204
+ case v3.ZodFirstPartyTypeKind.ZodBoolean:
1205
+ return parseBooleanDef();
1206
+ case v3.ZodFirstPartyTypeKind.ZodDate:
1207
+ return parseDateDef(def, refs);
1208
+ case v3.ZodFirstPartyTypeKind.ZodUndefined:
1209
+ return parseUndefinedDef();
1210
+ case v3.ZodFirstPartyTypeKind.ZodNull:
1211
+ return parseNullDef();
1212
+ case v3.ZodFirstPartyTypeKind.ZodArray:
1213
+ return parseArrayDef(def, refs);
1214
+ case v3.ZodFirstPartyTypeKind.ZodUnion:
1215
+ case v3.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
1216
+ return parseUnionDef(def, refs);
1217
+ case v3.ZodFirstPartyTypeKind.ZodIntersection:
1218
+ return parseIntersectionDef(def, refs);
1219
+ case v3.ZodFirstPartyTypeKind.ZodTuple:
1220
+ return parseTupleDef(def, refs);
1221
+ case v3.ZodFirstPartyTypeKind.ZodRecord:
1222
+ return parseRecordDef(def, refs);
1223
+ case v3.ZodFirstPartyTypeKind.ZodLiteral:
1224
+ return parseLiteralDef(def);
1225
+ case v3.ZodFirstPartyTypeKind.ZodEnum:
1226
+ return parseEnumDef(def);
1227
+ case v3.ZodFirstPartyTypeKind.ZodNativeEnum:
1228
+ return parseNativeEnumDef(def);
1229
+ case v3.ZodFirstPartyTypeKind.ZodNullable:
1230
+ return parseNullableDef(def, refs);
1231
+ case v3.ZodFirstPartyTypeKind.ZodOptional:
1232
+ return parseOptionalDef(def, refs);
1233
+ case v3.ZodFirstPartyTypeKind.ZodMap:
1234
+ return parseMapDef(def, refs);
1235
+ case v3.ZodFirstPartyTypeKind.ZodSet:
1236
+ return parseSetDef(def, refs);
1237
+ case v3.ZodFirstPartyTypeKind.ZodLazy:
1238
+ return () => def.getter()._def;
1239
+ case v3.ZodFirstPartyTypeKind.ZodPromise:
1240
+ return parsePromiseDef(def, refs);
1241
+ case v3.ZodFirstPartyTypeKind.ZodNaN:
1242
+ case v3.ZodFirstPartyTypeKind.ZodNever:
1243
+ return parseNeverDef();
1244
+ case v3.ZodFirstPartyTypeKind.ZodEffects:
1245
+ return parseEffectsDef(def, refs);
1246
+ case v3.ZodFirstPartyTypeKind.ZodAny:
1247
+ return parseAnyDef();
1248
+ case v3.ZodFirstPartyTypeKind.ZodUnknown:
1249
+ return parseUnknownDef();
1250
+ case v3.ZodFirstPartyTypeKind.ZodDefault:
1251
+ return parseDefaultDef(def, refs);
1252
+ case v3.ZodFirstPartyTypeKind.ZodBranded:
1253
+ return parseBrandedDef(def, refs);
1254
+ case v3.ZodFirstPartyTypeKind.ZodReadonly:
1255
+ return parseReadonlyDef(def, refs);
1256
+ case v3.ZodFirstPartyTypeKind.ZodCatch:
1257
+ return parseCatchDef(def, refs);
1258
+ case v3.ZodFirstPartyTypeKind.ZodPipeline:
1259
+ return parsePipelineDef(def, refs);
1260
+ case v3.ZodFirstPartyTypeKind.ZodFunction:
1261
+ case v3.ZodFirstPartyTypeKind.ZodVoid:
1262
+ case v3.ZodFirstPartyTypeKind.ZodSymbol:
1263
+ return void 0;
1264
+ default:
1265
+ return /* @__PURE__ */ ((_) => void 0)();
1266
+ }
1267
+ };
1268
+ function parseDef(def, refs, forceResolution = false) {
1269
+ var _a16;
1270
+ const seenItem = refs.seen.get(def);
1271
+ if (refs.override) {
1272
+ const overrideResult = (_a16 = refs.override) == null ? void 0 : _a16.call(
1273
+ refs,
1274
+ def,
1275
+ refs,
1276
+ seenItem,
1277
+ forceResolution
1278
+ );
1279
+ if (overrideResult !== ignoreOverride) {
1280
+ return overrideResult;
1281
+ }
1282
+ }
1283
+ if (seenItem && !forceResolution) {
1284
+ const seenSchema = get$ref(seenItem, refs);
1285
+ if (seenSchema !== void 0) {
1286
+ return seenSchema;
1287
+ }
1288
+ }
1289
+ const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1290
+ refs.seen.set(def, newItem);
1291
+ const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1292
+ const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1293
+ if (jsonSchema2) {
1294
+ addMeta(def, refs, jsonSchema2);
1295
+ }
1296
+ if (refs.postProcess) {
1297
+ const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
1298
+ newItem.jsonSchema = jsonSchema2;
1299
+ return postProcessResult;
1300
+ }
1301
+ newItem.jsonSchema = jsonSchema2;
1302
+ return jsonSchema2;
1303
+ }
1304
+ var get$ref = (item, refs) => {
1305
+ switch (refs.$refStrategy) {
1306
+ case "root":
1307
+ return { $ref: item.path.join("/") };
1308
+ case "relative":
1309
+ return { $ref: getRelativePath(refs.currentPath, item.path) };
1310
+ case "none":
1311
+ case "seen": {
1312
+ if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1313
+ console.warn(
1314
+ `Recursive reference detected at ${refs.currentPath.join(
1315
+ "/"
1316
+ )}! Defaulting to any`
1317
+ );
1318
+ return parseAnyDef();
1319
+ }
1320
+ return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
1321
+ }
1322
+ }
1323
+ };
1324
+ var addMeta = (def, refs, jsonSchema2) => {
1325
+ if (def.description) {
1326
+ jsonSchema2.description = def.description;
1327
+ }
1328
+ return jsonSchema2;
1329
+ };
1330
+ var getRefs = (options) => {
1331
+ const _options = getDefaultOptions(options);
1332
+ const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
1333
+ return {
1334
+ ..._options,
1335
+ currentPath,
1336
+ propertyPath: void 0,
1337
+ seen: new Map(
1338
+ Object.entries(_options.definitions).map(([name16, def]) => [
1339
+ def._def,
1340
+ {
1341
+ def: def._def,
1342
+ path: [..._options.basePath, _options.definitionPath, name16],
1343
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1344
+ jsonSchema: void 0
1345
+ }
1346
+ ])
1347
+ )
1348
+ };
1349
+ };
1350
+ var zodToJsonSchema = (schema, options) => {
1351
+ var _a16;
1352
+ const refs = getRefs(options);
1353
+ let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1354
+ (acc, [name23, schema2]) => {
1355
+ var _a23;
1356
+ return {
1357
+ ...acc,
1358
+ [name23]: (_a23 = parseDef(
1359
+ schema2._def,
1360
+ {
1361
+ ...refs,
1362
+ currentPath: [...refs.basePath, refs.definitionPath, name23]
1363
+ },
1364
+ true
1365
+ )) != null ? _a23 : parseAnyDef()
1366
+ };
1367
+ },
1368
+ {}
1369
+ ) : void 0;
1370
+ const name16 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1371
+ const main = (_a16 = parseDef(
1372
+ schema._def,
1373
+ name16 === void 0 ? refs : {
1374
+ ...refs,
1375
+ currentPath: [...refs.basePath, refs.definitionPath, name16]
1376
+ },
1377
+ false
1378
+ )) != null ? _a16 : parseAnyDef();
1379
+ const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1380
+ if (title !== void 0) {
1381
+ main.title = title;
1382
+ }
1383
+ const combined = name16 === void 0 ? definitions ? {
1384
+ ...main,
1385
+ [refs.definitionPath]: definitions
1386
+ } : main : {
1387
+ $ref: [
1388
+ ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1389
+ refs.definitionPath,
1390
+ name16
1391
+ ].join("/"),
1392
+ [refs.definitionPath]: {
1393
+ ...definitions,
1394
+ [name16]: main
1395
+ }
1396
+ };
1397
+ combined.$schema = "http://json-schema.org/draft-07/schema#";
1398
+ return combined;
1399
+ };
1400
+ var zod_to_json_schema_default = zodToJsonSchema;
1401
+ function zod3Schema(zodSchema2, options) {
1402
+ var _a16;
1403
+ const useReferences = (_a16 = void 0 ) != null ? _a16 : false;
1404
+ return jsonSchema(
1405
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1406
+ () => zod_to_json_schema_default(zodSchema2, {
1407
+ $refStrategy: useReferences ? "root" : "none"
1408
+ }),
1409
+ {
1410
+ validate: async (value) => {
1411
+ const result = await zodSchema2.safeParseAsync(value);
1412
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1413
+ }
1414
+ }
1415
+ );
1416
+ }
1417
+ function zod4Schema(zodSchema2, options) {
1418
+ var _a16;
1419
+ const useReferences = (_a16 = void 0 ) != null ? _a16 : false;
1420
+ return jsonSchema(
1421
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1422
+ () => z4__namespace.toJSONSchema(zodSchema2, {
1423
+ target: "draft-7",
1424
+ io: "output",
1425
+ reused: useReferences ? "ref" : "inline"
1426
+ }),
1427
+ {
1428
+ validate: async (value) => {
1429
+ const result = await z4__namespace.safeParseAsync(zodSchema2, value);
1430
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
1431
+ }
1432
+ }
1433
+ );
1434
+ }
1435
+ function isZod4Schema(zodSchema2) {
1436
+ return "_zod" in zodSchema2;
1437
+ }
1438
+ function zodSchema(zodSchema2, options) {
1439
+ if (isZod4Schema(zodSchema2)) {
1440
+ return zod4Schema(zodSchema2);
1441
+ } else {
1442
+ return zod3Schema(zodSchema2);
1443
+ }
1444
+ }
1445
+ var schemaSymbol = Symbol.for("vercel.ai.schema");
1446
+ function jsonSchema(jsonSchema2, {
1447
+ validate
1448
+ } = {}) {
1449
+ return {
1450
+ [schemaSymbol]: true,
1451
+ _type: void 0,
1452
+ // should never be used directly
1453
+ [validatorSymbol]: true,
1454
+ get jsonSchema() {
1455
+ if (typeof jsonSchema2 === "function") {
1456
+ jsonSchema2 = jsonSchema2();
1457
+ }
1458
+ return jsonSchema2;
1459
+ },
1460
+ validate
1461
+ };
1462
+ }
1463
+ function isSchema(value) {
1464
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
1465
+ }
1466
+ function asSchema(schema) {
1467
+ return schema == null ? jsonSchema({
1468
+ properties: {},
1469
+ additionalProperties: false
1470
+ }) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
1471
+ }
1472
+ var __defProp = Object.defineProperty;
1473
+ var __export = (target, all) => {
1474
+ for (var name16 in all)
1475
+ __defProp(target, name16, { get: all[name16], enumerable: true });
1476
+ };
1477
+ var name62 = "AI_NoObjectGeneratedError";
1478
+ var marker62 = `vercel.ai.error.${name62}`;
1479
+ var symbol62 = Symbol.for(marker62);
1480
+ var _a62;
1481
+ var NoObjectGeneratedError = class extends AISDKError {
1482
+ constructor({
1483
+ message = "No object generated.",
1484
+ cause,
1485
+ text: text2,
1486
+ response,
1487
+ usage,
1488
+ finishReason
1489
+ }) {
1490
+ super({ name: name62, message, cause });
1491
+ this[_a62] = true;
1492
+ this.text = text2;
1493
+ this.response = response;
1494
+ this.usage = usage;
1495
+ this.finishReason = finishReason;
1496
+ }
1497
+ static isInstance(error) {
1498
+ return AISDKError.hasMarker(error, marker62);
1499
+ }
1500
+ };
1501
+ _a62 = symbol62;
1502
+ var dataContentSchema = z4.z.union([
1503
+ z4.z.string(),
1504
+ z4.z.instanceof(Uint8Array),
1505
+ z4.z.instanceof(ArrayBuffer),
1506
+ z4.z.custom(
1507
+ // Buffer might not be available in some environments such as CloudFlare:
1508
+ (value) => {
1509
+ var _a16, _b;
1510
+ return (_b = (_a16 = globalThis.Buffer) == null ? void 0 : _a16.isBuffer(value)) != null ? _b : false;
1511
+ },
1512
+ { message: "Must be a Buffer" }
1513
+ )
1514
+ ]);
1515
+ var jsonValueSchema = z4.z.lazy(
1516
+ () => z4.z.union([
1517
+ z4.z.null(),
1518
+ z4.z.string(),
1519
+ z4.z.number(),
1520
+ z4.z.boolean(),
1521
+ z4.z.record(z4.z.string(), jsonValueSchema),
1522
+ z4.z.array(jsonValueSchema)
1523
+ ])
1524
+ );
1525
+ var providerMetadataSchema = z4.z.record(
1526
+ z4.z.string(),
1527
+ z4.z.record(z4.z.string(), jsonValueSchema)
1528
+ );
1529
+ var textPartSchema = z4.z.object({
1530
+ type: z4.z.literal("text"),
1531
+ text: z4.z.string(),
1532
+ providerOptions: providerMetadataSchema.optional()
1533
+ });
1534
+ var imagePartSchema = z4.z.object({
1535
+ type: z4.z.literal("image"),
1536
+ image: z4.z.union([dataContentSchema, z4.z.instanceof(URL)]),
1537
+ mediaType: z4.z.string().optional(),
1538
+ providerOptions: providerMetadataSchema.optional()
1539
+ });
1540
+ var filePartSchema = z4.z.object({
1541
+ type: z4.z.literal("file"),
1542
+ data: z4.z.union([dataContentSchema, z4.z.instanceof(URL)]),
1543
+ filename: z4.z.string().optional(),
1544
+ mediaType: z4.z.string(),
1545
+ providerOptions: providerMetadataSchema.optional()
1546
+ });
1547
+ var reasoningPartSchema = z4.z.object({
1548
+ type: z4.z.literal("reasoning"),
1549
+ text: z4.z.string(),
1550
+ providerOptions: providerMetadataSchema.optional()
1551
+ });
1552
+ var toolCallPartSchema = z4.z.object({
1553
+ type: z4.z.literal("tool-call"),
1554
+ toolCallId: z4.z.string(),
1555
+ toolName: z4.z.string(),
1556
+ input: z4.z.unknown(),
1557
+ providerOptions: providerMetadataSchema.optional(),
1558
+ providerExecuted: z4.z.boolean().optional()
1559
+ });
1560
+ var outputSchema = z4.z.discriminatedUnion("type", [
1561
+ z4.z.object({
1562
+ type: z4.z.literal("text"),
1563
+ value: z4.z.string()
1564
+ }),
1565
+ z4.z.object({
1566
+ type: z4.z.literal("json"),
1567
+ value: jsonValueSchema
1568
+ }),
1569
+ z4.z.object({
1570
+ type: z4.z.literal("error-text"),
1571
+ value: z4.z.string()
1572
+ }),
1573
+ z4.z.object({
1574
+ type: z4.z.literal("error-json"),
1575
+ value: jsonValueSchema
1576
+ }),
1577
+ z4.z.object({
1578
+ type: z4.z.literal("content"),
1579
+ value: z4.z.array(
1580
+ z4.z.union([
1581
+ z4.z.object({
1582
+ type: z4.z.literal("text"),
1583
+ text: z4.z.string()
1584
+ }),
1585
+ z4.z.object({
1586
+ type: z4.z.literal("media"),
1587
+ data: z4.z.string(),
1588
+ mediaType: z4.z.string()
1589
+ })
1590
+ ])
1591
+ )
1592
+ })
1593
+ ]);
1594
+ var toolResultPartSchema = z4.z.object({
1595
+ type: z4.z.literal("tool-result"),
1596
+ toolCallId: z4.z.string(),
1597
+ toolName: z4.z.string(),
1598
+ output: outputSchema,
1599
+ providerOptions: providerMetadataSchema.optional()
1600
+ });
1601
+ var systemModelMessageSchema = z4.z.object(
1602
+ {
1603
+ role: z4.z.literal("system"),
1604
+ content: z4.z.string(),
1605
+ providerOptions: providerMetadataSchema.optional()
1606
+ }
1607
+ );
1608
+ var userModelMessageSchema = z4.z.object({
1609
+ role: z4.z.literal("user"),
1610
+ content: z4.z.union([
1611
+ z4.z.string(),
1612
+ z4.z.array(z4.z.union([textPartSchema, imagePartSchema, filePartSchema]))
1613
+ ]),
1614
+ providerOptions: providerMetadataSchema.optional()
1615
+ });
1616
+ var assistantModelMessageSchema = z4.z.object({
1617
+ role: z4.z.literal("assistant"),
1618
+ content: z4.z.union([
1619
+ z4.z.string(),
1620
+ z4.z.array(
1621
+ z4.z.union([
1622
+ textPartSchema,
1623
+ filePartSchema,
1624
+ reasoningPartSchema,
1625
+ toolCallPartSchema,
1626
+ toolResultPartSchema
1627
+ ])
1628
+ )
1629
+ ]),
1630
+ providerOptions: providerMetadataSchema.optional()
1631
+ });
1632
+ var toolModelMessageSchema = z4.z.object({
1633
+ role: z4.z.literal("tool"),
1634
+ content: z4.z.array(toolResultPartSchema),
1635
+ providerOptions: providerMetadataSchema.optional()
1636
+ });
1637
+ z4.z.union([
1638
+ systemModelMessageSchema,
1639
+ userModelMessageSchema,
1640
+ assistantModelMessageSchema,
1641
+ toolModelMessageSchema
1642
+ ]);
1643
+ function asArray(value) {
1644
+ return value === void 0 ? [] : Array.isArray(value) ? value : [value];
1645
+ }
1646
+ createIdGenerator({
1647
+ prefix: "aitxt",
1648
+ size: 24
1649
+ });
1650
+ function prepareHeaders(headers, defaultHeaders) {
1651
+ const responseHeaders = new Headers(headers != null ? headers : {});
1652
+ for (const [key, value] of Object.entries(defaultHeaders)) {
1653
+ if (!responseHeaders.has(key)) {
1654
+ responseHeaders.set(key, value);
1655
+ }
1656
+ }
1657
+ return responseHeaders;
1658
+ }
1659
+ var JsonToSseTransformStream = class extends TransformStream {
1660
+ constructor() {
1661
+ super({
1662
+ transform(part, controller) {
1663
+ controller.enqueue(`data: ${JSON.stringify(part)}
1664
+
1665
+ `);
1666
+ },
1667
+ flush(controller) {
1668
+ controller.enqueue("data: [DONE]\n\n");
1669
+ }
1670
+ });
1671
+ }
1672
+ };
1673
+ var UI_MESSAGE_STREAM_HEADERS = {
1674
+ "content-type": "text/event-stream",
1675
+ "cache-control": "no-cache",
1676
+ connection: "keep-alive",
1677
+ "x-vercel-ai-ui-message-stream": "v1",
1678
+ "x-accel-buffering": "no"
1679
+ // disable nginx buffering
1680
+ };
1681
+ function createUIMessageStreamResponse({
1682
+ status,
1683
+ statusText,
1684
+ headers,
1685
+ stream,
1686
+ consumeSseStream
1687
+ }) {
1688
+ let sseStream = stream.pipeThrough(new JsonToSseTransformStream());
1689
+ if (consumeSseStream) {
1690
+ const [stream1, stream2] = sseStream.tee();
1691
+ sseStream = stream1;
1692
+ consumeSseStream({ stream: stream2 });
1693
+ }
1694
+ return new Response(sseStream.pipeThrough(new TextEncoderStream()), {
1695
+ status,
1696
+ statusText,
1697
+ headers: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)
1698
+ });
1699
+ }
1700
+ function isDataUIMessageChunk(chunk) {
1701
+ return chunk.type.startsWith("data-");
1702
+ }
1703
+ function mergeObjects(base, overrides) {
1704
+ if (base === void 0 && overrides === void 0) {
1705
+ return void 0;
1706
+ }
1707
+ if (base === void 0) {
1708
+ return overrides;
1709
+ }
1710
+ if (overrides === void 0) {
1711
+ return base;
1712
+ }
1713
+ const result = { ...base };
1714
+ for (const key in overrides) {
1715
+ if (Object.prototype.hasOwnProperty.call(overrides, key)) {
1716
+ const overridesValue = overrides[key];
1717
+ if (overridesValue === void 0)
1718
+ continue;
1719
+ const baseValue = key in base ? base[key] : void 0;
1720
+ const isSourceObject = overridesValue !== null && typeof overridesValue === "object" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);
1721
+ const isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === "object" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);
1722
+ if (isSourceObject && isTargetObject) {
1723
+ result[key] = mergeObjects(
1724
+ baseValue,
1725
+ overridesValue
1726
+ );
1727
+ } else {
1728
+ result[key] = overridesValue;
1729
+ }
1730
+ }
1731
+ }
1732
+ return result;
1733
+ }
1734
+ function fixJson(input) {
1735
+ const stack = ["ROOT"];
1736
+ let lastValidIndex = -1;
1737
+ let literalStart = null;
1738
+ function processValueStart(char, i, swapState) {
1739
+ {
1740
+ switch (char) {
1741
+ case '"': {
1742
+ lastValidIndex = i;
1743
+ stack.pop();
1744
+ stack.push(swapState);
1745
+ stack.push("INSIDE_STRING");
1746
+ break;
1747
+ }
1748
+ case "f":
1749
+ case "t":
1750
+ case "n": {
1751
+ lastValidIndex = i;
1752
+ literalStart = i;
1753
+ stack.pop();
1754
+ stack.push(swapState);
1755
+ stack.push("INSIDE_LITERAL");
1756
+ break;
1757
+ }
1758
+ case "-": {
1759
+ stack.pop();
1760
+ stack.push(swapState);
1761
+ stack.push("INSIDE_NUMBER");
1762
+ break;
1763
+ }
1764
+ case "0":
1765
+ case "1":
1766
+ case "2":
1767
+ case "3":
1768
+ case "4":
1769
+ case "5":
1770
+ case "6":
1771
+ case "7":
1772
+ case "8":
1773
+ case "9": {
1774
+ lastValidIndex = i;
1775
+ stack.pop();
1776
+ stack.push(swapState);
1777
+ stack.push("INSIDE_NUMBER");
1778
+ break;
1779
+ }
1780
+ case "{": {
1781
+ lastValidIndex = i;
1782
+ stack.pop();
1783
+ stack.push(swapState);
1784
+ stack.push("INSIDE_OBJECT_START");
1785
+ break;
1786
+ }
1787
+ case "[": {
1788
+ lastValidIndex = i;
1789
+ stack.pop();
1790
+ stack.push(swapState);
1791
+ stack.push("INSIDE_ARRAY_START");
1792
+ break;
1793
+ }
1794
+ }
1795
+ }
1796
+ }
1797
+ function processAfterObjectValue(char, i) {
1798
+ switch (char) {
1799
+ case ",": {
1800
+ stack.pop();
1801
+ stack.push("INSIDE_OBJECT_AFTER_COMMA");
1802
+ break;
1803
+ }
1804
+ case "}": {
1805
+ lastValidIndex = i;
1806
+ stack.pop();
1807
+ break;
1808
+ }
1809
+ }
1810
+ }
1811
+ function processAfterArrayValue(char, i) {
1812
+ switch (char) {
1813
+ case ",": {
1814
+ stack.pop();
1815
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
1816
+ break;
1817
+ }
1818
+ case "]": {
1819
+ lastValidIndex = i;
1820
+ stack.pop();
1821
+ break;
1822
+ }
1823
+ }
1824
+ }
1825
+ for (let i = 0; i < input.length; i++) {
1826
+ const char = input[i];
1827
+ const currentState = stack[stack.length - 1];
1828
+ switch (currentState) {
1829
+ case "ROOT":
1830
+ processValueStart(char, i, "FINISH");
1831
+ break;
1832
+ case "INSIDE_OBJECT_START": {
1833
+ switch (char) {
1834
+ case '"': {
1835
+ stack.pop();
1836
+ stack.push("INSIDE_OBJECT_KEY");
1837
+ break;
1838
+ }
1839
+ case "}": {
1840
+ lastValidIndex = i;
1841
+ stack.pop();
1842
+ break;
1843
+ }
1844
+ }
1845
+ break;
1846
+ }
1847
+ case "INSIDE_OBJECT_AFTER_COMMA": {
1848
+ switch (char) {
1849
+ case '"': {
1850
+ stack.pop();
1851
+ stack.push("INSIDE_OBJECT_KEY");
1852
+ break;
1853
+ }
1854
+ }
1855
+ break;
1856
+ }
1857
+ case "INSIDE_OBJECT_KEY": {
1858
+ switch (char) {
1859
+ case '"': {
1860
+ stack.pop();
1861
+ stack.push("INSIDE_OBJECT_AFTER_KEY");
1862
+ break;
1863
+ }
1864
+ }
1865
+ break;
1866
+ }
1867
+ case "INSIDE_OBJECT_AFTER_KEY": {
1868
+ switch (char) {
1869
+ case ":": {
1870
+ stack.pop();
1871
+ stack.push("INSIDE_OBJECT_BEFORE_VALUE");
1872
+ break;
1873
+ }
1874
+ }
1875
+ break;
1876
+ }
1877
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
1878
+ processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
1879
+ break;
1880
+ }
1881
+ case "INSIDE_OBJECT_AFTER_VALUE": {
1882
+ processAfterObjectValue(char, i);
1883
+ break;
1884
+ }
1885
+ case "INSIDE_STRING": {
1886
+ switch (char) {
1887
+ case '"': {
1888
+ stack.pop();
1889
+ lastValidIndex = i;
1890
+ break;
1891
+ }
1892
+ case "\\": {
1893
+ stack.push("INSIDE_STRING_ESCAPE");
1894
+ break;
1895
+ }
1896
+ default: {
1897
+ lastValidIndex = i;
1898
+ }
1899
+ }
1900
+ break;
1901
+ }
1902
+ case "INSIDE_ARRAY_START": {
1903
+ switch (char) {
1904
+ case "]": {
1905
+ lastValidIndex = i;
1906
+ stack.pop();
1907
+ break;
1908
+ }
1909
+ default: {
1910
+ lastValidIndex = i;
1911
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
1912
+ break;
1913
+ }
1914
+ }
1915
+ break;
1916
+ }
1917
+ case "INSIDE_ARRAY_AFTER_VALUE": {
1918
+ switch (char) {
1919
+ case ",": {
1920
+ stack.pop();
1921
+ stack.push("INSIDE_ARRAY_AFTER_COMMA");
1922
+ break;
1923
+ }
1924
+ case "]": {
1925
+ lastValidIndex = i;
1926
+ stack.pop();
1927
+ break;
1928
+ }
1929
+ default: {
1930
+ lastValidIndex = i;
1931
+ break;
1932
+ }
1933
+ }
1934
+ break;
1935
+ }
1936
+ case "INSIDE_ARRAY_AFTER_COMMA": {
1937
+ processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
1938
+ break;
1939
+ }
1940
+ case "INSIDE_STRING_ESCAPE": {
1941
+ stack.pop();
1942
+ lastValidIndex = i;
1943
+ break;
1944
+ }
1945
+ case "INSIDE_NUMBER": {
1946
+ switch (char) {
1947
+ case "0":
1948
+ case "1":
1949
+ case "2":
1950
+ case "3":
1951
+ case "4":
1952
+ case "5":
1953
+ case "6":
1954
+ case "7":
1955
+ case "8":
1956
+ case "9": {
1957
+ lastValidIndex = i;
1958
+ break;
1959
+ }
1960
+ case "e":
1961
+ case "E":
1962
+ case "-":
1963
+ case ".": {
1964
+ break;
1965
+ }
1966
+ case ",": {
1967
+ stack.pop();
1968
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1969
+ processAfterArrayValue(char, i);
1970
+ }
1971
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1972
+ processAfterObjectValue(char, i);
1973
+ }
1974
+ break;
1975
+ }
1976
+ case "}": {
1977
+ stack.pop();
1978
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
1979
+ processAfterObjectValue(char, i);
1980
+ }
1981
+ break;
1982
+ }
1983
+ case "]": {
1984
+ stack.pop();
1985
+ if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
1986
+ processAfterArrayValue(char, i);
1987
+ }
1988
+ break;
1989
+ }
1990
+ default: {
1991
+ stack.pop();
1992
+ break;
1993
+ }
1994
+ }
1995
+ break;
1996
+ }
1997
+ case "INSIDE_LITERAL": {
1998
+ const partialLiteral = input.substring(literalStart, i + 1);
1999
+ if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
2000
+ stack.pop();
2001
+ if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
2002
+ processAfterObjectValue(char, i);
2003
+ } else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
2004
+ processAfterArrayValue(char, i);
2005
+ }
2006
+ } else {
2007
+ lastValidIndex = i;
2008
+ }
2009
+ break;
2010
+ }
2011
+ }
2012
+ }
2013
+ let result = input.slice(0, lastValidIndex + 1);
2014
+ for (let i = stack.length - 1; i >= 0; i--) {
2015
+ const state = stack[i];
2016
+ switch (state) {
2017
+ case "INSIDE_STRING": {
2018
+ result += '"';
2019
+ break;
2020
+ }
2021
+ case "INSIDE_OBJECT_KEY":
2022
+ case "INSIDE_OBJECT_AFTER_KEY":
2023
+ case "INSIDE_OBJECT_AFTER_COMMA":
2024
+ case "INSIDE_OBJECT_START":
2025
+ case "INSIDE_OBJECT_BEFORE_VALUE":
2026
+ case "INSIDE_OBJECT_AFTER_VALUE": {
2027
+ result += "}";
2028
+ break;
2029
+ }
2030
+ case "INSIDE_ARRAY_START":
2031
+ case "INSIDE_ARRAY_AFTER_COMMA":
2032
+ case "INSIDE_ARRAY_AFTER_VALUE": {
2033
+ result += "]";
2034
+ break;
2035
+ }
2036
+ case "INSIDE_LITERAL": {
2037
+ const partialLiteral = input.substring(literalStart, input.length);
2038
+ if ("true".startsWith(partialLiteral)) {
2039
+ result += "true".slice(partialLiteral.length);
2040
+ } else if ("false".startsWith(partialLiteral)) {
2041
+ result += "false".slice(partialLiteral.length);
2042
+ } else if ("null".startsWith(partialLiteral)) {
2043
+ result += "null".slice(partialLiteral.length);
2044
+ }
2045
+ }
2046
+ }
2047
+ }
2048
+ return result;
2049
+ }
2050
+ async function parsePartialJson(jsonText) {
2051
+ if (jsonText === void 0) {
2052
+ return { value: void 0, state: "undefined-input" };
2053
+ }
2054
+ let result = await safeParseJSON({ text: jsonText });
2055
+ if (result.success) {
2056
+ return { value: result.value, state: "successful-parse" };
2057
+ }
2058
+ result = await safeParseJSON({ text: fixJson(jsonText) });
2059
+ if (result.success) {
2060
+ return { value: result.value, state: "repaired-parse" };
2061
+ }
2062
+ return { value: void 0, state: "failed-parse" };
2063
+ }
2064
+ function isToolUIPart(part) {
2065
+ return part.type.startsWith("tool-");
2066
+ }
2067
+ function getToolName(part) {
2068
+ return part.type.split("-").slice(1).join("-");
2069
+ }
2070
+ function createStreamingUIMessageState({
2071
+ lastMessage,
2072
+ messageId
2073
+ }) {
2074
+ return {
2075
+ message: (lastMessage == null ? void 0 : lastMessage.role) === "assistant" ? lastMessage : {
2076
+ id: messageId,
2077
+ metadata: void 0,
2078
+ role: "assistant",
2079
+ parts: []
2080
+ },
2081
+ activeTextParts: {},
2082
+ activeReasoningParts: {},
2083
+ partialToolCalls: {}
2084
+ };
2085
+ }
2086
+ function processUIMessageStream({
2087
+ stream,
2088
+ messageMetadataSchema,
2089
+ dataPartSchemas,
2090
+ runUpdateMessageJob,
2091
+ onError,
2092
+ onToolCall,
2093
+ onData
2094
+ }) {
2095
+ return stream.pipeThrough(
2096
+ new TransformStream({
2097
+ async transform(chunk, controller) {
2098
+ await runUpdateMessageJob(async ({ state, write }) => {
2099
+ var _a16, _b, _c, _d;
2100
+ function getToolInvocation(toolCallId) {
2101
+ const toolInvocations = state.message.parts.filter(isToolUIPart);
2102
+ const toolInvocation = toolInvocations.find(
2103
+ (invocation) => invocation.toolCallId === toolCallId
2104
+ );
2105
+ if (toolInvocation == null) {
2106
+ throw new Error(
2107
+ "tool-output-error must be preceded by a tool-input-available"
2108
+ );
2109
+ }
2110
+ return toolInvocation;
2111
+ }
2112
+ function getDynamicToolInvocation(toolCallId) {
2113
+ const toolInvocations = state.message.parts.filter(
2114
+ (part) => part.type === "dynamic-tool"
2115
+ );
2116
+ const toolInvocation = toolInvocations.find(
2117
+ (invocation) => invocation.toolCallId === toolCallId
2118
+ );
2119
+ if (toolInvocation == null) {
2120
+ throw new Error(
2121
+ "tool-output-error must be preceded by a tool-input-available"
2122
+ );
2123
+ }
2124
+ return toolInvocation;
2125
+ }
2126
+ function updateToolPart(options) {
2127
+ var _a17;
2128
+ const part = state.message.parts.find(
2129
+ (part2) => isToolUIPart(part2) && part2.toolCallId === options.toolCallId
2130
+ );
2131
+ const anyOptions = options;
2132
+ const anyPart = part;
2133
+ if (part != null) {
2134
+ part.state = options.state;
2135
+ anyPart.input = anyOptions.input;
2136
+ anyPart.output = anyOptions.output;
2137
+ anyPart.errorText = anyOptions.errorText;
2138
+ anyPart.rawInput = anyOptions.rawInput;
2139
+ anyPart.preliminary = anyOptions.preliminary;
2140
+ anyPart.providerExecuted = (_a17 = anyOptions.providerExecuted) != null ? _a17 : part.providerExecuted;
2141
+ if (anyOptions.providerMetadata != null && part.state === "input-available") {
2142
+ part.callProviderMetadata = anyOptions.providerMetadata;
2143
+ }
2144
+ } else {
2145
+ state.message.parts.push({
2146
+ type: `tool-${options.toolName}`,
2147
+ toolCallId: options.toolCallId,
2148
+ state: options.state,
2149
+ input: anyOptions.input,
2150
+ output: anyOptions.output,
2151
+ rawInput: anyOptions.rawInput,
2152
+ errorText: anyOptions.errorText,
2153
+ providerExecuted: anyOptions.providerExecuted,
2154
+ preliminary: anyOptions.preliminary,
2155
+ ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
2156
+ });
2157
+ }
2158
+ }
2159
+ function updateDynamicToolPart(options) {
2160
+ var _a17, _b2;
2161
+ const part = state.message.parts.find(
2162
+ (part2) => part2.type === "dynamic-tool" && part2.toolCallId === options.toolCallId
2163
+ );
2164
+ const anyOptions = options;
2165
+ const anyPart = part;
2166
+ if (part != null) {
2167
+ part.state = options.state;
2168
+ anyPart.toolName = options.toolName;
2169
+ anyPart.input = anyOptions.input;
2170
+ anyPart.output = anyOptions.output;
2171
+ anyPart.errorText = anyOptions.errorText;
2172
+ anyPart.rawInput = (_a17 = anyOptions.rawInput) != null ? _a17 : anyPart.rawInput;
2173
+ anyPart.preliminary = anyOptions.preliminary;
2174
+ anyPart.providerExecuted = (_b2 = anyOptions.providerExecuted) != null ? _b2 : part.providerExecuted;
2175
+ if (anyOptions.providerMetadata != null && part.state === "input-available") {
2176
+ part.callProviderMetadata = anyOptions.providerMetadata;
2177
+ }
2178
+ } else {
2179
+ state.message.parts.push({
2180
+ type: "dynamic-tool",
2181
+ toolName: options.toolName,
2182
+ toolCallId: options.toolCallId,
2183
+ state: options.state,
2184
+ input: anyOptions.input,
2185
+ output: anyOptions.output,
2186
+ errorText: anyOptions.errorText,
2187
+ preliminary: anyOptions.preliminary,
2188
+ providerExecuted: anyOptions.providerExecuted,
2189
+ ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
2190
+ });
2191
+ }
2192
+ }
2193
+ async function updateMessageMetadata(metadata) {
2194
+ if (metadata != null) {
2195
+ const mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;
2196
+ if (messageMetadataSchema != null) {
2197
+ await validateTypes({
2198
+ value: mergedMetadata,
2199
+ schema: messageMetadataSchema
2200
+ });
2201
+ }
2202
+ state.message.metadata = mergedMetadata;
2203
+ }
2204
+ }
2205
+ switch (chunk.type) {
2206
+ case "text-start": {
2207
+ const textPart = {
2208
+ type: "text",
2209
+ text: "",
2210
+ providerMetadata: chunk.providerMetadata,
2211
+ state: "streaming"
2212
+ };
2213
+ state.activeTextParts[chunk.id] = textPart;
2214
+ state.message.parts.push(textPart);
2215
+ write();
2216
+ break;
2217
+ }
2218
+ case "text-delta": {
2219
+ const textPart = state.activeTextParts[chunk.id];
2220
+ textPart.text += chunk.delta;
2221
+ textPart.providerMetadata = (_a16 = chunk.providerMetadata) != null ? _a16 : textPart.providerMetadata;
2222
+ write();
2223
+ break;
2224
+ }
2225
+ case "text-end": {
2226
+ const textPart = state.activeTextParts[chunk.id];
2227
+ textPart.state = "done";
2228
+ textPart.providerMetadata = (_b = chunk.providerMetadata) != null ? _b : textPart.providerMetadata;
2229
+ delete state.activeTextParts[chunk.id];
2230
+ write();
2231
+ break;
2232
+ }
2233
+ case "reasoning-start": {
2234
+ const reasoningPart = {
2235
+ type: "reasoning",
2236
+ text: "",
2237
+ providerMetadata: chunk.providerMetadata,
2238
+ state: "streaming"
2239
+ };
2240
+ state.activeReasoningParts[chunk.id] = reasoningPart;
2241
+ state.message.parts.push(reasoningPart);
2242
+ write();
2243
+ break;
2244
+ }
2245
+ case "reasoning-delta": {
2246
+ const reasoningPart = state.activeReasoningParts[chunk.id];
2247
+ reasoningPart.text += chunk.delta;
2248
+ reasoningPart.providerMetadata = (_c = chunk.providerMetadata) != null ? _c : reasoningPart.providerMetadata;
2249
+ write();
2250
+ break;
2251
+ }
2252
+ case "reasoning-end": {
2253
+ const reasoningPart = state.activeReasoningParts[chunk.id];
2254
+ reasoningPart.providerMetadata = (_d = chunk.providerMetadata) != null ? _d : reasoningPart.providerMetadata;
2255
+ reasoningPart.state = "done";
2256
+ delete state.activeReasoningParts[chunk.id];
2257
+ write();
2258
+ break;
2259
+ }
2260
+ case "file": {
2261
+ state.message.parts.push({
2262
+ type: "file",
2263
+ mediaType: chunk.mediaType,
2264
+ url: chunk.url
2265
+ });
2266
+ write();
2267
+ break;
2268
+ }
2269
+ case "source-url": {
2270
+ state.message.parts.push({
2271
+ type: "source-url",
2272
+ sourceId: chunk.sourceId,
2273
+ url: chunk.url,
2274
+ title: chunk.title,
2275
+ providerMetadata: chunk.providerMetadata
2276
+ });
2277
+ write();
2278
+ break;
2279
+ }
2280
+ case "source-document": {
2281
+ state.message.parts.push({
2282
+ type: "source-document",
2283
+ sourceId: chunk.sourceId,
2284
+ mediaType: chunk.mediaType,
2285
+ title: chunk.title,
2286
+ filename: chunk.filename,
2287
+ providerMetadata: chunk.providerMetadata
2288
+ });
2289
+ write();
2290
+ break;
2291
+ }
2292
+ case "tool-input-start": {
2293
+ const toolInvocations = state.message.parts.filter(isToolUIPart);
2294
+ state.partialToolCalls[chunk.toolCallId] = {
2295
+ text: "",
2296
+ toolName: chunk.toolName,
2297
+ index: toolInvocations.length,
2298
+ dynamic: chunk.dynamic
2299
+ };
2300
+ if (chunk.dynamic) {
2301
+ updateDynamicToolPart({
2302
+ toolCallId: chunk.toolCallId,
2303
+ toolName: chunk.toolName,
2304
+ state: "input-streaming",
2305
+ input: void 0,
2306
+ providerExecuted: chunk.providerExecuted
2307
+ });
2308
+ } else {
2309
+ updateToolPart({
2310
+ toolCallId: chunk.toolCallId,
2311
+ toolName: chunk.toolName,
2312
+ state: "input-streaming",
2313
+ input: void 0,
2314
+ providerExecuted: chunk.providerExecuted
2315
+ });
2316
+ }
2317
+ write();
2318
+ break;
2319
+ }
2320
+ case "tool-input-delta": {
2321
+ const partialToolCall = state.partialToolCalls[chunk.toolCallId];
2322
+ partialToolCall.text += chunk.inputTextDelta;
2323
+ const { value: partialArgs } = await parsePartialJson(
2324
+ partialToolCall.text
2325
+ );
2326
+ if (partialToolCall.dynamic) {
2327
+ updateDynamicToolPart({
2328
+ toolCallId: chunk.toolCallId,
2329
+ toolName: partialToolCall.toolName,
2330
+ state: "input-streaming",
2331
+ input: partialArgs
2332
+ });
2333
+ } else {
2334
+ updateToolPart({
2335
+ toolCallId: chunk.toolCallId,
2336
+ toolName: partialToolCall.toolName,
2337
+ state: "input-streaming",
2338
+ input: partialArgs
2339
+ });
2340
+ }
2341
+ write();
2342
+ break;
2343
+ }
2344
+ case "tool-input-available": {
2345
+ if (chunk.dynamic) {
2346
+ updateDynamicToolPart({
2347
+ toolCallId: chunk.toolCallId,
2348
+ toolName: chunk.toolName,
2349
+ state: "input-available",
2350
+ input: chunk.input,
2351
+ providerExecuted: chunk.providerExecuted,
2352
+ providerMetadata: chunk.providerMetadata
2353
+ });
2354
+ } else {
2355
+ updateToolPart({
2356
+ toolCallId: chunk.toolCallId,
2357
+ toolName: chunk.toolName,
2358
+ state: "input-available",
2359
+ input: chunk.input,
2360
+ providerExecuted: chunk.providerExecuted,
2361
+ providerMetadata: chunk.providerMetadata
2362
+ });
2363
+ }
2364
+ write();
2365
+ if (onToolCall && !chunk.providerExecuted) {
2366
+ await onToolCall({
2367
+ toolCall: chunk
2368
+ });
2369
+ }
2370
+ break;
2371
+ }
2372
+ case "tool-input-error": {
2373
+ if (chunk.dynamic) {
2374
+ updateDynamicToolPart({
2375
+ toolCallId: chunk.toolCallId,
2376
+ toolName: chunk.toolName,
2377
+ state: "output-error",
2378
+ input: chunk.input,
2379
+ errorText: chunk.errorText,
2380
+ providerExecuted: chunk.providerExecuted,
2381
+ providerMetadata: chunk.providerMetadata
2382
+ });
2383
+ } else {
2384
+ updateToolPart({
2385
+ toolCallId: chunk.toolCallId,
2386
+ toolName: chunk.toolName,
2387
+ state: "output-error",
2388
+ input: void 0,
2389
+ rawInput: chunk.input,
2390
+ errorText: chunk.errorText,
2391
+ providerExecuted: chunk.providerExecuted,
2392
+ providerMetadata: chunk.providerMetadata
2393
+ });
2394
+ }
2395
+ write();
2396
+ break;
2397
+ }
2398
+ case "tool-output-available": {
2399
+ if (chunk.dynamic) {
2400
+ const toolInvocation = getDynamicToolInvocation(
2401
+ chunk.toolCallId
2402
+ );
2403
+ updateDynamicToolPart({
2404
+ toolCallId: chunk.toolCallId,
2405
+ toolName: toolInvocation.toolName,
2406
+ state: "output-available",
2407
+ input: toolInvocation.input,
2408
+ output: chunk.output,
2409
+ preliminary: chunk.preliminary
2410
+ });
2411
+ } else {
2412
+ const toolInvocation = getToolInvocation(chunk.toolCallId);
2413
+ updateToolPart({
2414
+ toolCallId: chunk.toolCallId,
2415
+ toolName: getToolName(toolInvocation),
2416
+ state: "output-available",
2417
+ input: toolInvocation.input,
2418
+ output: chunk.output,
2419
+ providerExecuted: chunk.providerExecuted,
2420
+ preliminary: chunk.preliminary
2421
+ });
2422
+ }
2423
+ write();
2424
+ break;
2425
+ }
2426
+ case "tool-output-error": {
2427
+ if (chunk.dynamic) {
2428
+ const toolInvocation = getDynamicToolInvocation(
2429
+ chunk.toolCallId
2430
+ );
2431
+ updateDynamicToolPart({
2432
+ toolCallId: chunk.toolCallId,
2433
+ toolName: toolInvocation.toolName,
2434
+ state: "output-error",
2435
+ input: toolInvocation.input,
2436
+ errorText: chunk.errorText,
2437
+ providerExecuted: chunk.providerExecuted
2438
+ });
2439
+ } else {
2440
+ const toolInvocation = getToolInvocation(chunk.toolCallId);
2441
+ updateToolPart({
2442
+ toolCallId: chunk.toolCallId,
2443
+ toolName: getToolName(toolInvocation),
2444
+ state: "output-error",
2445
+ input: toolInvocation.input,
2446
+ rawInput: toolInvocation.rawInput,
2447
+ errorText: chunk.errorText,
2448
+ providerExecuted: chunk.providerExecuted
2449
+ });
2450
+ }
2451
+ write();
2452
+ break;
2453
+ }
2454
+ case "start-step": {
2455
+ state.message.parts.push({ type: "step-start" });
2456
+ break;
2457
+ }
2458
+ case "finish-step": {
2459
+ state.activeTextParts = {};
2460
+ state.activeReasoningParts = {};
2461
+ break;
2462
+ }
2463
+ case "start": {
2464
+ if (chunk.messageId != null) {
2465
+ state.message.id = chunk.messageId;
2466
+ }
2467
+ await updateMessageMetadata(chunk.messageMetadata);
2468
+ if (chunk.messageId != null || chunk.messageMetadata != null) {
2469
+ write();
2470
+ }
2471
+ break;
2472
+ }
2473
+ case "finish": {
2474
+ if (chunk.finishReason != null) {
2475
+ state.finishReason = chunk.finishReason;
2476
+ }
2477
+ await updateMessageMetadata(chunk.messageMetadata);
2478
+ if (chunk.messageMetadata != null) {
2479
+ write();
2480
+ }
2481
+ break;
2482
+ }
2483
+ case "message-metadata": {
2484
+ await updateMessageMetadata(chunk.messageMetadata);
2485
+ if (chunk.messageMetadata != null) {
2486
+ write();
2487
+ }
2488
+ break;
2489
+ }
2490
+ case "error": {
2491
+ onError == null ? void 0 : onError(new Error(chunk.errorText));
2492
+ break;
2493
+ }
2494
+ default: {
2495
+ if (isDataUIMessageChunk(chunk)) {
2496
+ if ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk.type]) != null) {
2497
+ await validateTypes({
2498
+ value: chunk.data,
2499
+ schema: dataPartSchemas[chunk.type]
2500
+ });
2501
+ }
2502
+ const dataChunk = chunk;
2503
+ if (dataChunk.transient) {
2504
+ onData == null ? void 0 : onData(dataChunk);
2505
+ break;
2506
+ }
2507
+ const existingUIPart = dataChunk.id != null ? state.message.parts.find(
2508
+ (chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id
2509
+ ) : void 0;
2510
+ if (existingUIPart != null) {
2511
+ existingUIPart.data = dataChunk.data;
2512
+ } else {
2513
+ state.message.parts.push(dataChunk);
2514
+ }
2515
+ onData == null ? void 0 : onData(dataChunk);
2516
+ write();
2517
+ }
2518
+ }
2519
+ }
2520
+ controller.enqueue(chunk);
2521
+ });
2522
+ }
2523
+ })
2524
+ );
2525
+ }
2526
+ function handleUIMessageStreamFinish({
2527
+ messageId,
2528
+ originalMessages = [],
2529
+ onFinish,
2530
+ onError,
2531
+ stream
2532
+ }) {
2533
+ let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];
2534
+ if ((lastMessage == null ? void 0 : lastMessage.role) !== "assistant") {
2535
+ lastMessage = void 0;
2536
+ } else {
2537
+ messageId = lastMessage.id;
2538
+ }
2539
+ let isAborted = false;
2540
+ const idInjectedStream = stream.pipeThrough(
2541
+ new TransformStream({
2542
+ transform(chunk, controller) {
2543
+ if (chunk.type === "start") {
2544
+ const startChunk = chunk;
2545
+ if (startChunk.messageId == null && messageId != null) {
2546
+ startChunk.messageId = messageId;
2547
+ }
2548
+ }
2549
+ if (chunk.type === "abort") {
2550
+ isAborted = true;
2551
+ }
2552
+ controller.enqueue(chunk);
2553
+ }
2554
+ })
2555
+ );
2556
+ if (onFinish == null) {
2557
+ return idInjectedStream;
2558
+ }
2559
+ const state = createStreamingUIMessageState({
2560
+ lastMessage: lastMessage ? structuredClone(lastMessage) : void 0,
2561
+ messageId: messageId != null ? messageId : ""
2562
+ // will be overridden by the stream
2563
+ });
2564
+ const runUpdateMessageJob = async (job) => {
2565
+ await job({ state, write: () => {
2566
+ } });
2567
+ };
2568
+ let finishCalled = false;
2569
+ const callOnFinish = async () => {
2570
+ if (finishCalled || !onFinish) {
2571
+ return;
2572
+ }
2573
+ finishCalled = true;
2574
+ const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
2575
+ await onFinish({
2576
+ isAborted,
2577
+ isContinuation,
2578
+ responseMessage: state.message,
2579
+ messages: [
2580
+ ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,
2581
+ state.message
2582
+ ],
2583
+ finishReason: state.finishReason
2584
+ });
2585
+ };
2586
+ return processUIMessageStream({
2587
+ stream: idInjectedStream,
2588
+ runUpdateMessageJob,
2589
+ onError
2590
+ }).pipeThrough(
2591
+ new TransformStream({
2592
+ transform(chunk, controller) {
2593
+ controller.enqueue(chunk);
2594
+ },
2595
+ // @ts-expect-error cancel is still new and missing from types https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility
2596
+ async cancel() {
2597
+ await callOnFinish();
2598
+ },
2599
+ async flush() {
2600
+ await callOnFinish();
2601
+ }
2602
+ })
2603
+ );
2604
+ }
2605
+ createIdGenerator({
2606
+ prefix: "aitxt",
2607
+ size: 24
2608
+ });
2609
+ createIdGenerator({ prefix: "aiobj", size: 24 });
2610
+ createIdGenerator({ prefix: "aiobj", size: 24 });
2611
+ var output_exports = {};
2612
+ __export(output_exports, {
2613
+ object: () => object,
2614
+ text: () => text
2615
+ });
2616
+ var text = () => ({
2617
+ type: "text",
2618
+ responseFormat: { type: "text" },
2619
+ async parsePartial({ text: text2 }) {
2620
+ return { partial: text2 };
2621
+ },
2622
+ async parseOutput({ text: text2 }) {
2623
+ return text2;
2624
+ }
2625
+ });
2626
+ var object = ({
2627
+ schema: inputSchema
2628
+ }) => {
2629
+ const schema = asSchema(inputSchema);
2630
+ return {
2631
+ type: "object",
2632
+ responseFormat: {
2633
+ type: "json",
2634
+ schema: schema.jsonSchema
2635
+ },
2636
+ async parsePartial({ text: text2 }) {
2637
+ const result = await parsePartialJson(text2);
2638
+ switch (result.state) {
2639
+ case "failed-parse":
2640
+ case "undefined-input":
2641
+ return void 0;
2642
+ case "repaired-parse":
2643
+ case "successful-parse":
2644
+ return {
2645
+ // Note: currently no validation of partial results:
2646
+ partial: result.value
2647
+ };
2648
+ default: {
2649
+ const _exhaustiveCheck = result.state;
2650
+ throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
2651
+ }
2652
+ }
2653
+ },
2654
+ async parseOutput({ text: text2 }, context) {
2655
+ const parseResult = await safeParseJSON({ text: text2 });
2656
+ if (!parseResult.success) {
2657
+ throw new NoObjectGeneratedError({
2658
+ message: "No object generated: could not parse the response.",
2659
+ cause: parseResult.error,
2660
+ text: text2,
2661
+ response: context.response,
2662
+ usage: context.usage,
2663
+ finishReason: context.finishReason
2664
+ });
2665
+ }
2666
+ const validationResult = await safeValidateTypes({
2667
+ value: parseResult.value,
2668
+ schema
2669
+ });
2670
+ if (!validationResult.success) {
2671
+ throw new NoObjectGeneratedError({
2672
+ message: "No object generated: response did not match schema.",
2673
+ cause: validationResult.error,
2674
+ text: text2,
2675
+ response: context.response,
2676
+ usage: context.usage,
2677
+ finishReason: context.finishReason
2678
+ });
2679
+ }
2680
+ return validationResult.value;
2681
+ }
2682
+ };
2683
+ };
2684
+ var wrapLanguageModel = ({
2685
+ model,
2686
+ middleware: middlewareArg,
2687
+ modelId,
2688
+ providerId
2689
+ }) => {
2690
+ return [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {
2691
+ return doWrap({ model: wrappedModel, middleware, modelId, providerId });
2692
+ }, model);
2693
+ };
2694
+ var doWrap = ({
2695
+ model,
2696
+ middleware: {
2697
+ transformParams,
2698
+ wrapGenerate,
2699
+ wrapStream,
2700
+ overrideProvider,
2701
+ overrideModelId,
2702
+ overrideSupportedUrls
2703
+ },
2704
+ modelId,
2705
+ providerId
2706
+ }) => {
2707
+ var _a16, _b, _c;
2708
+ async function doTransform({
2709
+ params,
2710
+ type
2711
+ }) {
2712
+ return transformParams ? await transformParams({ params, type, model }) : params;
2713
+ }
2714
+ return {
2715
+ specificationVersion: "v2",
2716
+ provider: (_a16 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a16 : model.provider,
2717
+ modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
2718
+ supportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,
2719
+ async doGenerate(params) {
2720
+ const transformedParams = await doTransform({ params, type: "generate" });
2721
+ const doGenerate = async () => model.doGenerate(transformedParams);
2722
+ const doStream = async () => model.doStream(transformedParams);
2723
+ return wrapGenerate ? wrapGenerate({
2724
+ doGenerate,
2725
+ doStream,
2726
+ params: transformedParams,
2727
+ model
2728
+ }) : doGenerate();
2729
+ },
2730
+ async doStream(params) {
2731
+ const transformedParams = await doTransform({ params, type: "stream" });
2732
+ const doGenerate = async () => model.doGenerate(transformedParams);
2733
+ const doStream = async () => model.doStream(transformedParams);
2734
+ return wrapStream ? wrapStream({ doGenerate, doStream, params: transformedParams, model }) : doStream();
2735
+ }
2736
+ };
2737
+ };
2738
+ function createUIMessageStream({
2739
+ execute,
2740
+ onError = getErrorMessage2,
2741
+ originalMessages,
2742
+ onFinish,
2743
+ generateId: generateId3 = generateId
2744
+ }) {
2745
+ let controller;
2746
+ const ongoingStreamPromises = [];
2747
+ const stream = new ReadableStream({
2748
+ start(controllerArg) {
2749
+ controller = controllerArg;
2750
+ }
2751
+ });
2752
+ function safeEnqueue(data) {
2753
+ try {
2754
+ controller.enqueue(data);
2755
+ } catch (error) {
2756
+ }
2757
+ }
2758
+ try {
2759
+ const result = execute({
2760
+ writer: {
2761
+ write(part) {
2762
+ safeEnqueue(part);
2763
+ },
2764
+ merge(streamArg) {
2765
+ ongoingStreamPromises.push(
2766
+ (async () => {
2767
+ const reader = streamArg.getReader();
2768
+ while (true) {
2769
+ const { done, value } = await reader.read();
2770
+ if (done)
2771
+ break;
2772
+ safeEnqueue(value);
2773
+ }
2774
+ })().catch((error) => {
2775
+ safeEnqueue({
2776
+ type: "error",
2777
+ errorText: onError(error)
2778
+ });
2779
+ })
2780
+ );
2781
+ },
2782
+ onError
2783
+ }
2784
+ });
2785
+ if (result) {
2786
+ ongoingStreamPromises.push(
2787
+ result.catch((error) => {
2788
+ safeEnqueue({
2789
+ type: "error",
2790
+ errorText: onError(error)
2791
+ });
2792
+ })
2793
+ );
2794
+ }
2795
+ } catch (error) {
2796
+ safeEnqueue({
2797
+ type: "error",
2798
+ errorText: onError(error)
2799
+ });
2800
+ }
2801
+ const waitForStreams = new Promise(async (resolve2) => {
2802
+ while (ongoingStreamPromises.length > 0) {
2803
+ await ongoingStreamPromises.shift();
2804
+ }
2805
+ resolve2();
2806
+ });
2807
+ waitForStreams.finally(() => {
2808
+ try {
2809
+ controller.close();
2810
+ } catch (error) {
2811
+ }
2812
+ });
2813
+ return handleUIMessageStreamFinish({
2814
+ stream,
2815
+ messageId: generateId3(),
2816
+ originalMessages,
2817
+ onFinish,
2818
+ onError
2819
+ });
2820
+ }
8
2821
 
9
2822
  // src/utils.ts
10
2823
  var isDataChunkType = (chunk) => {
@@ -22,6 +2835,8 @@ var isMastraTextStreamChunk = (chunk) => {
22
2835
  "source",
23
2836
  "tool-input-start",
24
2837
  "tool-input-delta",
2838
+ "tool-call-approval",
2839
+ "tool-call-suspended",
25
2840
  "tool-call",
26
2841
  "tool-result",
27
2842
  "tool-error",
@@ -32,6 +2847,8 @@ var isMastraTextStreamChunk = (chunk) => {
32
2847
  "finish",
33
2848
  "abort",
34
2849
  "tool-input-end",
2850
+ "object",
2851
+ "tripwire",
35
2852
  "raw"
36
2853
  ].includes(chunk.type);
37
2854
  };
@@ -57,6 +2874,12 @@ var isWorkflowExecutionDataChunkType = (chunk) => {
57
2874
  };
58
2875
 
59
2876
  // src/helpers.ts
2877
+ function toAISDKFinishReason(reason) {
2878
+ if (reason === "tripwire" || reason === "retry") {
2879
+ return "other";
2880
+ }
2881
+ return reason;
2882
+ }
60
2883
  function convertMastraChunkToAISDKv5({
61
2884
  chunk,
62
2885
  mode = "stream"
@@ -64,7 +2887,9 @@ function convertMastraChunkToAISDKv5({
64
2887
  switch (chunk.type) {
65
2888
  case "start":
66
2889
  return {
67
- type: "start"
2890
+ type: "start",
2891
+ // Preserve messageId from the payload so it can be sent to useChat
2892
+ ...chunk.payload?.messageId ? { messageId: chunk.payload.messageId } : {}
68
2893
  };
69
2894
  case "step-start":
70
2895
  const { messageId: _messageId, ...rest } = chunk.payload;
@@ -81,7 +2906,8 @@ function convertMastraChunkToAISDKv5({
81
2906
  case "finish": {
82
2907
  return {
83
2908
  type: "finish",
84
- finishReason: chunk.payload.stepResult.reason,
2909
+ finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
2910
+ // Cast needed: Mastra's LanguageModelUsage has optional properties, AI SDK has required-but-nullable
85
2911
  totalUsage: chunk.payload.output.usage
86
2912
  };
87
2913
  }
@@ -173,7 +2999,8 @@ function convertMastraChunkToAISDKv5({
173
2999
  runId: chunk.runId,
174
3000
  toolCallId: chunk.payload.toolCallId,
175
3001
  toolName: chunk.payload.toolName,
176
- args: chunk.payload.args
3002
+ args: chunk.payload.args,
3003
+ resumeSchema: chunk.payload.resumeSchema
177
3004
  }
178
3005
  };
179
3006
  case "tool-call-suspended":
@@ -184,7 +3011,8 @@ function convertMastraChunkToAISDKv5({
184
3011
  runId: chunk.runId,
185
3012
  toolCallId: chunk.payload.toolCallId,
186
3013
  toolName: chunk.payload.toolName,
187
- suspendPayload: chunk.payload.suspendPayload
3014
+ suspendPayload: chunk.payload.suspendPayload,
3015
+ resumeSchema: chunk.payload.resumeSchema
188
3016
  }
189
3017
  };
190
3018
  case "tool-call-input-streaming-start":
@@ -220,7 +3048,7 @@ function convertMastraChunkToAISDKv5({
220
3048
  ...rest2
221
3049
  },
222
3050
  usage: chunk.payload.output.usage,
223
- finishReason: chunk.payload.stepResult.reason,
3051
+ finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
224
3052
  providerMetadata
225
3053
  };
226
3054
  }
@@ -281,7 +3109,10 @@ function convertMastraChunkToAISDKv5({
281
3109
  return {
282
3110
  type: "data-tripwire",
283
3111
  data: {
284
- tripwireReason: chunk.payload.tripwireReason
3112
+ reason: chunk.payload.reason,
3113
+ retry: chunk.payload.retry,
3114
+ metadata: chunk.payload.metadata,
3115
+ processorId: chunk.payload.processorId
285
3116
  }
286
3117
  };
287
3118
  default:
@@ -447,7 +3278,8 @@ function convertFullStreamChunkToUIMessageStream({
447
3278
  ${JSON.stringify(part)}`
448
3279
  );
449
3280
  }
450
- return part.output;
3281
+ const { type, data, id } = part.output;
3282
+ return { type, data, ...id !== void 0 && { id } };
451
3283
  }
452
3284
  return;
453
3285
  }
@@ -474,10 +3306,11 @@ function convertFullStreamChunkToUIMessageStream({
474
3306
  }
475
3307
  case "start": {
476
3308
  if (sendStart) {
3309
+ const messageId = ("messageId" in part ? part.messageId : void 0) || responseMessageId;
477
3310
  return {
478
3311
  type: "start",
479
3312
  ...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},
480
- ...responseMessageId != null ? { messageId: responseMessageId } : {}
3313
+ ...messageId != null ? { messageId } : {}
481
3314
  };
482
3315
  }
483
3316
  return;
@@ -508,7 +3341,8 @@ function convertFullStreamChunkToUIMessageStream({
508
3341
  ${JSON.stringify(part)}`
509
3342
  );
510
3343
  }
511
- return part;
3344
+ const { type, data, id } = part;
3345
+ return { type, data, ...id !== void 0 && { id } };
512
3346
  }
513
3347
  return;
514
3348
  }
@@ -553,7 +3387,15 @@ function AgentNetworkToAISDKTransformer() {
553
3387
  },
554
3388
  transform(chunk, controller) {
555
3389
  const transformed = transformNetwork(chunk, bufferedNetworks);
556
- if (transformed) controller.enqueue(transformed);
3390
+ if (transformed) {
3391
+ if (Array.isArray(transformed)) {
3392
+ for (const item of transformed) {
3393
+ controller.enqueue(item);
3394
+ }
3395
+ } else {
3396
+ controller.enqueue(transformed);
3397
+ }
3398
+ }
557
3399
  }
558
3400
  });
559
3401
  }
@@ -866,7 +3708,8 @@ function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStre
866
3708
  ${JSON.stringify(output)}`
867
3709
  );
868
3710
  }
869
- return output;
3711
+ const { type, data, id } = output;
3712
+ return { type, data, ...id !== void 0 && { id } };
870
3713
  }
871
3714
  return null;
872
3715
  }
@@ -878,7 +3721,12 @@ function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStre
878
3721
  ${JSON.stringify(payload)}`
879
3722
  );
880
3723
  }
881
- return payload;
3724
+ const { type, data, id } = payload;
3725
+ return {
3726
+ type,
3727
+ data,
3728
+ ...id !== void 0 && { id }
3729
+ };
882
3730
  }
883
3731
  return null;
884
3732
  }
@@ -892,7 +3740,8 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
892
3740
  name: payload.payload.networkId,
893
3741
  steps: [],
894
3742
  usage: null,
895
- output: null
3743
+ output: null,
3744
+ hasEmittedText: false
896
3745
  });
897
3746
  }
898
3747
  const current = bufferedNetworks.get(payload.runId);
@@ -927,6 +3776,7 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
927
3776
  case "routing-agent-text-start": {
928
3777
  const current = bufferedNetworks.get(payload.runId);
929
3778
  if (!current) return null;
3779
+ current.hasEmittedText = true;
930
3780
  return {
931
3781
  type: "text-start",
932
3782
  id: payload.runId
@@ -935,6 +3785,7 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
935
3785
  case "routing-agent-text-delta": {
936
3786
  const current = bufferedNetworks.get(payload.runId);
937
3787
  if (!current) return null;
3788
+ current.hasEmittedText = true;
938
3789
  return {
939
3790
  type: "text-delta",
940
3791
  id: payload.runId,
@@ -1109,15 +3960,25 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
1109
3960
  case "network-execution-event-step-finish": {
1110
3961
  const current = bufferedNetworks.get(payload.runId);
1111
3962
  if (!current) return null;
1112
- return {
3963
+ const resultText = payload.payload?.result;
3964
+ const dataNetworkChunk = {
1113
3965
  type: isNested ? "data-tool-network" : "data-network",
1114
3966
  id: payload.runId,
1115
3967
  data: {
1116
3968
  ...current,
1117
3969
  status: "finished",
1118
- output: payload.payload?.result ?? current.output
3970
+ output: resultText ?? current.output
1119
3971
  }
1120
3972
  };
3973
+ if (!current.hasEmittedText && resultText && typeof resultText === "string" && resultText.length > 0) {
3974
+ current.hasEmittedText = true;
3975
+ return [
3976
+ { type: "text-start", id: payload.runId },
3977
+ { type: "text-delta", id: payload.runId, delta: resultText },
3978
+ dataNetworkChunk
3979
+ ];
3980
+ }
3981
+ return dataNetworkChunk;
1121
3982
  }
1122
3983
  case "network-execution-event-finish": {
1123
3984
  const current = bufferedNetworks.get(payload.runId);
@@ -1134,6 +3995,26 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
1134
3995
  };
1135
3996
  }
1136
3997
  default: {
3998
+ if (isAgentExecutionDataChunkType(payload)) {
3999
+ if (!("data" in payload.payload)) {
4000
+ throw new Error(
4001
+ `UI Messages require a data property when using data- prefixed chunks
4002
+ ${JSON.stringify(payload)}`
4003
+ );
4004
+ }
4005
+ const { type, data, id } = payload.payload;
4006
+ return { type, data, ...id !== void 0 && { id } };
4007
+ }
4008
+ if (isWorkflowExecutionDataChunkType(payload)) {
4009
+ if (!("data" in payload.payload)) {
4010
+ throw new Error(
4011
+ `UI Messages require a data property when using data- prefixed chunks
4012
+ ${JSON.stringify(payload)}`
4013
+ );
4014
+ }
4015
+ const { type, data, id } = payload.payload;
4016
+ return { type, data, ...id !== void 0 && { id } };
4017
+ }
1137
4018
  if (payload.type.startsWith("agent-execution-event-")) {
1138
4019
  const stepId = payload.payload.runId;
1139
4020
  const current = bufferedNetworks.get(payload.runId);
@@ -1148,6 +4029,15 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
1148
4029
  const { request, response, ...data } = result.data;
1149
4030
  step.task = data;
1150
4031
  }
4032
+ bufferedNetworks.set(payload.runId, current);
4033
+ return {
4034
+ type: isNested ? "data-tool-network" : "data-network",
4035
+ id: payload.runId,
4036
+ data: {
4037
+ ...current,
4038
+ status: "running"
4039
+ }
4040
+ };
1151
4041
  }
1152
4042
  if (payload.type.startsWith("workflow-execution-event-")) {
1153
4043
  const stepId = payload.payload.runId;
@@ -1166,6 +4056,15 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
1166
4056
  step.task.id = data.name;
1167
4057
  }
1168
4058
  }
4059
+ bufferedNetworks.set(payload.runId, current);
4060
+ return {
4061
+ type: isNested ? "data-tool-network" : "data-network",
4062
+ id: payload.runId,
4063
+ data: {
4064
+ ...current,
4065
+ status: "running"
4066
+ }
4067
+ };
1169
4068
  }
1170
4069
  if (isDataChunkType(payload)) {
1171
4070
  if (!("data" in payload)) {
@@ -1174,28 +4073,8 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
1174
4073
  ${JSON.stringify(payload)}`
1175
4074
  );
1176
4075
  }
1177
- const { type, data } = payload;
1178
- return { type, data };
1179
- }
1180
- if (isAgentExecutionDataChunkType(payload)) {
1181
- if (!("data" in payload.payload)) {
1182
- throw new Error(
1183
- `UI Messages require a data property when using data- prefixed chunks
1184
- ${JSON.stringify(payload)}`
1185
- );
1186
- }
1187
- const { type, data } = payload.payload;
1188
- return { type, data };
1189
- }
1190
- if (isWorkflowExecutionDataChunkType(payload)) {
1191
- if (!("data" in payload.payload)) {
1192
- throw new Error(
1193
- `UI Messages require a data property when using data- prefixed chunks
1194
- ${JSON.stringify(payload)}`
1195
- );
1196
- }
1197
- const { type, data } = payload.payload;
1198
- return { type, data };
4076
+ const { type, data, id } = payload;
4077
+ return { type, data, ...id !== void 0 && { id } };
1199
4078
  }
1200
4079
  return null;
1201
4080
  }
@@ -1237,7 +4116,7 @@ async function handleChatStream({
1237
4116
  mastra,
1238
4117
  agentId,
1239
4118
  params,
1240
- defaultOptions,
4119
+ defaultOptions: defaultOptions2,
1241
4120
  sendStart = true,
1242
4121
  sendFinish = true,
1243
4122
  sendReasoning = false,
@@ -1255,10 +4134,10 @@ async function handleChatStream({
1255
4134
  throw new Error("Messages must be an array of UIMessage objects");
1256
4135
  }
1257
4136
  const mergedOptions = {
1258
- ...defaultOptions,
4137
+ ...defaultOptions2,
1259
4138
  ...rest,
1260
4139
  ...runId && { runId },
1261
- requestContext: requestContext || defaultOptions?.requestContext
4140
+ requestContext: requestContext || defaultOptions2?.requestContext
1262
4141
  };
1263
4142
  const result = resumeData ? await agentObj.resumeStream(resumeData, mergedOptions) : await agentObj.stream(messages, mergedOptions);
1264
4143
  let lastMessageId;
@@ -1268,7 +4147,7 @@ async function handleChatStream({
1268
4147
  lastMessageId = lastMessage.id;
1269
4148
  }
1270
4149
  }
1271
- return ai.createUIMessageStream({
4150
+ return createUIMessageStream({
1272
4151
  originalMessages: messages,
1273
4152
  execute: async ({ writer }) => {
1274
4153
  for await (const part of toAISdkV5Stream(result, {
@@ -1287,7 +4166,7 @@ async function handleChatStream({
1287
4166
  function chatRoute({
1288
4167
  path = "/chat/:agentId",
1289
4168
  agent,
1290
- defaultOptions,
4169
+ defaultOptions: defaultOptions2,
1291
4170
  sendStart = true,
1292
4171
  sendFinish = true,
1293
4172
  sendReasoning = false,
@@ -1411,8 +4290,9 @@ function chatRoute({
1411
4290
  `Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
1412
4291
  );
1413
4292
  }
1414
- if (contextRequestContext && defaultOptions?.requestContext) {
1415
- mastra.getLogger()?.warn(`"requestContext" set in the route options will be overridden by the request's "requestContext".`);
4293
+ const effectiveRequestContext = contextRequestContext || defaultOptions2?.requestContext || params.requestContext;
4294
+ if (contextRequestContext && defaultOptions2?.requestContext || contextRequestContext && params.requestContext || defaultOptions2?.requestContext && params.requestContext) {
4295
+ mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
1416
4296
  }
1417
4297
  if (!agentToUse) {
1418
4298
  throw new Error("Agent ID is required");
@@ -1422,15 +4302,15 @@ function chatRoute({
1422
4302
  agentId: agentToUse,
1423
4303
  params: {
1424
4304
  ...params,
1425
- requestContext: contextRequestContext || params.requestContext
4305
+ requestContext: effectiveRequestContext
1426
4306
  },
1427
- defaultOptions,
4307
+ defaultOptions: defaultOptions2,
1428
4308
  sendStart,
1429
4309
  sendFinish,
1430
4310
  sendReasoning,
1431
4311
  sendSources
1432
4312
  });
1433
- return ai.createUIMessageStreamResponse({
4313
+ return createUIMessageStreamResponse({
1434
4314
  stream: uiMessageStream
1435
4315
  });
1436
4316
  }
@@ -1449,7 +4329,7 @@ async function handleWorkflowStream({
1449
4329
  }
1450
4330
  const run = await workflowObj.createRun({ runId, resourceId, ...rest });
1451
4331
  const stream = resumeData ? run.resumeStream({ resumeData, ...rest, requestContext }) : run.stream({ inputData, ...rest, requestContext });
1452
- return ai.createUIMessageStream({
4332
+ return createUIMessageStream({
1453
4333
  execute: async ({ writer }) => {
1454
4334
  for await (const part of toAISdkV5Stream(stream, { from: "workflow", includeTextStreamParts })) {
1455
4335
  writer.write(part);
@@ -1541,7 +4421,7 @@ function workflowRoute({
1541
4421
  },
1542
4422
  includeTextStreamParts
1543
4423
  });
1544
- return ai.createUIMessageStreamResponse({ stream: uiMessageStream });
4424
+ return createUIMessageStreamResponse({ stream: uiMessageStream });
1545
4425
  }
1546
4426
  });
1547
4427
  }
@@ -1549,7 +4429,7 @@ async function handleNetworkStream({
1549
4429
  mastra,
1550
4430
  agentId,
1551
4431
  params,
1552
- defaultOptions
4432
+ defaultOptions: defaultOptions2
1553
4433
  }) {
1554
4434
  const { messages, ...rest } = params;
1555
4435
  const agentObj = mastra.getAgentById(agentId);
@@ -1557,10 +4437,10 @@ async function handleNetworkStream({
1557
4437
  throw new Error(`Agent ${agentId} not found`);
1558
4438
  }
1559
4439
  const result = await agentObj.network(messages, {
1560
- ...defaultOptions,
4440
+ ...defaultOptions2,
1561
4441
  ...rest
1562
4442
  });
1563
- return ai.createUIMessageStream({
4443
+ return createUIMessageStream({
1564
4444
  execute: async ({ writer }) => {
1565
4445
  for await (const part of toAISdkV5Stream(result, { from: "network" })) {
1566
4446
  writer.write(part);
@@ -1571,7 +4451,7 @@ async function handleNetworkStream({
1571
4451
  function networkRoute({
1572
4452
  path = "/network/:agentId",
1573
4453
  agent,
1574
- defaultOptions
4454
+ defaultOptions: defaultOptions2
1575
4455
  }) {
1576
4456
  if (!agent && !path.includes("/:agentId")) {
1577
4457
  throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
@@ -1630,6 +4510,7 @@ function networkRoute({
1630
4510
  handler: async (c) => {
1631
4511
  const params = await c.req.json();
1632
4512
  const mastra = c.get("mastra");
4513
+ const contextRequestContext = c.get("requestContext");
1633
4514
  let agentToUse = agent;
1634
4515
  if (!agent) {
1635
4516
  const agentId = c.req.param("agentId");
@@ -1640,19 +4521,475 @@ function networkRoute({
1640
4521
  `Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
1641
4522
  );
1642
4523
  }
4524
+ const effectiveRequestContext = contextRequestContext || defaultOptions2?.requestContext || params.requestContext;
4525
+ if (contextRequestContext && defaultOptions2?.requestContext || contextRequestContext && params.requestContext || defaultOptions2?.requestContext && params.requestContext) {
4526
+ mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
4527
+ }
1643
4528
  if (!agentToUse) {
1644
4529
  throw new Error("Agent ID is required");
1645
4530
  }
1646
4531
  const uiMessageStream = await handleNetworkStream({
1647
4532
  mastra,
1648
4533
  agentId: agentToUse,
1649
- params,
1650
- defaultOptions
4534
+ params: {
4535
+ ...params,
4536
+ requestContext: effectiveRequestContext
4537
+ },
4538
+ defaultOptions: defaultOptions2
4539
+ });
4540
+ return createUIMessageStreamResponse({ stream: uiMessageStream });
4541
+ }
4542
+ });
4543
+ }
4544
+ function withMastra(model, options = {}) {
4545
+ const { memory, inputProcessors = [], outputProcessors = [] } = options;
4546
+ const allInputProcessors = [...inputProcessors];
4547
+ const allOutputProcessors = [...outputProcessors];
4548
+ if (memory) {
4549
+ const { storage, lastMessages, semanticRecall, workingMemory } = memory;
4550
+ const isWorkingMemoryEnabled = typeof workingMemory === "object" && workingMemory.enabled !== false;
4551
+ if (isWorkingMemoryEnabled && typeof workingMemory === "object") {
4552
+ let template;
4553
+ if (workingMemory.template) {
4554
+ template = {
4555
+ format: "markdown",
4556
+ content: workingMemory.template
4557
+ };
4558
+ }
4559
+ const workingMemoryProcessor = new processors.WorkingMemory({
4560
+ storage,
4561
+ template,
4562
+ scope: workingMemory.scope,
4563
+ useVNext: "version" in workingMemory && workingMemory.version === "vnext"
4564
+ });
4565
+ allInputProcessors.push(workingMemoryProcessor);
4566
+ }
4567
+ if (lastMessages !== false && lastMessages !== void 0) {
4568
+ const messageHistory = new processors.MessageHistory({
4569
+ storage,
4570
+ lastMessages: typeof lastMessages === "number" ? lastMessages : void 0
4571
+ });
4572
+ allInputProcessors.push(messageHistory);
4573
+ allOutputProcessors.push(messageHistory);
4574
+ }
4575
+ if (semanticRecall) {
4576
+ const { vector, embedder, indexName, ...semanticConfig } = semanticRecall;
4577
+ const semanticRecallProcessor = new processors.SemanticRecall({
4578
+ storage,
4579
+ vector,
4580
+ embedder,
4581
+ indexName: indexName || "memory_messages",
4582
+ ...semanticConfig
4583
+ });
4584
+ allInputProcessors.push(semanticRecallProcessor);
4585
+ allOutputProcessors.push(semanticRecallProcessor);
4586
+ }
4587
+ }
4588
+ return wrapLanguageModel({
4589
+ model,
4590
+ middleware: createProcessorMiddleware({
4591
+ inputProcessors: allInputProcessors,
4592
+ outputProcessors: allOutputProcessors,
4593
+ memory: memory ? {
4594
+ threadId: memory.threadId,
4595
+ resourceId: memory.resourceId
4596
+ } : void 0
4597
+ })
4598
+ });
4599
+ }
4600
+ function createProcessorMiddleware(options) {
4601
+ const { inputProcessors = [], outputProcessors = [], memory } = options;
4602
+ const requestContext = new di.RequestContext();
4603
+ if (memory) {
4604
+ requestContext.set("MastraMemory", {
4605
+ thread: memory.threadId ? { id: memory.threadId } : void 0,
4606
+ resourceId: memory.resourceId,
4607
+ memoryConfig: memory.config
4608
+ });
4609
+ }
4610
+ return {
4611
+ middlewareVersion: "v2",
4612
+ /**
4613
+ * Transform params runs input processors (processInput)
4614
+ */
4615
+ async transformParams({ params }) {
4616
+ const messageList = new agent.MessageList({
4617
+ threadId: memory?.threadId,
4618
+ resourceId: memory?.resourceId
4619
+ });
4620
+ for (const msg of params.prompt) {
4621
+ if (msg.role === "system") {
4622
+ messageList.addSystem(msg.content);
4623
+ } else {
4624
+ messageList.add(msg, "input");
4625
+ }
4626
+ }
4627
+ for (const processor of inputProcessors) {
4628
+ if (processor.processInput) {
4629
+ try {
4630
+ await processor.processInput({
4631
+ messages: messageList.get.input.db(),
4632
+ systemMessages: messageList.getAllSystemMessages(),
4633
+ messageList,
4634
+ requestContext,
4635
+ abort: (reason) => {
4636
+ throw new agent.TripWire(reason || "Aborted by processor");
4637
+ }
4638
+ });
4639
+ } catch (error) {
4640
+ if (error instanceof agent.TripWire) {
4641
+ return {
4642
+ ...params,
4643
+ providerOptions: {
4644
+ ...params.providerOptions,
4645
+ mastraProcessors: {
4646
+ tripwire: true,
4647
+ reason: error.message
4648
+ }
4649
+ }
4650
+ };
4651
+ }
4652
+ throw error;
4653
+ }
4654
+ }
4655
+ }
4656
+ const newPrompt = messageList.get.all.aiV5.prompt().map(agent.MessageList.aiV5ModelMessageToV2PromptMessage);
4657
+ return {
4658
+ ...params,
4659
+ prompt: newPrompt
4660
+ };
4661
+ },
4662
+ /**
4663
+ * Wrap generate for non-streaming output processing
4664
+ */
4665
+ async wrapGenerate({ doGenerate, params }) {
4666
+ const processorState = params.providerOptions?.mastraProcessors;
4667
+ if (processorState?.tripwire) {
4668
+ const reason = processorState.reason || "Blocked by processor";
4669
+ return {
4670
+ content: [{ type: "text", text: reason }],
4671
+ finishReason: "stop",
4672
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
4673
+ warnings: [{ type: "other", message: `Tripwire: ${reason}` }]
4674
+ };
4675
+ }
4676
+ const result = await doGenerate();
4677
+ if (!outputProcessors.length) return result;
4678
+ const messageList = new agent.MessageList({
4679
+ threadId: memory?.threadId,
4680
+ resourceId: memory?.resourceId
4681
+ });
4682
+ for (const msg of params.prompt) {
4683
+ if (msg.role === "system") {
4684
+ messageList.addSystem(msg.content);
4685
+ } else {
4686
+ messageList.add(msg, "input");
4687
+ }
4688
+ }
4689
+ const textContent = result.content.filter((c) => c.type === "text").map((c) => c.text).join("");
4690
+ const responseMessage = {
4691
+ id: crypto.randomUUID(),
4692
+ role: "assistant",
4693
+ content: {
4694
+ format: 2,
4695
+ parts: [{ type: "text", text: textContent }]
4696
+ },
4697
+ createdAt: /* @__PURE__ */ new Date(),
4698
+ ...memory?.threadId && { threadId: memory.threadId },
4699
+ ...memory?.resourceId && { resourceId: memory.resourceId }
4700
+ };
4701
+ messageList.add(responseMessage, "response");
4702
+ for (const processor of outputProcessors) {
4703
+ if (processor.processOutputResult) {
4704
+ try {
4705
+ await processor.processOutputResult({
4706
+ messages: messageList.get.all.db(),
4707
+ messageList,
4708
+ requestContext,
4709
+ abort: (reason) => {
4710
+ throw new agent.TripWire(reason || "Aborted by processor");
4711
+ }
4712
+ });
4713
+ } catch (error) {
4714
+ if (error instanceof agent.TripWire) {
4715
+ return {
4716
+ content: [{ type: "text", text: error.message }],
4717
+ finishReason: "stop",
4718
+ usage: result.usage,
4719
+ warnings: [{ type: "other", message: `Output blocked: ${error.message}` }]
4720
+ };
4721
+ }
4722
+ throw error;
4723
+ }
4724
+ }
4725
+ }
4726
+ const processedText = messageList.get.response.db().map((m) => extractTextFromMastraMessage(m)).join("");
4727
+ return {
4728
+ ...result,
4729
+ content: [{ type: "text", text: processedText }]
4730
+ };
4731
+ },
4732
+ /**
4733
+ * Wrap stream for streaming output processing
4734
+ */
4735
+ async wrapStream({ doStream, params }) {
4736
+ const processorState = params.providerOptions?.mastraProcessors;
4737
+ if (processorState?.tripwire) {
4738
+ const reason = processorState.reason || "Blocked by processor";
4739
+ return {
4740
+ stream: createBlockedStream(reason)
4741
+ };
4742
+ }
4743
+ const { stream: stream$1, ...rest } = await doStream();
4744
+ if (!outputProcessors.length) return { stream: stream$1, ...rest };
4745
+ const processorStates = /* @__PURE__ */ new Map();
4746
+ const runId = crypto.randomUUID();
4747
+ const transformedStream = stream$1.pipeThrough(
4748
+ new TransformStream({
4749
+ async transform(chunk, controller) {
4750
+ let mastraChunk = stream.convertFullStreamChunkToMastra(
4751
+ chunk,
4752
+ { runId }
4753
+ );
4754
+ if (!mastraChunk) {
4755
+ controller.enqueue(chunk);
4756
+ return;
4757
+ }
4758
+ for (const processor of outputProcessors) {
4759
+ if (processor.processOutputStream && mastraChunk) {
4760
+ let state = processorStates.get(processor.id);
4761
+ if (!state) {
4762
+ state = { streamParts: [], customState: {} };
4763
+ processorStates.set(processor.id, state);
4764
+ }
4765
+ state.streamParts.push(mastraChunk);
4766
+ try {
4767
+ const result = await processor.processOutputStream({
4768
+ part: mastraChunk,
4769
+ streamParts: state.streamParts,
4770
+ state: state.customState,
4771
+ requestContext,
4772
+ abort: (reason) => {
4773
+ throw new agent.TripWire(reason || "Aborted by processor");
4774
+ }
4775
+ });
4776
+ if (result === null || result === void 0) {
4777
+ mastraChunk = void 0;
4778
+ } else {
4779
+ mastraChunk = result;
4780
+ }
4781
+ } catch (error) {
4782
+ if (error instanceof agent.TripWire) {
4783
+ controller.enqueue({
4784
+ type: "error",
4785
+ error: new Error(error.message)
4786
+ });
4787
+ controller.terminate();
4788
+ return;
4789
+ }
4790
+ throw error;
4791
+ }
4792
+ }
4793
+ }
4794
+ if (mastraChunk) {
4795
+ const aiChunk = convertMastraChunkToAISDKStreamPart(mastraChunk);
4796
+ if (aiChunk) {
4797
+ controller.enqueue(aiChunk);
4798
+ }
4799
+ }
4800
+ }
4801
+ })
4802
+ );
4803
+ return { stream: transformedStream, ...rest };
4804
+ }
4805
+ };
4806
+ }
4807
+ function createBlockedStream(reason) {
4808
+ return new ReadableStream({
4809
+ start(controller) {
4810
+ const id = crypto.randomUUID();
4811
+ controller.enqueue({
4812
+ type: "text-start",
4813
+ id
4814
+ });
4815
+ controller.enqueue({
4816
+ type: "text-delta",
4817
+ id,
4818
+ delta: reason
4819
+ });
4820
+ controller.enqueue({
4821
+ type: "text-end",
4822
+ id
4823
+ });
4824
+ controller.enqueue({
4825
+ type: "finish",
4826
+ finishReason: "stop",
4827
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
1651
4828
  });
1652
- return ai.createUIMessageStreamResponse({ stream: uiMessageStream });
4829
+ controller.close();
1653
4830
  }
1654
4831
  });
1655
4832
  }
4833
+ function extractTextFromMastraMessage(msg) {
4834
+ const content = msg.content;
4835
+ if (typeof content === "string") {
4836
+ return content;
4837
+ }
4838
+ if (content?.parts) {
4839
+ return content.parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join("");
4840
+ }
4841
+ return "";
4842
+ }
4843
+ function convertMastraChunkToAISDKStreamPart(chunk) {
4844
+ switch (chunk.type) {
4845
+ // Text streaming
4846
+ case "text-start":
4847
+ return {
4848
+ type: "text-start",
4849
+ id: chunk.payload.id || crypto.randomUUID(),
4850
+ providerMetadata: chunk.payload.providerMetadata
4851
+ };
4852
+ case "text-delta":
4853
+ return {
4854
+ type: "text-delta",
4855
+ id: chunk.payload.id || crypto.randomUUID(),
4856
+ delta: chunk.payload.text,
4857
+ providerMetadata: chunk.payload.providerMetadata
4858
+ };
4859
+ case "text-end":
4860
+ return {
4861
+ type: "text-end",
4862
+ id: chunk.payload.id || crypto.randomUUID(),
4863
+ providerMetadata: chunk.payload.providerMetadata
4864
+ };
4865
+ // Reasoning streaming
4866
+ case "reasoning-start":
4867
+ return {
4868
+ type: "reasoning-start",
4869
+ id: chunk.payload.id || crypto.randomUUID(),
4870
+ providerMetadata: chunk.payload.providerMetadata
4871
+ };
4872
+ case "reasoning-delta":
4873
+ return {
4874
+ type: "reasoning-delta",
4875
+ id: chunk.payload.id || crypto.randomUUID(),
4876
+ delta: chunk.payload.text,
4877
+ providerMetadata: chunk.payload.providerMetadata
4878
+ };
4879
+ case "reasoning-end":
4880
+ return {
4881
+ type: "reasoning-end",
4882
+ id: chunk.payload.id || crypto.randomUUID(),
4883
+ providerMetadata: chunk.payload.providerMetadata
4884
+ };
4885
+ // Tool call (complete)
4886
+ case "tool-call":
4887
+ return {
4888
+ type: "tool-call",
4889
+ toolCallId: chunk.payload.toolCallId,
4890
+ toolName: chunk.payload.toolName,
4891
+ input: JSON.stringify(chunk.payload.args),
4892
+ providerExecuted: chunk.payload.providerExecuted,
4893
+ providerMetadata: chunk.payload.providerMetadata
4894
+ };
4895
+ // Tool call input streaming
4896
+ case "tool-call-input-streaming-start":
4897
+ return {
4898
+ type: "tool-input-start",
4899
+ id: chunk.payload.toolCallId,
4900
+ toolName: chunk.payload.toolName,
4901
+ providerExecuted: chunk.payload.providerExecuted,
4902
+ providerMetadata: chunk.payload.providerMetadata
4903
+ };
4904
+ case "tool-call-delta":
4905
+ return {
4906
+ type: "tool-input-delta",
4907
+ id: chunk.payload.toolCallId,
4908
+ delta: chunk.payload.argsTextDelta,
4909
+ providerMetadata: chunk.payload.providerMetadata
4910
+ };
4911
+ case "tool-call-input-streaming-end":
4912
+ return {
4913
+ type: "tool-input-end",
4914
+ id: chunk.payload.toolCallId,
4915
+ providerMetadata: chunk.payload.providerMetadata
4916
+ };
4917
+ // Tool result
4918
+ case "tool-result":
4919
+ return {
4920
+ type: "tool-result",
4921
+ toolCallId: chunk.payload.toolCallId,
4922
+ toolName: chunk.payload.toolName,
4923
+ result: { type: "json", value: chunk.payload.result },
4924
+ isError: chunk.payload.isError,
4925
+ providerExecuted: chunk.payload.providerExecuted,
4926
+ providerMetadata: chunk.payload.providerMetadata
4927
+ };
4928
+ // Source (citations)
4929
+ case "source":
4930
+ if (chunk.payload.sourceType === "url") {
4931
+ return {
4932
+ type: "source",
4933
+ sourceType: "url",
4934
+ id: chunk.payload.id,
4935
+ url: chunk.payload.url,
4936
+ title: chunk.payload.title,
4937
+ providerMetadata: chunk.payload.providerMetadata
4938
+ };
4939
+ } else {
4940
+ return {
4941
+ type: "source",
4942
+ sourceType: "document",
4943
+ id: chunk.payload.id,
4944
+ mediaType: chunk.payload.mimeType,
4945
+ title: chunk.payload.title,
4946
+ filename: chunk.payload.filename,
4947
+ providerMetadata: chunk.payload.providerMetadata
4948
+ };
4949
+ }
4950
+ // File output
4951
+ case "file":
4952
+ return {
4953
+ type: "file",
4954
+ data: chunk.payload.data || chunk.payload.base64,
4955
+ mediaType: chunk.payload.mimeType
4956
+ };
4957
+ // Response metadata
4958
+ case "response-metadata":
4959
+ return {
4960
+ type: "response-metadata",
4961
+ ...chunk.payload
4962
+ };
4963
+ // Raw provider data
4964
+ case "raw":
4965
+ return {
4966
+ type: "raw",
4967
+ rawValue: chunk.payload
4968
+ };
4969
+ // Finish
4970
+ case "finish": {
4971
+ const usage = chunk.payload.output?.usage;
4972
+ return {
4973
+ type: "finish",
4974
+ finishReason: toAISDKFinishReason(chunk.payload.stepResult?.reason || "stop"),
4975
+ usage: usage ? {
4976
+ inputTokens: usage.inputTokens || 0,
4977
+ outputTokens: usage.outputTokens || 0,
4978
+ totalTokens: usage.totalTokens || 0
4979
+ } : { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
4980
+ providerMetadata: chunk.payload.metadata?.providerMetadata
4981
+ };
4982
+ }
4983
+ // Error
4984
+ case "error":
4985
+ return {
4986
+ type: "error",
4987
+ error: chunk.payload.error || chunk.payload
4988
+ };
4989
+ default:
4990
+ return null;
4991
+ }
4992
+ }
1656
4993
 
1657
4994
  // src/to-ai-sdk-format.ts
1658
4995
  function toAISdkFormat() {
@@ -1668,6 +5005,7 @@ exports.handleWorkflowStream = handleWorkflowStream;
1668
5005
  exports.networkRoute = networkRoute;
1669
5006
  exports.toAISdkFormat = toAISdkFormat;
1670
5007
  exports.toAISdkStream = toAISdkV5Stream;
5008
+ exports.withMastra = withMastra;
1671
5009
  exports.workflowRoute = workflowRoute;
1672
5010
  //# sourceMappingURL=index.cjs.map
1673
5011
  //# sourceMappingURL=index.cjs.map