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