@mastra/ai-sdk 1.0.0-beta.1 → 1.0.0-beta.11

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 (50) hide show
  1. package/CHANGELOG.md +366 -0
  2. package/README.md +60 -0
  3. package/dist/__tests__/__fixtures__/network.stream.d.ts +2329 -0
  4. package/dist/__tests__/__fixtures__/network.stream.d.ts.map +1 -0
  5. package/dist/_types/@ai-sdk_provider/dist/index.d.ts +1719 -0
  6. package/dist/chat-route.d.ts +90 -3
  7. package/dist/chat-route.d.ts.map +1 -1
  8. package/dist/chunk-AAQDCHJY.js +293 -0
  9. package/dist/chunk-AAQDCHJY.js.map +1 -0
  10. package/dist/chunk-CCJXHQQO.cjs +296 -0
  11. package/dist/chunk-CCJXHQQO.cjs.map +1 -0
  12. package/dist/chunk-DES3K4SD.cjs +17 -0
  13. package/dist/chunk-DES3K4SD.cjs.map +1 -0
  14. package/dist/chunk-VUNV25KB.js +14 -0
  15. package/dist/chunk-VUNV25KB.js.map +1 -0
  16. package/dist/convert-messages.d.ts +83 -3
  17. package/dist/convert-messages.d.ts.map +1 -1
  18. package/dist/convert-streams.d.ts +64 -1
  19. package/dist/convert-streams.d.ts.map +1 -1
  20. package/dist/helpers.d.ts +9 -3
  21. package/dist/helpers.d.ts.map +1 -1
  22. package/dist/index.cjs +3755 -118
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.ts +8 -6
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +3731 -117
  27. package/dist/index.js.map +1 -1
  28. package/dist/middleware.d.ts +157 -0
  29. package/dist/middleware.d.ts.map +1 -0
  30. package/dist/network-route.d.ts +63 -2
  31. package/dist/network-route.d.ts.map +1 -1
  32. package/dist/token-36YTPVWD.cjs +63 -0
  33. package/dist/token-36YTPVWD.cjs.map +1 -0
  34. package/dist/token-ZFKXETJY.js +61 -0
  35. package/dist/token-ZFKXETJY.js.map +1 -0
  36. package/dist/token-util-737PGIQA.cjs +9 -0
  37. package/dist/token-util-737PGIQA.cjs.map +1 -0
  38. package/dist/token-util-SD2EI4DD.js +7 -0
  39. package/dist/token-util-SD2EI4DD.js.map +1 -0
  40. package/dist/transformers.d.ts +137 -10
  41. package/dist/transformers.d.ts.map +1 -1
  42. package/dist/ui.cjs +0 -1
  43. package/dist/ui.cjs.map +1 -1
  44. package/dist/ui.js +0 -1
  45. package/dist/ui.js.map +1 -1
  46. package/dist/utils.d.ts +2 -1
  47. package/dist/utils.d.ts.map +1 -1
  48. package/dist/workflow-route.d.ts +68 -1
  49. package/dist/workflow-route.d.ts.map +1 -1
  50. package/package.json +9 -7
package/dist/index.cjs CHANGED
@@ -1,15 +1,2857 @@
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) => {
11
2824
  return chunk && typeof chunk === "object" && "type" in chunk && chunk.type?.startsWith("data-");
12
2825
  };
