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

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