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

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