@mastra/ai-sdk 0.0.0-span-scorring-test-20251124132129 → 0.0.0-standard-schema-20260126101119

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