@mastra/ai-sdk 0.0.0-main-test-2-20251127211532 → 0.0.0-mastra-auto-detect-server-20260108233416

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