@mastra/ai-sdk 1.0.0-beta.0 → 1.0.0-beta.10

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