2826
+ var isMastraTextStreamChunk = (chunk) => {
2827
+ return chunk && typeof chunk === "object" && "type" in chunk && typeof chunk.type === "string" && [
2828
+ "text-start",
2829
+ "text-delta",
2830
+ "text-end",
2831
+ "reasoning-start",
2832
+ "reasoning-delta",
2833
+ "reasoning-end",
2834
+ "file",
2835
+ "source",
2836
+ "tool-input-start",
2837
+ "tool-input-delta",
2838
+ "tool-call-approval",
2839
+ "tool-call-suspended",
2840
+ "tool-call",
2841
+ "tool-result",
2842
+ "tool-error",
2843
+ "error",
2844
+ "start-step",
2845
+ "finish-step",
2846
+ "start",
2847
+ "finish",
2848
+ "abort",
2849
+ "tool-input-end",
2850
+ "object",
2851
+ "tripwire",
2852
+ "raw"
2853
+ ].includes(chunk.type);
2854
+ };
13
2855
  function safeParseErrorObject(obj) {
14
2856
  if (typeof obj !== "object" || obj === null) {
15
2857
  return String(obj);
@@ -32,6 +2874,12 @@ var isWorkflowExecutionDataChunkType = (chunk) => {
32
2874
  };
33
2875
 
34
2876
  // src/helpers.ts
2877
+ function toAISDKFinishReason(reason) {
2878
+ if (reason === "tripwire" || reason === "retry") {
2879
+ return "other";
2880
+ }
2881
+ return reason;
2882
+ }
35
2883
  function convertMastraChunkToAISDKv5({
36
2884
  chunk,
37
2885
  mode = "stream"
@@ -39,7 +2887,9 @@ function convertMastraChunkToAISDKv5({
39
2887
  switch (chunk.type) {
40
2888
  case "start":
41
2889
  return {
42
- 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 } : {}
43
2893
  };
44
2894
  case "step-start":
45
2895
  const { messageId: _messageId, ...rest } = chunk.payload;
@@ -56,7 +2906,8 @@ function convertMastraChunkToAISDKv5({
56
2906
  case "finish": {
57
2907
  return {
58
2908
  type: "finish",
59
- 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
60
2911
  totalUsage: chunk.payload.output.usage
61
2912
  };
62
2913
  }
@@ -140,6 +2991,28 @@ function convertMastraChunkToAISDKv5({
140
2991
  toolName: chunk.payload.toolName,
141
2992
  input: chunk.payload.args
142
2993
  };
2994
+ case "tool-call-approval":
2995
+ return {
2996
+ type: "data-tool-call-approval",
2997
+ id: chunk.payload.toolCallId,
2998
+ data: {
2999
+ runId: chunk.runId,
3000
+ toolCallId: chunk.payload.toolCallId,
3001
+ toolName: chunk.payload.toolName,
3002
+ args: chunk.payload.args
3003
+ }
3004
+ };
3005
+ case "tool-call-suspended":
3006
+ return {
3007
+ type: "data-tool-call-suspended",
3008
+ id: chunk.payload.toolCallId,
3009
+ data: {
3010
+ runId: chunk.runId,
3011
+ toolCallId: chunk.payload.toolCallId,
3012
+ toolName: chunk.payload.toolName,
3013
+ suspendPayload: chunk.payload.suspendPayload
3014
+ }
3015
+ };
143
3016
  case "tool-call-input-streaming-start":
144
3017
  return {
145
3018
  type: "tool-input-start",
@@ -173,7 +3046,7 @@ function convertMastraChunkToAISDKv5({
173
3046
  ...rest2
174
3047
  },
175
3048
  usage: chunk.payload.output.usage,
176
- finishReason: chunk.payload.stepResult.reason,
3049
+ finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
177
3050
  providerMetadata
178
3051
  };
179
3052
  }
@@ -230,6 +3103,16 @@ function convertMastraChunkToAISDKv5({
230
3103
  type: "object",
231
3104
  object: chunk.object
232
3105
  };
3106
+ case "tripwire":
3107
+ return {
3108
+ type: "data-tripwire",
3109
+ data: {
3110
+ reason: chunk.payload.reason,
3111
+ retry: chunk.payload.retry,
3112
+ metadata: chunk.payload.metadata,
3113
+ processorId: chunk.payload.processorId
3114
+ }
3115
+ };
233
3116
  default:
234
3117
  if (chunk.type && "payload" in chunk && chunk.payload) {
235
3118
  return {
@@ -285,6 +3168,14 @@ function convertFullStreamChunkToUIMessageStream({
285
3168
  };
286
3169
  }
287
3170
  case "reasoning-delta": {
3171
+ if (sendReasoning) {
3172
+ return {
3173
+ type: "reasoning-delta",
3174
+ id: part.id,
3175
+ delta: part.text,
3176
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
3177
+ };
3178
+ }
288
3179
  return;
289
3180
  }
290
3181
  case "reasoning-end": {
@@ -302,6 +3193,25 @@ function convertFullStreamChunkToUIMessageStream({
302
3193
  };
303
3194
  }
304
3195
  case "source": {
3196
+ if (sendSources && part.sourceType === "url") {
3197
+ return {
3198
+ type: "source-url",
3199
+ sourceId: part.id,
3200
+ url: part.url,
3201
+ title: part.title,
3202
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
3203
+ };
3204
+ }
3205
+ if (sendSources && part.sourceType === "document") {
3206
+ return {
3207
+ type: "source-document",
3208
+ sourceId: part.id,
3209
+ mediaType: part.mediaType,
3210
+ title: part.title,
3211
+ filename: part.filename,
3212
+ ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
3213
+ };
3214
+ }
305
3215
  return;
306
3216
  }
307
3217
  case "tool-input-start": {
@@ -392,21 +3302,24 @@ function convertFullStreamChunkToUIMessageStream({
392
3302
  return { type: "finish-step" };
393
3303
  }
394
3304
  case "start": {
395
- {
3305
+ if (sendStart) {
3306
+ const messageId = ("messageId" in part ? part.messageId : void 0) || responseMessageId;
396
3307
  return {
397
3308
  type: "start",
398
3309
  ...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},
399
- ...responseMessageId != null ? { messageId: responseMessageId } : {}
3310
+ ...messageId != null ? { messageId } : {}
400
3311
  };
401
3312
  }
3313
+ return;
402
3314
  }
403
3315
  case "finish": {
404
- {
3316
+ if (sendFinish) {
405
3317
  return {
406
3318
  type: "finish",
407
3319
  ...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}
408
3320
  };
409
3321
  }
3322
+ return;
410
3323
  }
411
3324
  case "abort": {
412
3325
  return part;
@@ -433,7 +3346,10 @@ function convertFullStreamChunkToUIMessageStream({
433
3346
  }
434
3347
 
435
3348
  // src/transformers.ts
436
- function WorkflowStreamToAISDKTransformer() {
3349
+ var PRIMITIVE_CACHE_SYMBOL = Symbol("primitive-cache");
3350
+ function WorkflowStreamToAISDKTransformer({
3351
+ includeTextStreamParts
3352
+ } = {}) {
437
3353
  const bufferedWorkflows = /* @__PURE__ */ new Map();
438
3354
  return new TransformStream({
439
3355
  start(controller) {
@@ -447,7 +3363,7 @@ function WorkflowStreamToAISDKTransformer() {
447
3363
  });
448
3364
  },
449
3365
  transform(chunk, controller) {
450
- const transformed = transformWorkflow(chunk, bufferedWorkflows);
3366
+ const transformed = transformWorkflow(chunk, bufferedWorkflows, false, includeTextStreamParts);
451
3367
  if (transformed) controller.enqueue(transformed);
452
3368
  }
453
3369
  });
@@ -471,20 +3387,37 @@ function AgentNetworkToAISDKTransformer() {
471
3387
  }
472
3388
  });
473
3389
  }
474
- function AgentStreamToAISDKTransformer(lastMessageId) {
3390
+ function AgentStreamToAISDKTransformer({
3391
+ lastMessageId,
3392
+ sendStart,
3393
+ sendFinish,
3394
+ sendReasoning,
3395
+ sendSources,
3396
+ messageMetadata,
3397
+ onError
3398
+ }) {
475
3399
  let bufferedSteps = /* @__PURE__ */ new Map();
3400
+ let tripwireOccurred = false;
3401
+ let finishEventSent = false;
476
3402
  return new TransformStream({
477
3403
  transform(chunk, controller) {
3404
+ if (chunk.type === "tripwire") {
3405
+ tripwireOccurred = true;
3406
+ }
3407
+ if (chunk.type === "finish") {
3408
+ finishEventSent = true;
3409
+ }
478
3410
  const part = convertMastraChunkToAISDKv5({ chunk, mode: "stream" });
479
3411
  const transformedChunk = convertFullStreamChunkToUIMessageStream({
480
3412
  part,
481
- sendReasoning: false,
482
- sendSources: false,
483
- sendStart: true,
484
- sendFinish: true,
3413
+ sendReasoning,
3414
+ sendSources,
3415
+ messageMetadataValue: messageMetadata?.({ part }),
3416
+ sendStart,
3417
+ sendFinish,
485
3418
  responseMessageId: lastMessageId,
486
3419
  onError(error) {
487
- return safeParseErrorObject(error);
3420
+ return onError ? onError(error) : safeParseErrorObject(error);
488
3421
  }
489
3422
  });
490
3423
  if (transformedChunk) {
@@ -504,6 +3437,14 @@ function AgentStreamToAISDKTransformer(lastMessageId) {
504
3437
  controller.enqueue(transformedChunk);
505
3438
  }
506
3439
  }
3440
+ },
3441
+ flush(controller) {
3442
+ if (tripwireOccurred && !finishEventSent && sendFinish) {
3443
+ controller.enqueue({
3444
+ type: "finish",
3445
+ finishReason: "other"
3446
+ });
3447
+ }
507
3448
  }
508
3449
  });
509
3450
  }
@@ -643,7 +3584,7 @@ function transformAgent(payload, bufferedSteps) {
643
3584
  }
644
3585
  return null;
645
3586
  }
646
- function transformWorkflow(payload, bufferedWorkflows, isNested) {
3587
+ function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStreamParts) {
647
3588
  switch (payload.type) {
648
3589
  case "workflow-start":
649
3590
  bufferedWorkflows.set(payload.runId, {
@@ -736,6 +3677,29 @@ function transformWorkflow(payload, bufferedWorkflows, isNested) {
736
3677
  }
737
3678
  };
738
3679
  }
3680
+ case "workflow-step-output": {
3681
+ const output = payload.payload.output;
3682
+ if (includeTextStreamParts && output && isMastraTextStreamChunk(output)) {
3683
+ const part = convertMastraChunkToAISDKv5({ chunk: output, mode: "stream" });
3684
+ const transformedChunk = convertFullStreamChunkToUIMessageStream({
3685
+ part,
3686
+ onError(error) {
3687
+ return safeParseErrorObject(error);
3688
+ }
3689
+ });
3690
+ return transformedChunk;
3691
+ }
3692
+ if (output && isDataChunkType(output)) {
3693
+ if (!("data" in output)) {
3694
+ throw new Error(
3695
+ `UI Messages require a data property when using data- prefixed chunks
3696
+ ${JSON.stringify(output)}`
3697
+ );
3698
+ }
3699
+ return output;
3700
+ }
3701
+ return null;
3702
+ }
739
3703
  default: {
740
3704
  if (isDataChunkType(payload)) {
741
3705
  if (!("data" in payload)) {
@@ -755,12 +3719,29 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
755
3719
  case "routing-agent-start": {
756
3720
  if (!bufferedNetworks.has(payload.runId)) {
757
3721
  bufferedNetworks.set(payload.runId, {
758
- name: payload.payload.agentId,
3722
+ name: payload.payload.networkId,
759
3723
  steps: [],
760
3724
  usage: null,
761
3725
  output: null
762
3726
  });
763
3727
  }
3728
+ const current = bufferedNetworks.get(payload.runId);
3729
+ current.steps.push({
3730
+ id: payload.payload.runId,
3731
+ name: payload.payload.agentId,
3732
+ status: "running",
3733
+ iteration: payload.payload.inputData.iteration,
3734
+ input: {
3735
+ task: payload.payload.inputData.task,
3736
+ threadId: payload.payload.inputData.threadId,
3737
+ threadResourceId: payload.payload.inputData.threadResourceId
3738
+ },
3739
+ output: "",
3740
+ task: null,
3741
+ suspendPayload: null,
3742
+ resumePayload: null,
3743
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
3744
+ });
764
3745
  return {
765
3746
  type: isNested ? "data-tool-network" : "data-network",
766
3747
  id: payload.runId,
@@ -791,14 +3772,19 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
791
3772
  };
792
3773
  }
793
3774
  case "agent-execution-start": {
794
- const current = bufferedNetworks.get(payload.runId) || { name: "", steps: [], usage: null, output: null };
3775
+ const current = bufferedNetworks.get(payload.runId);
3776
+ if (!current) return null;
795
3777
  current.steps.push({
3778
+ id: payload.payload.runId,
796
3779
  name: payload.payload.agentId,
797
3780
  status: "running",
798
- input: payload.payload.args || null,
3781
+ iteration: payload.payload.args?.iteration ?? 0,
3782
+ input: { prompt: payload.payload.args?.prompt ?? "" },
799
3783
  output: null,
3784
+ task: null,
800
3785
  suspendPayload: null,
801
- resumePayload: null
3786
+ resumePayload: null,
3787
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
802
3788
  });
803
3789
  bufferedNetworks.set(payload.runId, current);
804
3790
  return {
@@ -811,14 +3797,19 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
811
3797
  };
812
3798
  }
813
3799
  case "workflow-execution-start": {
814
- const current = bufferedNetworks.get(payload.runId) || { name: "", steps: [], usage: null, output: null };
3800
+ const current = bufferedNetworks.get(payload.runId);
3801
+ if (!current) return null;
815
3802
  current.steps.push({
816
- name: payload.payload.name,
3803
+ id: payload.payload.runId,
3804
+ name: payload.payload.workflowId,
817
3805
  status: "running",
818
- input: payload.payload.args || null,
3806
+ iteration: payload.payload.args?.iteration ?? 0,
3807
+ input: { prompt: payload.payload.args?.prompt ?? "" },
819
3808
  output: null,
3809
+ task: null,
820
3810
  suspendPayload: null,
821
- resumePayload: null
3811
+ resumePayload: null,
3812
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
822
3813
  });
823
3814
  bufferedNetworks.set(payload.runId, current);
824
3815
  return {
@@ -831,14 +3822,21 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
831
3822
  };
832
3823
  }
833
3824
  case "tool-execution-start": {
834
- const current = bufferedNetworks.get(payload.runId) || { name: "", steps: [], usage: null, output: null };
3825
+ const current = bufferedNetworks.get(payload.runId);
3826
+ if (!current) return null;
835
3827
  current.steps.push({
3828
+ id: payload.payload.args.toolCallId,
836
3829
  name: payload.payload.args?.toolName,
837
3830
  status: "running",
3831
+ iteration: payload.payload.args?.iteration ? Number(payload.payload.args.iteration) : 0,
3832
+ task: {
3833
+ id: payload.payload.args?.toolName
3834
+ },
838
3835
  input: payload.payload.args?.args || null,
839
3836
  output: null,
840
3837
  suspendPayload: null,
841
- resumePayload: null
3838
+ resumePayload: null,
3839
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
842
3840
  });
843
3841
  bufferedNetworks.set(payload.runId, current);
844
3842
  return {
@@ -853,14 +3851,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
853
3851
  case "agent-execution-end": {
854
3852
  const current = bufferedNetworks.get(payload.runId);
855
3853
  if (!current) return null;
856
- current.steps.push({
857
- name: payload.payload.agentId,
858
- status: "success",
859
- input: null,
860
- output: payload.payload.result,
861
- suspendPayload: null,
862
- resumePayload: null
863
- });
3854
+ const stepId = payload.payload.runId;
3855
+ const step = current.steps.find((step2) => step2.id === stepId);
3856
+ if (!step) {
3857
+ return null;
3858
+ }
3859
+ step.status = "success";
3860
+ step.output = payload.payload.result;
864
3861
  return {
865
3862
  type: isNested ? "data-tool-network" : "data-network",
866
3863
  id: payload.runId,
@@ -875,14 +3872,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
875
3872
  case "tool-execution-end": {
876
3873
  const current = bufferedNetworks.get(payload.runId);
877
3874
  if (!current) return null;
878
- current.steps.push({
879
- name: payload.payload.toolName,
880
- status: "success",
881
- input: null,
882
- output: payload.payload.result,
883
- suspendPayload: null,
884
- resumePayload: null
885
- });
3875
+ const stepId = payload.payload.toolCallId;
3876
+ const step = current.steps.find((step2) => step2.id === stepId);
3877
+ if (!step) {
3878
+ return null;
3879
+ }
3880
+ step.status = "success";
3881
+ step.output = payload.payload.result;
886
3882
  return {
887
3883
  type: isNested ? "data-tool-network" : "data-network",
888
3884
  id: payload.runId,
@@ -895,15 +3891,14 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
895
3891
  }
896
3892
  case "workflow-execution-end": {
897
3893
  const current = bufferedNetworks.get(payload.runId);
898
- if (!current) return null;
899
- current.steps.push({
900
- name: payload.payload.name,
901
- status: "success",
902
- input: null,
903
- output: payload.payload.result,
904
- suspendPayload: null,
905
- resumePayload: null
906
- });
3894
+ if (!current) return null;
3895
+ const stepId = payload.payload.runId;
3896
+ const step = current.steps.find((step2) => step2.id === stepId);
3897
+ if (!step) {
3898
+ return null;
3899
+ }
3900
+ step.status = "success";
3901
+ step.output = payload.payload.result;
907
3902
  return {
908
3903
  type: isNested ? "data-tool-network" : "data-network",
909
3904
  id: payload.runId,
@@ -918,12 +3913,24 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
918
3913
  case "routing-agent-end": {
919
3914
  const current = bufferedNetworks.get(payload.runId);
920
3915
  if (!current) return null;
3916
+ const stepId = payload.payload.runId;
3917
+ const step = current.steps.find((step2) => step2.id === stepId);
3918
+ if (!step) {
3919
+ return null;
3920
+ }
3921
+ step.status = "success";
3922
+ step.task = {
3923
+ id: payload.payload.primitiveId,
3924
+ type: payload.payload.primitiveType,
3925
+ name: payload.payload.task,
3926
+ reason: payload.payload.selectionReason
3927
+ };
3928
+ step.output = payload.payload.result;
921
3929
  return {
922
3930
  type: isNested ? "data-tool-network" : "data-network",
923
3931
  id: payload.runId,
924
3932
  data: {
925
3933
  ...current,
926
- status: "finished",
927
3934
  usage: payload.payload?.usage ?? current.usage,
928
3935
  output: payload.payload?.result ?? current.output
929
3936
  }
@@ -957,32 +3964,86 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
957
3964
  };
958
3965
  }
959
3966
  default: {
960
- if (isDataChunkType(payload)) {
961
- if (!("data" in payload)) {
3967
+ if (isAgentExecutionDataChunkType(payload)) {
3968
+ if (!("data" in payload.payload)) {
962
3969
  throw new Error(
963
3970
  `UI Messages require a data property when using data- prefixed chunks
964
3971
  ${JSON.stringify(payload)}`
965
3972
  );
966
3973
  }
967
- return payload;
3974
+ const { type, data } = payload.payload;
3975
+ return { type, data };
968
3976
  }
969
- if (isAgentExecutionDataChunkType(payload)) {
3977
+ if (isWorkflowExecutionDataChunkType(payload)) {
970
3978
  if (!("data" in payload.payload)) {
971
3979
  throw new Error(
972
3980
  `UI Messages require a data property when using data- prefixed chunks
973
3981
  ${JSON.stringify(payload)}`
974
3982
  );
975
3983
  }
976
- return payload.payload;
3984
+ const { type, data } = payload.payload;
3985
+ return { type, data };
977
3986
  }
978
- if (isWorkflowExecutionDataChunkType(payload)) {
979
- if (!("data" in payload.payload)) {
3987
+ if (payload.type.startsWith("agent-execution-event-")) {
3988
+ const stepId = payload.payload.runId;
3989
+ const current = bufferedNetworks.get(payload.runId);
3990
+ if (!current) return null;
3991
+ const step = current.steps.find((step2) => step2.id === stepId);
3992
+ if (!step) {
3993
+ return null;
3994
+ }
3995
+ step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
3996
+ const result = transformAgent(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
3997
+ if (result) {
3998
+ const { request, response, ...data } = result.data;
3999
+ step.task = data;
4000
+ }
4001
+ bufferedNetworks.set(payload.runId, current);
4002
+ return {
4003
+ type: isNested ? "data-tool-network" : "data-network",
4004
+ id: payload.runId,
4005
+ data: {
4006
+ ...current,
4007
+ status: "running"
4008
+ }
4009
+ };
4010
+ }
4011
+ if (payload.type.startsWith("workflow-execution-event-")) {
4012
+ const stepId = payload.payload.runId;
4013
+ const current = bufferedNetworks.get(payload.runId);
4014
+ if (!current) return null;
4015
+ const step = current.steps.find((step2) => step2.id === stepId);
4016
+ if (!step) {
4017
+ return null;
4018
+ }
4019
+ step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
4020
+ const result = transformWorkflow(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
4021
+ if (result && "data" in result) {
4022
+ const data = result.data;
4023
+ step.task = data;
4024
+ if (data.name && step.task) {
4025
+ step.task.id = data.name;
4026
+ }
4027
+ }
4028
+ bufferedNetworks.set(payload.runId, current);
4029
+ return {
4030
+ type: isNested ? "data-tool-network" : "data-network",
4031
+ id: payload.runId,
4032
+ data: {
4033
+ ...current,
4034
+ status: "running"
4035
+ }
4036
+ };
4037
+ }
4038
+ if (isDataChunkType(payload)) {
4039
+ if (!("data" in payload)) {
980
4040
  throw new Error(
981
4041
  `UI Messages require a data property when using data- prefixed chunks
982
4042
  ${JSON.stringify(payload)}`
983
4043
  );
984
4044
  }
985
- return payload.payload;
4045
+ const { type, data } = payload;
4046
+ return { type, data };
986
4047
  }
987
4048
  return null;
988
4049
  }
@@ -990,23 +4051,95 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
990
4051
  }
991
4052
 
992
4053
  // src/convert-streams.ts
993
- function toAISdkV5Stream(stream, options = { from: "agent" }) {
4054
+ function toAISdkV5Stream(stream, options = {
4055
+ from: "agent",
4056
+ sendStart: true,
4057
+ sendFinish: true
4058
+ }) {
994
4059
  const from = options?.from;
995
4060
  if (from === "workflow") {
996
- return stream.pipeThrough(WorkflowStreamToAISDKTransformer());
4061
+ const includeTextStreamParts = options?.includeTextStreamParts ?? true;
4062
+ return stream.pipeThrough(
4063
+ WorkflowStreamToAISDKTransformer({ includeTextStreamParts })
4064
+ );
997
4065
  }
998
4066
  if (from === "network") {
999
4067
  return stream.pipeThrough(AgentNetworkToAISDKTransformer());
1000
4068
  }
1001
4069
  const agentReadable = "fullStream" in stream ? stream.fullStream : stream;
1002
- return agentReadable.pipeThrough(AgentStreamToAISDKTransformer(options?.lastMessageId));
4070
+ return agentReadable.pipeThrough(
4071
+ AgentStreamToAISDKTransformer({
4072
+ lastMessageId: options?.lastMessageId,
4073
+ sendStart: options?.sendStart,
4074
+ sendFinish: options?.sendFinish,
4075
+ sendReasoning: options?.sendReasoning,
4076
+ sendSources: options?.sendSources,
4077
+ messageMetadata: options?.messageMetadata,
4078
+ onError: options?.onError
4079
+ })
4080
+ );
1003
4081
  }
1004
4082
 
1005
4083
  // src/chat-route.ts
4084
+ async function handleChatStream({
4085
+ mastra,
4086
+ agentId,
4087
+ params,
4088
+ defaultOptions: defaultOptions2,
4089
+ sendStart = true,
4090
+ sendFinish = true,
4091
+ sendReasoning = false,
4092
+ sendSources = false
4093
+ }) {
4094
+ const { messages, resumeData, runId, requestContext, ...rest } = params;
4095
+ if (resumeData && !runId) {
4096
+ throw new Error("runId is required when resumeData is provided");
4097
+ }
4098
+ const agentObj = mastra.getAgentById(agentId);
4099
+ if (!agentObj) {
4100
+ throw new Error(`Agent ${agentId} not found`);
4101
+ }
4102
+ if (!Array.isArray(messages)) {
4103
+ throw new Error("Messages must be an array of UIMessage objects");
4104
+ }
4105
+ const mergedOptions = {
4106
+ ...defaultOptions2,
4107
+ ...rest,
4108
+ ...runId && { runId },
4109
+ requestContext: requestContext || defaultOptions2?.requestContext
4110
+ };
4111
+ const result = resumeData ? await agentObj.resumeStream(resumeData, mergedOptions) : await agentObj.stream(messages, mergedOptions);
4112
+ let lastMessageId;
4113
+ if (messages.length) {
4114
+ const lastMessage = messages[messages.length - 1];
4115
+ if (lastMessage?.role === "assistant") {
4116
+ lastMessageId = lastMessage.id;
4117
+ }
4118
+ }
4119
+ return createUIMessageStream({
4120
+ originalMessages: messages,
4121
+ execute: async ({ writer }) => {
4122
+ for await (const part of toAISdkV5Stream(result, {
4123
+ from: "agent",
4124
+ lastMessageId,
4125
+ sendStart,
4126
+ sendFinish,
4127
+ sendReasoning,
4128
+ sendSources
4129
+ })) {
4130
+ writer.write(part);
4131
+ }
4132
+ }
4133
+ });
4134
+ }
1006
4135
  function chatRoute({
1007
4136
  path = "/chat/:agentId",
1008
4137
  agent,
1009
- defaultOptions
4138
+ defaultOptions: defaultOptions2,
4139
+ sendStart = true,
4140
+ sendFinish = true,
4141
+ sendReasoning = false,
4142
+ sendSources = false
1010
4143
  }) {
1011
4144
  if (!agent && !path.includes("/:agentId")) {
1012
4145
  throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
@@ -1035,6 +4168,14 @@ function chatRoute({
1035
4168
  schema: {
1036
4169
  type: "object",
1037
4170
  properties: {
4171
+ resumeData: {
4172
+ type: "object",
4173
+ description: "Resume data for the agent"
4174
+ },
4175
+ runId: {
4176
+ type: "string",
4177
+ description: "The run ID required when resuming an agent execution"
4178
+ },
1038
4179
  messages: {
1039
4180
  type: "array",
1040
4181
  description: "Array of messages in the conversation",
@@ -1105,9 +4246,9 @@ function chatRoute({
1105
4246
  }
1106
4247
  },
1107
4248
  handler: async (c) => {
1108
- const { messages, ...rest } = await c.req.json();
4249
+ const params = await c.req.json();
1109
4250
  const mastra = c.get("mastra");
1110
- const requestContext = c.get("requestContext");
4251
+ const contextRequestContext = c.get("requestContext");
1111
4252
  let agentToUse = agent;
1112
4253
  if (!agent) {
1113
4254
  const agentId = c.req.param("agentId");
@@ -1118,42 +4259,57 @@ function chatRoute({
1118
4259
  `Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
1119
4260
  );
1120
4261
  }
1121
- if (requestContext && defaultOptions?.requestContext) {
1122
- mastra.getLogger()?.warn(`"requestContext" set in the route options will be overridden by the request's "requestContext".`);
4262
+ const effectiveRequestContext = contextRequestContext || defaultOptions2?.requestContext || params.requestContext;
4263
+ if (contextRequestContext && defaultOptions2?.requestContext || contextRequestContext && params.requestContext || defaultOptions2?.requestContext && params.requestContext) {
4264
+ mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
1123
4265
  }
1124
4266
  if (!agentToUse) {
1125
4267
  throw new Error("Agent ID is required");
1126
4268
  }
1127
- const agentObj = mastra.getAgent(agentToUse);
1128
- if (!agentObj) {
1129
- throw new Error(`Agent ${agentToUse} not found`);
1130
- }
1131
- const result = await agentObj.stream(messages, {
1132
- ...defaultOptions,
1133
- ...rest,
1134
- requestContext: requestContext || defaultOptions?.requestContext
1135
- });
1136
- let lastMessageId;
1137
- if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1138
- lastMessageId = messages[messages.length - 1].id;
1139
- }
1140
- const uiMessageStream = ai.createUIMessageStream({
1141
- originalMessages: messages,
1142
- execute: async ({ writer }) => {
1143
- for await (const part of toAISdkV5Stream(result, { from: "agent", lastMessageId })) {
1144
- writer.write(part);
1145
- }
1146
- }
4269
+ const uiMessageStream = await handleChatStream({
4270
+ mastra,
4271
+ agentId: agentToUse,
4272
+ params: {
4273
+ ...params,
4274
+ requestContext: effectiveRequestContext
4275
+ },
4276
+ defaultOptions: defaultOptions2,
4277
+ sendStart,
4278
+ sendFinish,
4279
+ sendReasoning,
4280
+ sendSources
1147
4281
  });
1148
- return ai.createUIMessageStreamResponse({
4282
+ return createUIMessageStreamResponse({
1149
4283
  stream: uiMessageStream
1150
4284
  });
1151
4285
  }
1152
4286
  });
1153
4287
  }
4288
+ async function handleWorkflowStream({
4289
+ mastra,
4290
+ workflowId,
4291
+ params,
4292
+ includeTextStreamParts = true
4293
+ }) {
4294
+ const { runId, resourceId, inputData, resumeData, requestContext, ...rest } = params;
4295
+ const workflowObj = mastra.getWorkflowById(workflowId);
4296
+ if (!workflowObj) {
4297
+ throw new Error(`Workflow ${workflowId} not found`);
4298
+ }
4299
+ const run = await workflowObj.createRun({ runId, resourceId, ...rest });
4300
+ const stream = resumeData ? run.resumeStream({ resumeData, ...rest, requestContext }) : run.stream({ inputData, ...rest, requestContext });
4301
+ return createUIMessageStream({
4302
+ execute: async ({ writer }) => {
4303
+ for await (const part of toAISdkV5Stream(stream, { from: "workflow", includeTextStreamParts })) {
4304
+ writer.write(part);
4305
+ }
4306
+ }
4307
+ });
4308
+ }
1154
4309
  function workflowRoute({
1155
4310
  path = "/api/workflows/:workflowId/stream",
1156
- workflow
4311
+ workflow,
4312
+ includeTextStreamParts = true
1157
4313
  }) {
1158
4314
  if (!workflow && !path.includes("/:workflowId")) {
1159
4315
  throw new Error("Path must include :workflowId to route to the correct workflow or pass the workflow explicitly");
@@ -1180,9 +4336,13 @@ function workflowRoute({
1180
4336
  schema: {
1181
4337
  type: "object",
1182
4338
  properties: {
4339
+ runId: { type: "string" },
4340
+ resourceId: { type: "string" },
1183
4341
  inputData: { type: "object", additionalProperties: true },
4342
+ resumeData: { type: "object", additionalProperties: true },
1184
4343
  requestContext: { type: "object", additionalProperties: true },
1185
- tracingOptions: { type: "object", additionalProperties: true }
4344
+ tracingOptions: { type: "object", additionalProperties: true },
4345
+ step: { type: "string" }
1186
4346
  }
1187
4347
  }
1188
4348
  }
@@ -1200,8 +4360,9 @@ function workflowRoute({
1200
4360
  }
1201
4361
  },
1202
4362
  handler: async (c) => {
1203
- const { inputData, resumeData, ...rest } = await c.req.json();
4363
+ const params = await c.req.json();
1204
4364
  const mastra = c.get("mastra");
4365
+ const contextRequestContext = c.get("requestContext");
1205
4366
  let workflowToUse = workflow;
1206
4367
  if (!workflow) {
1207
4368
  const workflowId = c.req.param("workflowId");
@@ -1215,27 +4376,51 @@ function workflowRoute({
1215
4376
  if (!workflowToUse) {
1216
4377
  throw new Error("Workflow ID is required");
1217
4378
  }
1218
- const workflowObj = mastra.getWorkflow(workflowToUse);
1219
- if (!workflowObj) {
1220
- throw new Error(`Workflow ${workflowToUse} not found`);
4379
+ if (contextRequestContext && params.requestContext) {
4380
+ mastra.getLogger()?.warn(
4381
+ `"requestContext" from the request body will be ignored because "requestContext" is already set in the route options.`
4382
+ );
1221
4383
  }
1222
- const run = await workflowObj.createRun();
1223
- const stream = resumeData ? run.resumeStream({ resumeData, ...rest }) : run.stream({ inputData, ...rest });
1224
- const uiMessageStream = ai.createUIMessageStream({
1225
- execute: async ({ writer }) => {
1226
- for await (const part of toAISdkV5Stream(stream, { from: "workflow" })) {
1227
- writer.write(part);
1228
- }
1229
- }
4384
+ const uiMessageStream = await handleWorkflowStream({
4385
+ mastra,
4386
+ workflowId: workflowToUse,
4387
+ params: {
4388
+ ...params,
4389
+ requestContext: contextRequestContext || params.requestContext
4390
+ },
4391
+ includeTextStreamParts
1230
4392
  });
1231
- return ai.createUIMessageStreamResponse({ stream: uiMessageStream });
4393
+ return createUIMessageStreamResponse({ stream: uiMessageStream });
4394
+ }
4395
+ });
4396
+ }
4397
+ async function handleNetworkStream({
4398
+ mastra,
4399
+ agentId,
4400
+ params,
4401
+ defaultOptions: defaultOptions2
4402
+ }) {
4403
+ const { messages, ...rest } = params;
4404
+ const agentObj = mastra.getAgentById(agentId);
4405
+ if (!agentObj) {
4406
+ throw new Error(`Agent ${agentId} not found`);
4407
+ }
4408
+ const result = await agentObj.network(messages, {
4409
+ ...defaultOptions2,
4410
+ ...rest
4411
+ });
4412
+ return createUIMessageStream({
4413
+ execute: async ({ writer }) => {
4414
+ for await (const part of toAISdkV5Stream(result, { from: "network" })) {
4415
+ writer.write(part);
4416
+ }
1232
4417
  }
1233
4418
  });
1234
4419
  }
1235
4420
  function networkRoute({
1236
4421
  path = "/network/:agentId",
1237
4422
  agent,
1238
- defaultOptions
4423
+ defaultOptions: defaultOptions2
1239
4424
  }) {
1240
4425
  if (!agent && !path.includes("/:agentId")) {
1241
4426
  throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
@@ -1292,8 +4477,9 @@ function networkRoute({
1292
4477
  }
1293
4478
  },
1294
4479
  handler: async (c) => {
1295
- const { messages, ...rest } = await c.req.json();
4480
+ const params = await c.req.json();
1296
4481
  const mastra = c.get("mastra");
4482
+ const contextRequestContext = c.get("requestContext");
1297
4483
  let agentToUse = agent;
1298
4484
  if (!agent) {
1299
4485
  const agentId = c.req.param("agentId");
@@ -1304,28 +4490,475 @@ function networkRoute({
1304
4490
  `Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
1305
4491
  );
1306
4492
  }
4493
+ const effectiveRequestContext = contextRequestContext || defaultOptions2?.requestContext || params.requestContext;
4494
+ if (contextRequestContext && defaultOptions2?.requestContext || contextRequestContext && params.requestContext || defaultOptions2?.requestContext && params.requestContext) {
4495
+ mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
4496
+ }
1307
4497
  if (!agentToUse) {
1308
4498
  throw new Error("Agent ID is required");
1309
4499
  }
1310
- const agentObj = mastra.getAgent(agentToUse);
1311
- if (!agentObj) {
1312
- throw new Error(`Agent ${agentToUse} not found`);
4500
+ const uiMessageStream = await handleNetworkStream({
4501
+ mastra,
4502
+ agentId: agentToUse,
4503
+ params: {
4504
+ ...params,
4505
+ requestContext: effectiveRequestContext
4506
+ },
4507
+ defaultOptions: defaultOptions2
4508
+ });
4509
+ return createUIMessageStreamResponse({ stream: uiMessageStream });
4510
+ }
4511
+ });
4512
+ }
4513
+ function withMastra(model, options = {}) {
4514
+ const { memory, inputProcessors = [], outputProcessors = [] } = options;
4515
+ const allInputProcessors = [...inputProcessors];
4516
+ const allOutputProcessors = [...outputProcessors];
4517
+ if (memory) {
4518
+ const { storage, lastMessages, semanticRecall, workingMemory } = memory;
4519
+ const isWorkingMemoryEnabled = typeof workingMemory === "object" && workingMemory.enabled !== false;
4520
+ if (isWorkingMemoryEnabled && typeof workingMemory === "object") {
4521
+ let template;
4522
+ if (workingMemory.template) {
4523
+ template = {
4524
+ format: "markdown",
4525
+ content: workingMemory.template
4526
+ };
4527
+ }
4528
+ const workingMemoryProcessor = new processors.WorkingMemory({
4529
+ storage,
4530
+ template,
4531
+ scope: workingMemory.scope,
4532
+ useVNext: "version" in workingMemory && workingMemory.version === "vnext"
4533
+ });
4534
+ allInputProcessors.push(workingMemoryProcessor);
4535
+ }
4536
+ if (lastMessages !== false && lastMessages !== void 0) {
4537
+ const messageHistory = new processors.MessageHistory({
4538
+ storage,
4539
+ lastMessages: typeof lastMessages === "number" ? lastMessages : void 0
4540
+ });
4541
+ allInputProcessors.push(messageHistory);
4542
+ allOutputProcessors.push(messageHistory);
4543
+ }
4544
+ if (semanticRecall) {
4545
+ const { vector, embedder, indexName, ...semanticConfig } = semanticRecall;
4546
+ const semanticRecallProcessor = new processors.SemanticRecall({
4547
+ storage,
4548
+ vector,
4549
+ embedder,
4550
+ indexName: indexName || "memory_messages",
4551
+ ...semanticConfig
4552
+ });
4553
+ allInputProcessors.push(semanticRecallProcessor);
4554
+ allOutputProcessors.push(semanticRecallProcessor);
4555
+ }
4556
+ }
4557
+ return wrapLanguageModel({
4558
+ model,
4559
+ middleware: createProcessorMiddleware({
4560
+ inputProcessors: allInputProcessors,
4561
+ outputProcessors: allOutputProcessors,
4562
+ memory: memory ? {
4563
+ threadId: memory.threadId,
4564
+ resourceId: memory.resourceId
4565
+ } : void 0
4566
+ })
4567
+ });
4568
+ }
4569
+ function createProcessorMiddleware(options) {
4570
+ const { inputProcessors = [], outputProcessors = [], memory } = options;
4571
+ const requestContext = new di.RequestContext();
4572
+ if (memory) {
4573
+ requestContext.set("MastraMemory", {
4574
+ thread: memory.threadId ? { id: memory.threadId } : void 0,
4575
+ resourceId: memory.resourceId,
4576
+ memoryConfig: memory.config
4577
+ });
4578
+ }
4579
+ return {
4580
+ middlewareVersion: "v2",
4581
+ /**
4582
+ * Transform params runs input processors (processInput)
4583
+ */
4584
+ async transformParams({ params }) {
4585
+ const messageList = new agent.MessageList({
4586
+ threadId: memory?.threadId,
4587
+ resourceId: memory?.resourceId
4588
+ });
4589
+ for (const msg of params.prompt) {
4590
+ if (msg.role === "system") {
4591
+ messageList.addSystem(msg.content);
4592
+ } else {
4593
+ messageList.add(msg, "input");
4594
+ }
4595
+ }
4596
+ for (const processor of inputProcessors) {
4597
+ if (processor.processInput) {
4598
+ try {
4599
+ await processor.processInput({
4600
+ messages: messageList.get.input.db(),
4601
+ systemMessages: messageList.getAllSystemMessages(),
4602
+ messageList,
4603
+ requestContext,
4604
+ abort: (reason) => {
4605
+ throw new agent.TripWire(reason || "Aborted by processor");
4606
+ }
4607
+ });
4608
+ } catch (error) {
4609
+ if (error instanceof agent.TripWire) {
4610
+ return {
4611
+ ...params,
4612
+ providerOptions: {
4613
+ ...params.providerOptions,
4614
+ mastraProcessors: {
4615
+ tripwire: true,
4616
+ reason: error.message
4617
+ }
4618
+ }
4619
+ };
4620
+ }
4621
+ throw error;
4622
+ }
4623
+ }
4624
+ }
4625
+ const newPrompt = messageList.get.all.aiV5.prompt().map(agent.MessageList.aiV5ModelMessageToV2PromptMessage);
4626
+ return {
4627
+ ...params,
4628
+ prompt: newPrompt
4629
+ };
4630
+ },
4631
+ /**
4632
+ * Wrap generate for non-streaming output processing
4633
+ */
4634
+ async wrapGenerate({ doGenerate, params }) {
4635
+ const processorState = params.providerOptions?.mastraProcessors;
4636
+ if (processorState?.tripwire) {
4637
+ const reason = processorState.reason || "Blocked by processor";
4638
+ return {
4639
+ content: [{ type: "text", text: reason }],
4640
+ finishReason: "stop",
4641
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
4642
+ warnings: [{ type: "other", message: `Tripwire: ${reason}` }]
4643
+ };
1313
4644
  }
1314
- const result = await agentObj.network(messages, {
1315
- ...defaultOptions,
1316
- ...rest
4645
+ const result = await doGenerate();
4646
+ if (!outputProcessors.length) return result;
4647
+ const messageList = new agent.MessageList({
4648
+ threadId: memory?.threadId,
4649
+ resourceId: memory?.resourceId
1317
4650
  });
1318
- const uiMessageStream = ai.createUIMessageStream({
1319
- execute: async ({ writer }) => {
1320
- for await (const part of toAISdkV5Stream(result, { from: "network" })) {
1321
- writer.write(part);
4651
+ for (const msg of params.prompt) {
4652
+ if (msg.role === "system") {
4653
+ messageList.addSystem(msg.content);
4654
+ } else {
4655
+ messageList.add(msg, "input");
4656
+ }
4657
+ }
4658
+ const textContent = result.content.filter((c) => c.type === "text").map((c) => c.text).join("");
4659
+ const responseMessage = {
4660
+ id: crypto.randomUUID(),
4661
+ role: "assistant",
4662
+ content: {
4663
+ format: 2,
4664
+ parts: [{ type: "text", text: textContent }]
4665
+ },
4666
+ createdAt: /* @__PURE__ */ new Date(),
4667
+ ...memory?.threadId && { threadId: memory.threadId },
4668
+ ...memory?.resourceId && { resourceId: memory.resourceId }
4669
+ };
4670
+ messageList.add(responseMessage, "response");
4671
+ for (const processor of outputProcessors) {
4672
+ if (processor.processOutputResult) {
4673
+ try {
4674
+ await processor.processOutputResult({
4675
+ messages: messageList.get.all.db(),
4676
+ messageList,
4677
+ requestContext,
4678
+ abort: (reason) => {
4679
+ throw new agent.TripWire(reason || "Aborted by processor");
4680
+ }
4681
+ });
4682
+ } catch (error) {
4683
+ if (error instanceof agent.TripWire) {
4684
+ return {
4685
+ content: [{ type: "text", text: error.message }],
4686
+ finishReason: "stop",
4687
+ usage: result.usage,
4688
+ warnings: [{ type: "other", message: `Output blocked: ${error.message}` }]
4689
+ };
4690
+ }
4691
+ throw error;
1322
4692
  }
1323
4693
  }
4694
+ }
4695
+ const processedText = messageList.get.response.db().map((m) => extractTextFromMastraMessage(m)).join("");
4696
+ return {
4697
+ ...result,
4698
+ content: [{ type: "text", text: processedText }]
4699
+ };
4700
+ },
4701
+ /**
4702
+ * Wrap stream for streaming output processing
4703
+ */
4704
+ async wrapStream({ doStream, params }) {
4705
+ const processorState = params.providerOptions?.mastraProcessors;
4706
+ if (processorState?.tripwire) {
4707
+ const reason = processorState.reason || "Blocked by processor";
4708
+ return {
4709
+ stream: createBlockedStream(reason)
4710
+ };
4711
+ }
4712
+ const { stream: stream$1, ...rest } = await doStream();
4713
+ if (!outputProcessors.length) return { stream: stream$1, ...rest };
4714
+ const processorStates = /* @__PURE__ */ new Map();
4715
+ const runId = crypto.randomUUID();
4716
+ const transformedStream = stream$1.pipeThrough(
4717
+ new TransformStream({
4718
+ async transform(chunk, controller) {
4719
+ let mastraChunk = stream.convertFullStreamChunkToMastra(
4720
+ chunk,
4721
+ { runId }
4722
+ );
4723
+ if (!mastraChunk) {
4724
+ controller.enqueue(chunk);
4725
+ return;
4726
+ }
4727
+ for (const processor of outputProcessors) {
4728
+ if (processor.processOutputStream && mastraChunk) {
4729
+ let state = processorStates.get(processor.id);
4730
+ if (!state) {
4731
+ state = { streamParts: [], customState: {} };
4732
+ processorStates.set(processor.id, state);
4733
+ }
4734
+ state.streamParts.push(mastraChunk);
4735
+ try {
4736
+ const result = await processor.processOutputStream({
4737
+ part: mastraChunk,
4738
+ streamParts: state.streamParts,
4739
+ state: state.customState,
4740
+ requestContext,
4741
+ abort: (reason) => {
4742
+ throw new agent.TripWire(reason || "Aborted by processor");
4743
+ }
4744
+ });
4745
+ if (result === null || result === void 0) {
4746
+ mastraChunk = void 0;
4747
+ } else {
4748
+ mastraChunk = result;
4749
+ }
4750
+ } catch (error) {
4751
+ if (error instanceof agent.TripWire) {
4752
+ controller.enqueue({
4753
+ type: "error",
4754
+ error: new Error(error.message)
4755
+ });
4756
+ controller.terminate();
4757
+ return;
4758
+ }
4759
+ throw error;
4760
+ }
4761
+ }
4762
+ }
4763
+ if (mastraChunk) {
4764
+ const aiChunk = convertMastraChunkToAISDKStreamPart(mastraChunk);
4765
+ if (aiChunk) {
4766
+ controller.enqueue(aiChunk);
4767
+ }
4768
+ }
4769
+ }
4770
+ })
4771
+ );
4772
+ return { stream: transformedStream, ...rest };
4773
+ }
4774
+ };
4775
+ }
4776
+ function createBlockedStream(reason) {
4777
+ return new ReadableStream({
4778
+ start(controller) {
4779
+ const id = crypto.randomUUID();
4780
+ controller.enqueue({
4781
+ type: "text-start",
4782
+ id
4783
+ });
4784
+ controller.enqueue({
4785
+ type: "text-delta",
4786
+ id,
4787
+ delta: reason
4788
+ });
4789
+ controller.enqueue({
4790
+ type: "text-end",
4791
+ id
4792
+ });
4793
+ controller.enqueue({
4794
+ type: "finish",
4795
+ finishReason: "stop",
4796
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
1324
4797
  });
1325
- return ai.createUIMessageStreamResponse({ stream: uiMessageStream });
4798
+ controller.close();
1326
4799
  }
1327
4800
  });
1328
4801
  }
4802
+ function extractTextFromMastraMessage(msg) {
4803
+ const content = msg.content;
4804
+ if (typeof content === "string") {
4805
+ return content;
4806
+ }
4807
+ if (content?.parts) {
4808
+ return content.parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join("");
4809
+ }
4810
+ return "";
4811
+ }
4812
+ function convertMastraChunkToAISDKStreamPart(chunk) {
4813
+ switch (chunk.type) {
4814
+ // Text streaming
4815
+ case "text-start":
4816
+ return {
4817
+ type: "text-start",
4818
+ id: chunk.payload.id || crypto.randomUUID(),
4819
+ providerMetadata: chunk.payload.providerMetadata
4820
+ };
4821
+ case "text-delta":
4822
+ return {
4823
+ type: "text-delta",
4824
+ id: chunk.payload.id || crypto.randomUUID(),
4825
+ delta: chunk.payload.text,
4826
+ providerMetadata: chunk.payload.providerMetadata
4827
+ };
4828
+ case "text-end":
4829
+ return {
4830
+ type: "text-end",
4831
+ id: chunk.payload.id || crypto.randomUUID(),
4832
+ providerMetadata: chunk.payload.providerMetadata
4833
+ };
4834
+ // Reasoning streaming
4835
+ case "reasoning-start":
4836
+ return {
4837
+ type: "reasoning-start",
4838
+ id: chunk.payload.id || crypto.randomUUID(),
4839
+ providerMetadata: chunk.payload.providerMetadata
4840
+ };
4841
+ case "reasoning-delta":
4842
+ return {
4843
+ type: "reasoning-delta",
4844
+ id: chunk.payload.id || crypto.randomUUID(),
4845
+ delta: chunk.payload.text,
4846
+ providerMetadata: chunk.payload.providerMetadata
4847
+ };
4848
+ case "reasoning-end":
4849
+ return {
4850
+ type: "reasoning-end",
4851
+ id: chunk.payload.id || crypto.randomUUID(),
4852
+ providerMetadata: chunk.payload.providerMetadata
4853
+ };
4854
+ // Tool call (complete)
4855
+ case "tool-call":
4856
+ return {
4857
+ type: "tool-call",
4858
+ toolCallId: chunk.payload.toolCallId,
4859
+ toolName: chunk.payload.toolName,
4860
+ input: JSON.stringify(chunk.payload.args),
4861
+ providerExecuted: chunk.payload.providerExecuted,
4862
+ providerMetadata: chunk.payload.providerMetadata
4863
+ };
4864
+ // Tool call input streaming
4865
+ case "tool-call-input-streaming-start":
4866
+ return {
4867
+ type: "tool-input-start",
4868
+ id: chunk.payload.toolCallId,
4869
+ toolName: chunk.payload.toolName,
4870
+ providerExecuted: chunk.payload.providerExecuted,
4871
+ providerMetadata: chunk.payload.providerMetadata
4872
+ };
4873
+ case "tool-call-delta":
4874
+ return {
4875
+ type: "tool-input-delta",
4876
+ id: chunk.payload.toolCallId,
4877
+ delta: chunk.payload.argsTextDelta,
4878
+ providerMetadata: chunk.payload.providerMetadata
4879
+ };
4880
+ case "tool-call-input-streaming-end":
4881
+ return {
4882
+ type: "tool-input-end",
4883
+ id: chunk.payload.toolCallId,
4884
+ providerMetadata: chunk.payload.providerMetadata
4885
+ };
4886
+ // Tool result
4887
+ case "tool-result":
4888
+ return {
4889
+ type: "tool-result",
4890
+ toolCallId: chunk.payload.toolCallId,
4891
+ toolName: chunk.payload.toolName,
4892
+ result: { type: "json", value: chunk.payload.result },
4893
+ isError: chunk.payload.isError,
4894
+ providerExecuted: chunk.payload.providerExecuted,
4895
+ providerMetadata: chunk.payload.providerMetadata
4896
+ };
4897
+ // Source (citations)
4898
+ case "source":
4899
+ if (chunk.payload.sourceType === "url") {
4900
+ return {
4901
+ type: "source",
4902
+ sourceType: "url",
4903
+ id: chunk.payload.id,
4904
+ url: chunk.payload.url,
4905
+ title: chunk.payload.title,
4906
+ providerMetadata: chunk.payload.providerMetadata
4907
+ };
4908
+ } else {
4909
+ return {
4910
+ type: "source",
4911
+ sourceType: "document",
4912
+ id: chunk.payload.id,
4913
+ mediaType: chunk.payload.mimeType,
4914
+ title: chunk.payload.title,
4915
+ filename: chunk.payload.filename,
4916
+ providerMetadata: chunk.payload.providerMetadata
4917
+ };
4918
+ }
4919
+ // File output
4920
+ case "file":
4921
+ return {
4922
+ type: "file",
4923
+ data: chunk.payload.data || chunk.payload.base64,
4924
+ mediaType: chunk.payload.mimeType
4925
+ };
4926
+ // Response metadata
4927
+ case "response-metadata":
4928
+ return {
4929
+ type: "response-metadata",
4930
+ ...chunk.payload
4931
+ };
4932
+ // Raw provider data
4933
+ case "raw":
4934
+ return {
4935
+ type: "raw",
4936
+ rawValue: chunk.payload
4937
+ };
4938
+ // Finish
4939
+ case "finish": {
4940
+ const usage = chunk.payload.output?.usage;
4941
+ return {
4942
+ type: "finish",
4943
+ finishReason: toAISDKFinishReason(chunk.payload.stepResult?.reason || "stop"),
4944
+ usage: usage ? {
4945
+ inputTokens: usage.inputTokens || 0,
4946
+ outputTokens: usage.outputTokens || 0,
4947
+ totalTokens: usage.totalTokens || 0
4948
+ } : { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
4949
+ providerMetadata: chunk.payload.metadata?.providerMetadata
4950
+ };
4951
+ }
4952
+ // Error
4953
+ case "error":
4954
+ return {
4955
+ type: "error",
4956
+ error: chunk.payload.error || chunk.payload
4957
+ };
4958
+ default:
4959
+ return null;
4960
+ }
4961
+ }
1329
4962
 
1330
4963
  // src/to-ai-sdk-format.ts
1331
4964
  function toAISdkFormat() {
@@ -1335,9 +4968,13 @@ function toAISdkFormat() {
1335
4968
  }
1336
4969
 
1337
4970
  exports.chatRoute = chatRoute;
4971
+ exports.handleChatStream = handleChatStream;
4972
+ exports.handleNetworkStream = handleNetworkStream;
4973
+ exports.handleWorkflowStream = handleWorkflowStream;
1338
4974
  exports.networkRoute = networkRoute;
1339
4975
  exports.toAISdkFormat = toAISdkFormat;
1340
4976
  exports.toAISdkStream = toAISdkV5Stream;
4977
+ exports.withMastra = withMastra;
1341
4978
  exports.workflowRoute = workflowRoute;
1342
4979
  //# sourceMappingURL=index.cjs.map
1343
4980
  //# sourceMappingURL=index.cjs.map