@mastra/ai-sdk 1.0.0-beta.0 → 1.0.0-beta.10
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 +325 -0
- package/README.md +60 -0
- 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 +90 -3
- package/dist/chat-route.d.ts.map +1 -1
- package/dist/chunk-DES3K4SD.cjs +17 -0
- package/dist/chunk-DES3K4SD.cjs.map +1 -0
- package/dist/chunk-KYQEM4AK.js +294 -0
- package/dist/chunk-KYQEM4AK.js.map +1 -0
- package/dist/chunk-TD7TJ4N5.cjs +297 -0
- package/dist/chunk-TD7TJ4N5.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 +83 -3
- package/dist/convert-messages.d.ts.map +1 -1
- package/dist/convert-streams.d.ts +64 -1
- package/dist/convert-streams.d.ts.map +1 -1
- package/dist/helpers.d.ts +9 -3
- package/dist/helpers.d.ts.map +1 -1
- package/dist/index.cjs +3872 -118
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +8 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3848 -117
- 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 +63 -2
- package/dist/network-route.d.ts.map +1 -1
- package/dist/token-5ZTQBFQ6.cjs +63 -0
- package/dist/token-5ZTQBFQ6.cjs.map +1 -0
- package/dist/token-UOO4N54I.js +61 -0
- package/dist/token-UOO4N54I.js.map +1 -0
- package/dist/token-util-DUN56AZR.cjs +9 -0
- package/dist/token-util-DUN56AZR.cjs.map +1 -0
- package/dist/token-util-JCUK3SCT.js +7 -0
- package/dist/token-util-JCUK3SCT.js.map +1 -0
- package/dist/transformers.d.ts +136 -10
- package/dist/transformers.d.ts.map +1 -1
- package/dist/ui.cjs +0 -1
- package/dist/ui.cjs.map +1 -1
- package/dist/ui.js +0 -1
- package/dist/ui.js.map +1 -1
- package/dist/utils.d.ts +2 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/workflow-route.d.ts +68 -1
- package/dist/workflow-route.d.ts.map +1 -1
- package/package.json +9 -7
package/dist/index.cjs
CHANGED
|
@@ -1,15 +1,2966 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var server = require('@mastra/core/server');
|
|
4
|
-
var
|
|
4
|
+
var z4 = require('zod/v4');
|
|
5
|
+
var v3 = require('zod/v3');
|
|
5
6
|
var stream = require('@mastra/core/stream');
|
|
7
|
+
var agent = require('@mastra/core/agent');
|
|
8
|
+
var di = require('@mastra/core/di');
|
|
9
|
+
var processors = require('@mastra/core/processors');
|
|
6
10
|
|
|
7
|
-
|
|
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
|
+
Error.stackTraceLimit = 0;
|
|
232
|
+
try {
|
|
233
|
+
return _parse(text2);
|
|
234
|
+
} finally {
|
|
235
|
+
Error.stackTraceLimit = stackTraceLimit;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
var validatorSymbol = Symbol.for("vercel.ai.validator");
|
|
239
|
+
function validator(validate) {
|
|
240
|
+
return { [validatorSymbol]: true, validate };
|
|
241
|
+
}
|
|
242
|
+
function isValidator(value) {
|
|
243
|
+
return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value;
|
|
244
|
+
}
|
|
245
|
+
function asValidator(value) {
|
|
246
|
+
return isValidator(value) ? value : typeof value === "function" ? value() : standardSchemaValidator(value);
|
|
247
|
+
}
|
|
248
|
+
function standardSchemaValidator(standardSchema) {
|
|
249
|
+
return validator(async (value) => {
|
|
250
|
+
const result = await standardSchema["~standard"].validate(value);
|
|
251
|
+
return result.issues == null ? { success: true, value: result.value } : {
|
|
252
|
+
success: false,
|
|
253
|
+
error: new TypeValidationError({
|
|
254
|
+
value,
|
|
255
|
+
cause: result.issues
|
|
256
|
+
})
|
|
257
|
+
};
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
async function validateTypes({
|
|
261
|
+
value,
|
|
262
|
+
schema
|
|
263
|
+
}) {
|
|
264
|
+
const result = await safeValidateTypes({ value, schema });
|
|
265
|
+
if (!result.success) {
|
|
266
|
+
throw TypeValidationError.wrap({ value, cause: result.error });
|
|
267
|
+
}
|
|
268
|
+
return result.value;
|
|
269
|
+
}
|
|
270
|
+
async function safeValidateTypes({
|
|
271
|
+
value,
|
|
272
|
+
schema
|
|
273
|
+
}) {
|
|
274
|
+
const validator2 = asValidator(schema);
|
|
275
|
+
try {
|
|
276
|
+
if (validator2.validate == null) {
|
|
277
|
+
return { success: true, value, rawValue: value };
|
|
278
|
+
}
|
|
279
|
+
const result = await validator2.validate(value);
|
|
280
|
+
if (result.success) {
|
|
281
|
+
return { success: true, value: result.value, rawValue: value };
|
|
282
|
+
}
|
|
283
|
+
return {
|
|
284
|
+
success: false,
|
|
285
|
+
error: TypeValidationError.wrap({ value, cause: result.error }),
|
|
286
|
+
rawValue: value
|
|
287
|
+
};
|
|
288
|
+
} catch (error) {
|
|
289
|
+
return {
|
|
290
|
+
success: false,
|
|
291
|
+
error: TypeValidationError.wrap({ value, cause: error }),
|
|
292
|
+
rawValue: value
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
async function safeParseJSON({
|
|
297
|
+
text: text2,
|
|
298
|
+
schema
|
|
299
|
+
}) {
|
|
300
|
+
try {
|
|
301
|
+
const value = secureJsonParse(text2);
|
|
302
|
+
if (schema == null) {
|
|
303
|
+
return { success: true, value, rawValue: value };
|
|
304
|
+
}
|
|
305
|
+
return await safeValidateTypes({ value, schema });
|
|
306
|
+
} catch (error) {
|
|
307
|
+
return {
|
|
308
|
+
success: false,
|
|
309
|
+
error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text: text2, cause: error }),
|
|
310
|
+
rawValue: void 0
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
var getRelativePath = (pathA, pathB) => {
|
|
315
|
+
let i = 0;
|
|
316
|
+
for (; i < pathA.length && i < pathB.length; i++) {
|
|
317
|
+
if (pathA[i] !== pathB[i]) break;
|
|
318
|
+
}
|
|
319
|
+
return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
|
|
320
|
+
};
|
|
321
|
+
var ignoreOverride = Symbol(
|
|
322
|
+
"Let zodToJsonSchema decide on which parser to use"
|
|
323
|
+
);
|
|
324
|
+
var defaultOptions = {
|
|
325
|
+
name: void 0,
|
|
326
|
+
$refStrategy: "root",
|
|
327
|
+
basePath: ["#"],
|
|
328
|
+
effectStrategy: "input",
|
|
329
|
+
pipeStrategy: "all",
|
|
330
|
+
dateStrategy: "format:date-time",
|
|
331
|
+
mapStrategy: "entries",
|
|
332
|
+
removeAdditionalStrategy: "passthrough",
|
|
333
|
+
allowedAdditionalProperties: true,
|
|
334
|
+
rejectedAdditionalProperties: false,
|
|
335
|
+
definitionPath: "definitions",
|
|
336
|
+
strictUnions: false,
|
|
337
|
+
definitions: {},
|
|
338
|
+
errorMessages: false,
|
|
339
|
+
patternStrategy: "escape",
|
|
340
|
+
applyRegexFlags: false,
|
|
341
|
+
emailStrategy: "format:email",
|
|
342
|
+
base64Strategy: "contentEncoding:base64",
|
|
343
|
+
nameStrategy: "ref"
|
|
344
|
+
};
|
|
345
|
+
var getDefaultOptions = (options) => typeof options === "string" ? {
|
|
346
|
+
...defaultOptions,
|
|
347
|
+
name: options
|
|
348
|
+
} : {
|
|
349
|
+
...defaultOptions,
|
|
350
|
+
...options
|
|
351
|
+
};
|
|
352
|
+
function parseAnyDef() {
|
|
353
|
+
return {};
|
|
354
|
+
}
|
|
355
|
+
function parseArrayDef(def, refs) {
|
|
356
|
+
var _a17, _b, _c;
|
|
357
|
+
const res = {
|
|
358
|
+
type: "array"
|
|
359
|
+
};
|
|
360
|
+
if (((_a17 = def.type) == null ? void 0 : _a17._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== v3.ZodFirstPartyTypeKind.ZodAny) {
|
|
361
|
+
res.items = parseDef(def.type._def, {
|
|
362
|
+
...refs,
|
|
363
|
+
currentPath: [...refs.currentPath, "items"]
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
if (def.minLength) {
|
|
367
|
+
res.minItems = def.minLength.value;
|
|
368
|
+
}
|
|
369
|
+
if (def.maxLength) {
|
|
370
|
+
res.maxItems = def.maxLength.value;
|
|
371
|
+
}
|
|
372
|
+
if (def.exactLength) {
|
|
373
|
+
res.minItems = def.exactLength.value;
|
|
374
|
+
res.maxItems = def.exactLength.value;
|
|
375
|
+
}
|
|
376
|
+
return res;
|
|
377
|
+
}
|
|
378
|
+
function parseBigintDef(def) {
|
|
379
|
+
const res = {
|
|
380
|
+
type: "integer",
|
|
381
|
+
format: "int64"
|
|
382
|
+
};
|
|
383
|
+
if (!def.checks) return res;
|
|
384
|
+
for (const check of def.checks) {
|
|
385
|
+
switch (check.kind) {
|
|
386
|
+
case "min":
|
|
387
|
+
if (check.inclusive) {
|
|
388
|
+
res.minimum = check.value;
|
|
389
|
+
} else {
|
|
390
|
+
res.exclusiveMinimum = check.value;
|
|
391
|
+
}
|
|
392
|
+
break;
|
|
393
|
+
case "max":
|
|
394
|
+
if (check.inclusive) {
|
|
395
|
+
res.maximum = check.value;
|
|
396
|
+
} else {
|
|
397
|
+
res.exclusiveMaximum = check.value;
|
|
398
|
+
}
|
|
399
|
+
break;
|
|
400
|
+
case "multipleOf":
|
|
401
|
+
res.multipleOf = check.value;
|
|
402
|
+
break;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
return res;
|
|
406
|
+
}
|
|
407
|
+
function parseBooleanDef() {
|
|
408
|
+
return { type: "boolean" };
|
|
409
|
+
}
|
|
410
|
+
function parseBrandedDef(_def, refs) {
|
|
411
|
+
return parseDef(_def.type._def, refs);
|
|
412
|
+
}
|
|
413
|
+
var parseCatchDef = (def, refs) => {
|
|
414
|
+
return parseDef(def.innerType._def, refs);
|
|
415
|
+
};
|
|
416
|
+
function parseDateDef(def, refs, overrideDateStrategy) {
|
|
417
|
+
const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy;
|
|
418
|
+
if (Array.isArray(strategy)) {
|
|
419
|
+
return {
|
|
420
|
+
anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
switch (strategy) {
|
|
424
|
+
case "string":
|
|
425
|
+
case "format:date-time":
|
|
426
|
+
return {
|
|
427
|
+
type: "string",
|
|
428
|
+
format: "date-time"
|
|
429
|
+
};
|
|
430
|
+
case "format:date":
|
|
431
|
+
return {
|
|
432
|
+
type: "string",
|
|
433
|
+
format: "date"
|
|
434
|
+
};
|
|
435
|
+
case "integer":
|
|
436
|
+
return integerDateParser(def);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
var integerDateParser = (def) => {
|
|
440
|
+
const res = {
|
|
441
|
+
type: "integer",
|
|
442
|
+
format: "unix-time"
|
|
443
|
+
};
|
|
444
|
+
for (const check of def.checks) {
|
|
445
|
+
switch (check.kind) {
|
|
446
|
+
case "min":
|
|
447
|
+
res.minimum = check.value;
|
|
448
|
+
break;
|
|
449
|
+
case "max":
|
|
450
|
+
res.maximum = check.value;
|
|
451
|
+
break;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return res;
|
|
455
|
+
};
|
|
456
|
+
function parseDefaultDef(_def, refs) {
|
|
457
|
+
return {
|
|
458
|
+
...parseDef(_def.innerType._def, refs),
|
|
459
|
+
default: _def.defaultValue()
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
function parseEffectsDef(_def, refs) {
|
|
463
|
+
return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef();
|
|
464
|
+
}
|
|
465
|
+
function parseEnumDef(def) {
|
|
466
|
+
return {
|
|
467
|
+
type: "string",
|
|
468
|
+
enum: Array.from(def.values)
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
var isJsonSchema7AllOfType = (type) => {
|
|
472
|
+
if ("type" in type && type.type === "string") return false;
|
|
473
|
+
return "allOf" in type;
|
|
474
|
+
};
|
|
475
|
+
function parseIntersectionDef(def, refs) {
|
|
476
|
+
const allOf = [
|
|
477
|
+
parseDef(def.left._def, {
|
|
478
|
+
...refs,
|
|
479
|
+
currentPath: [...refs.currentPath, "allOf", "0"]
|
|
480
|
+
}),
|
|
481
|
+
parseDef(def.right._def, {
|
|
482
|
+
...refs,
|
|
483
|
+
currentPath: [...refs.currentPath, "allOf", "1"]
|
|
484
|
+
})
|
|
485
|
+
].filter((x) => !!x);
|
|
486
|
+
const mergedAllOf = [];
|
|
487
|
+
allOf.forEach((schema) => {
|
|
488
|
+
if (isJsonSchema7AllOfType(schema)) {
|
|
489
|
+
mergedAllOf.push(...schema.allOf);
|
|
490
|
+
} else {
|
|
491
|
+
let nestedSchema = schema;
|
|
492
|
+
if ("additionalProperties" in schema && schema.additionalProperties === false) {
|
|
493
|
+
const { additionalProperties, ...rest } = schema;
|
|
494
|
+
nestedSchema = rest;
|
|
495
|
+
}
|
|
496
|
+
mergedAllOf.push(nestedSchema);
|
|
497
|
+
}
|
|
498
|
+
});
|
|
499
|
+
return mergedAllOf.length ? { allOf: mergedAllOf } : void 0;
|
|
500
|
+
}
|
|
501
|
+
function parseLiteralDef(def) {
|
|
502
|
+
const parsedType = typeof def.value;
|
|
503
|
+
if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
|
|
504
|
+
return {
|
|
505
|
+
type: Array.isArray(def.value) ? "array" : "object"
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
return {
|
|
509
|
+
type: parsedType === "bigint" ? "integer" : parsedType,
|
|
510
|
+
const: def.value
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
var emojiRegex = void 0;
|
|
514
|
+
var zodPatterns = {
|
|
515
|
+
/**
|
|
516
|
+
* `c` was changed to `[cC]` to replicate /i flag
|
|
517
|
+
*/
|
|
518
|
+
cuid: /^[cC][^\s-]{8,}$/,
|
|
519
|
+
cuid2: /^[0-9a-z]+$/,
|
|
520
|
+
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
|
|
521
|
+
/**
|
|
522
|
+
* `a-z` was added to replicate /i flag
|
|
523
|
+
*/
|
|
524
|
+
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
|
|
525
|
+
/**
|
|
526
|
+
* Constructed a valid Unicode RegExp
|
|
527
|
+
*
|
|
528
|
+
* Lazily instantiate since this type of regex isn't supported
|
|
529
|
+
* in all envs (e.g. React Native).
|
|
530
|
+
*
|
|
531
|
+
* See:
|
|
532
|
+
* https://github.com/colinhacks/zod/issues/2433
|
|
533
|
+
* Fix in Zod:
|
|
534
|
+
* https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
|
|
535
|
+
*/
|
|
536
|
+
emoji: () => {
|
|
537
|
+
if (emojiRegex === void 0) {
|
|
538
|
+
emojiRegex = RegExp(
|
|
539
|
+
"^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
|
|
540
|
+
"u"
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
return emojiRegex;
|
|
544
|
+
},
|
|
545
|
+
/**
|
|
546
|
+
* Unused
|
|
547
|
+
*/
|
|
548
|
+
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}$/,
|
|
549
|
+
/**
|
|
550
|
+
* Unused
|
|
551
|
+
*/
|
|
552
|
+
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])$/,
|
|
553
|
+
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])$/,
|
|
554
|
+
/**
|
|
555
|
+
* Unused
|
|
556
|
+
*/
|
|
557
|
+
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})))$/,
|
|
558
|
+
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])$/,
|
|
559
|
+
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
|
|
560
|
+
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
|
|
561
|
+
nanoid: /^[a-zA-Z0-9_-]{21}$/,
|
|
562
|
+
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
|
|
563
|
+
};
|
|
564
|
+
function parseStringDef(def, refs) {
|
|
565
|
+
const res = {
|
|
566
|
+
type: "string"
|
|
567
|
+
};
|
|
568
|
+
if (def.checks) {
|
|
569
|
+
for (const check of def.checks) {
|
|
570
|
+
switch (check.kind) {
|
|
571
|
+
case "min":
|
|
572
|
+
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
|
|
573
|
+
break;
|
|
574
|
+
case "max":
|
|
575
|
+
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
|
|
576
|
+
break;
|
|
577
|
+
case "email":
|
|
578
|
+
switch (refs.emailStrategy) {
|
|
579
|
+
case "format:email":
|
|
580
|
+
addFormat(res, "email", check.message, refs);
|
|
581
|
+
break;
|
|
582
|
+
case "format:idn-email":
|
|
583
|
+
addFormat(res, "idn-email", check.message, refs);
|
|
584
|
+
break;
|
|
585
|
+
case "pattern:zod":
|
|
586
|
+
addPattern(res, zodPatterns.email, check.message, refs);
|
|
587
|
+
break;
|
|
588
|
+
}
|
|
589
|
+
break;
|
|
590
|
+
case "url":
|
|
591
|
+
addFormat(res, "uri", check.message, refs);
|
|
592
|
+
break;
|
|
593
|
+
case "uuid":
|
|
594
|
+
addFormat(res, "uuid", check.message, refs);
|
|
595
|
+
break;
|
|
596
|
+
case "regex":
|
|
597
|
+
addPattern(res, check.regex, check.message, refs);
|
|
598
|
+
break;
|
|
599
|
+
case "cuid":
|
|
600
|
+
addPattern(res, zodPatterns.cuid, check.message, refs);
|
|
601
|
+
break;
|
|
602
|
+
case "cuid2":
|
|
603
|
+
addPattern(res, zodPatterns.cuid2, check.message, refs);
|
|
604
|
+
break;
|
|
605
|
+
case "startsWith":
|
|
606
|
+
addPattern(
|
|
607
|
+
res,
|
|
608
|
+
RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`),
|
|
609
|
+
check.message,
|
|
610
|
+
refs
|
|
611
|
+
);
|
|
612
|
+
break;
|
|
613
|
+
case "endsWith":
|
|
614
|
+
addPattern(
|
|
615
|
+
res,
|
|
616
|
+
RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`),
|
|
617
|
+
check.message,
|
|
618
|
+
refs
|
|
619
|
+
);
|
|
620
|
+
break;
|
|
621
|
+
case "datetime":
|
|
622
|
+
addFormat(res, "date-time", check.message, refs);
|
|
623
|
+
break;
|
|
624
|
+
case "date":
|
|
625
|
+
addFormat(res, "date", check.message, refs);
|
|
626
|
+
break;
|
|
627
|
+
case "time":
|
|
628
|
+
addFormat(res, "time", check.message, refs);
|
|
629
|
+
break;
|
|
630
|
+
case "duration":
|
|
631
|
+
addFormat(res, "duration", check.message, refs);
|
|
632
|
+
break;
|
|
633
|
+
case "length":
|
|
634
|
+
res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value;
|
|
635
|
+
res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value;
|
|
636
|
+
break;
|
|
637
|
+
case "includes": {
|
|
638
|
+
addPattern(
|
|
639
|
+
res,
|
|
640
|
+
RegExp(escapeLiteralCheckValue(check.value, refs)),
|
|
641
|
+
check.message,
|
|
642
|
+
refs
|
|
643
|
+
);
|
|
644
|
+
break;
|
|
645
|
+
}
|
|
646
|
+
case "ip": {
|
|
647
|
+
if (check.version !== "v6") {
|
|
648
|
+
addFormat(res, "ipv4", check.message, refs);
|
|
649
|
+
}
|
|
650
|
+
if (check.version !== "v4") {
|
|
651
|
+
addFormat(res, "ipv6", check.message, refs);
|
|
652
|
+
}
|
|
653
|
+
break;
|
|
654
|
+
}
|
|
655
|
+
case "base64url":
|
|
656
|
+
addPattern(res, zodPatterns.base64url, check.message, refs);
|
|
657
|
+
break;
|
|
658
|
+
case "jwt":
|
|
659
|
+
addPattern(res, zodPatterns.jwt, check.message, refs);
|
|
660
|
+
break;
|
|
661
|
+
case "cidr": {
|
|
662
|
+
if (check.version !== "v6") {
|
|
663
|
+
addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
|
|
664
|
+
}
|
|
665
|
+
if (check.version !== "v4") {
|
|
666
|
+
addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
|
|
667
|
+
}
|
|
668
|
+
break;
|
|
669
|
+
}
|
|
670
|
+
case "emoji":
|
|
671
|
+
addPattern(res, zodPatterns.emoji(), check.message, refs);
|
|
672
|
+
break;
|
|
673
|
+
case "ulid": {
|
|
674
|
+
addPattern(res, zodPatterns.ulid, check.message, refs);
|
|
675
|
+
break;
|
|
676
|
+
}
|
|
677
|
+
case "base64": {
|
|
678
|
+
switch (refs.base64Strategy) {
|
|
679
|
+
case "format:binary": {
|
|
680
|
+
addFormat(res, "binary", check.message, refs);
|
|
681
|
+
break;
|
|
682
|
+
}
|
|
683
|
+
case "contentEncoding:base64": {
|
|
684
|
+
res.contentEncoding = "base64";
|
|
685
|
+
break;
|
|
686
|
+
}
|
|
687
|
+
case "pattern:zod": {
|
|
688
|
+
addPattern(res, zodPatterns.base64, check.message, refs);
|
|
689
|
+
break;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
break;
|
|
693
|
+
}
|
|
694
|
+
case "nanoid": {
|
|
695
|
+
addPattern(res, zodPatterns.nanoid, check.message, refs);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
return res;
|
|
701
|
+
}
|
|
702
|
+
function escapeLiteralCheckValue(literal, refs) {
|
|
703
|
+
return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
|
|
704
|
+
}
|
|
705
|
+
var ALPHA_NUMERIC = new Set(
|
|
706
|
+
"ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
|
|
707
|
+
);
|
|
708
|
+
function escapeNonAlphaNumeric(source) {
|
|
709
|
+
let result = "";
|
|
710
|
+
for (let i = 0; i < source.length; i++) {
|
|
711
|
+
if (!ALPHA_NUMERIC.has(source[i])) {
|
|
712
|
+
result += "\\";
|
|
713
|
+
}
|
|
714
|
+
result += source[i];
|
|
715
|
+
}
|
|
716
|
+
return result;
|
|
717
|
+
}
|
|
718
|
+
function addFormat(schema, value, message, refs) {
|
|
719
|
+
var _a17;
|
|
720
|
+
if (schema.format || ((_a17 = schema.anyOf) == null ? void 0 : _a17.some((x) => x.format))) {
|
|
721
|
+
if (!schema.anyOf) {
|
|
722
|
+
schema.anyOf = [];
|
|
723
|
+
}
|
|
724
|
+
if (schema.format) {
|
|
725
|
+
schema.anyOf.push({
|
|
726
|
+
format: schema.format
|
|
727
|
+
});
|
|
728
|
+
delete schema.format;
|
|
729
|
+
}
|
|
730
|
+
schema.anyOf.push({
|
|
731
|
+
format: value,
|
|
732
|
+
...message && refs.errorMessages && { errorMessage: { format: message } }
|
|
733
|
+
});
|
|
734
|
+
} else {
|
|
735
|
+
schema.format = value;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
function addPattern(schema, regex, message, refs) {
|
|
739
|
+
var _a17;
|
|
740
|
+
if (schema.pattern || ((_a17 = schema.allOf) == null ? void 0 : _a17.some((x) => x.pattern))) {
|
|
741
|
+
if (!schema.allOf) {
|
|
742
|
+
schema.allOf = [];
|
|
743
|
+
}
|
|
744
|
+
if (schema.pattern) {
|
|
745
|
+
schema.allOf.push({
|
|
746
|
+
pattern: schema.pattern
|
|
747
|
+
});
|
|
748
|
+
delete schema.pattern;
|
|
749
|
+
}
|
|
750
|
+
schema.allOf.push({
|
|
751
|
+
pattern: stringifyRegExpWithFlags(regex, refs),
|
|
752
|
+
...message && refs.errorMessages && { errorMessage: { pattern: message } }
|
|
753
|
+
});
|
|
754
|
+
} else {
|
|
755
|
+
schema.pattern = stringifyRegExpWithFlags(regex, refs);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
function stringifyRegExpWithFlags(regex, refs) {
|
|
759
|
+
var _a17;
|
|
760
|
+
if (!refs.applyRegexFlags || !regex.flags) {
|
|
761
|
+
return regex.source;
|
|
762
|
+
}
|
|
763
|
+
const flags = {
|
|
764
|
+
i: regex.flags.includes("i"),
|
|
765
|
+
// Case-insensitive
|
|
766
|
+
m: regex.flags.includes("m"),
|
|
767
|
+
// `^` and `$` matches adjacent to newline characters
|
|
768
|
+
s: regex.flags.includes("s")
|
|
769
|
+
// `.` matches newlines
|
|
770
|
+
};
|
|
771
|
+
const source = flags.i ? regex.source.toLowerCase() : regex.source;
|
|
772
|
+
let pattern = "";
|
|
773
|
+
let isEscaped = false;
|
|
774
|
+
let inCharGroup = false;
|
|
775
|
+
let inCharRange = false;
|
|
776
|
+
for (let i = 0; i < source.length; i++) {
|
|
777
|
+
if (isEscaped) {
|
|
778
|
+
pattern += source[i];
|
|
779
|
+
isEscaped = false;
|
|
780
|
+
continue;
|
|
781
|
+
}
|
|
782
|
+
if (flags.i) {
|
|
783
|
+
if (inCharGroup) {
|
|
784
|
+
if (source[i].match(/[a-z]/)) {
|
|
785
|
+
if (inCharRange) {
|
|
786
|
+
pattern += source[i];
|
|
787
|
+
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
|
|
788
|
+
inCharRange = false;
|
|
789
|
+
} else if (source[i + 1] === "-" && ((_a17 = source[i + 2]) == null ? void 0 : _a17.match(/[a-z]/))) {
|
|
790
|
+
pattern += source[i];
|
|
791
|
+
inCharRange = true;
|
|
792
|
+
} else {
|
|
793
|
+
pattern += `${source[i]}${source[i].toUpperCase()}`;
|
|
794
|
+
}
|
|
795
|
+
continue;
|
|
796
|
+
}
|
|
797
|
+
} else if (source[i].match(/[a-z]/)) {
|
|
798
|
+
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
|
|
799
|
+
continue;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
if (flags.m) {
|
|
803
|
+
if (source[i] === "^") {
|
|
804
|
+
pattern += `(^|(?<=[\r
|
|
805
|
+
]))`;
|
|
806
|
+
continue;
|
|
807
|
+
} else if (source[i] === "$") {
|
|
808
|
+
pattern += `($|(?=[\r
|
|
809
|
+
]))`;
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
if (flags.s && source[i] === ".") {
|
|
814
|
+
pattern += inCharGroup ? `${source[i]}\r
|
|
815
|
+
` : `[${source[i]}\r
|
|
816
|
+
]`;
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
pattern += source[i];
|
|
820
|
+
if (source[i] === "\\") {
|
|
821
|
+
isEscaped = true;
|
|
822
|
+
} else if (inCharGroup && source[i] === "]") {
|
|
823
|
+
inCharGroup = false;
|
|
824
|
+
} else if (!inCharGroup && source[i] === "[") {
|
|
825
|
+
inCharGroup = true;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
return pattern;
|
|
829
|
+
}
|
|
830
|
+
function parseRecordDef(def, refs) {
|
|
831
|
+
var _a17, _b, _c, _d, _e, _f;
|
|
832
|
+
const schema = {
|
|
833
|
+
type: "object",
|
|
834
|
+
additionalProperties: (_a17 = parseDef(def.valueType._def, {
|
|
835
|
+
...refs,
|
|
836
|
+
currentPath: [...refs.currentPath, "additionalProperties"]
|
|
837
|
+
})) != null ? _a17 : refs.allowedAdditionalProperties
|
|
838
|
+
};
|
|
839
|
+
if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === v3.ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
|
|
840
|
+
const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
|
|
841
|
+
return {
|
|
842
|
+
...schema,
|
|
843
|
+
propertyNames: keyType
|
|
844
|
+
};
|
|
845
|
+
} else if (((_d = def.keyType) == null ? void 0 : _d._def.typeName) === v3.ZodFirstPartyTypeKind.ZodEnum) {
|
|
846
|
+
return {
|
|
847
|
+
...schema,
|
|
848
|
+
propertyNames: {
|
|
849
|
+
enum: def.keyType._def.values
|
|
850
|
+
}
|
|
851
|
+
};
|
|
852
|
+
} 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)) {
|
|
853
|
+
const { type, ...keyType } = parseBrandedDef(
|
|
854
|
+
def.keyType._def,
|
|
855
|
+
refs
|
|
856
|
+
);
|
|
857
|
+
return {
|
|
858
|
+
...schema,
|
|
859
|
+
propertyNames: keyType
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
return schema;
|
|
863
|
+
}
|
|
864
|
+
function parseMapDef(def, refs) {
|
|
865
|
+
if (refs.mapStrategy === "record") {
|
|
866
|
+
return parseRecordDef(def, refs);
|
|
867
|
+
}
|
|
868
|
+
const keys = parseDef(def.keyType._def, {
|
|
869
|
+
...refs,
|
|
870
|
+
currentPath: [...refs.currentPath, "items", "items", "0"]
|
|
871
|
+
}) || parseAnyDef();
|
|
872
|
+
const values = parseDef(def.valueType._def, {
|
|
873
|
+
...refs,
|
|
874
|
+
currentPath: [...refs.currentPath, "items", "items", "1"]
|
|
875
|
+
}) || parseAnyDef();
|
|
876
|
+
return {
|
|
877
|
+
type: "array",
|
|
878
|
+
maxItems: 125,
|
|
879
|
+
items: {
|
|
880
|
+
type: "array",
|
|
881
|
+
items: [keys, values],
|
|
882
|
+
minItems: 2,
|
|
883
|
+
maxItems: 2
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
function parseNativeEnumDef(def) {
|
|
888
|
+
const object2 = def.values;
|
|
889
|
+
const actualKeys = Object.keys(def.values).filter((key) => {
|
|
890
|
+
return typeof object2[object2[key]] !== "number";
|
|
891
|
+
});
|
|
892
|
+
const actualValues = actualKeys.map((key) => object2[key]);
|
|
893
|
+
const parsedTypes = Array.from(
|
|
894
|
+
new Set(actualValues.map((values) => typeof values))
|
|
895
|
+
);
|
|
896
|
+
return {
|
|
897
|
+
type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
|
|
898
|
+
enum: actualValues
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
function parseNeverDef() {
|
|
902
|
+
return { not: parseAnyDef() };
|
|
903
|
+
}
|
|
904
|
+
function parseNullDef() {
|
|
905
|
+
return {
|
|
906
|
+
type: "null"
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
var primitiveMappings = {
|
|
910
|
+
ZodString: "string",
|
|
911
|
+
ZodNumber: "number",
|
|
912
|
+
ZodBigInt: "integer",
|
|
913
|
+
ZodBoolean: "boolean",
|
|
914
|
+
ZodNull: "null"
|
|
915
|
+
};
|
|
916
|
+
function parseUnionDef(def, refs) {
|
|
917
|
+
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
|
|
918
|
+
if (options.every(
|
|
919
|
+
(x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length)
|
|
920
|
+
)) {
|
|
921
|
+
const types = options.reduce((types2, x) => {
|
|
922
|
+
const type = primitiveMappings[x._def.typeName];
|
|
923
|
+
return type && !types2.includes(type) ? [...types2, type] : types2;
|
|
924
|
+
}, []);
|
|
925
|
+
return {
|
|
926
|
+
type: types.length > 1 ? types : types[0]
|
|
927
|
+
};
|
|
928
|
+
} else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
|
|
929
|
+
const types = options.reduce(
|
|
930
|
+
(acc, x) => {
|
|
931
|
+
const type = typeof x._def.value;
|
|
932
|
+
switch (type) {
|
|
933
|
+
case "string":
|
|
934
|
+
case "number":
|
|
935
|
+
case "boolean":
|
|
936
|
+
return [...acc, type];
|
|
937
|
+
case "bigint":
|
|
938
|
+
return [...acc, "integer"];
|
|
939
|
+
case "object":
|
|
940
|
+
if (x._def.value === null) return [...acc, "null"];
|
|
941
|
+
case "symbol":
|
|
942
|
+
case "undefined":
|
|
943
|
+
case "function":
|
|
944
|
+
default:
|
|
945
|
+
return acc;
|
|
946
|
+
}
|
|
947
|
+
},
|
|
948
|
+
[]
|
|
949
|
+
);
|
|
950
|
+
if (types.length === options.length) {
|
|
951
|
+
const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
|
|
952
|
+
return {
|
|
953
|
+
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
|
|
954
|
+
enum: options.reduce(
|
|
955
|
+
(acc, x) => {
|
|
956
|
+
return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
|
|
957
|
+
},
|
|
958
|
+
[]
|
|
959
|
+
)
|
|
960
|
+
};
|
|
961
|
+
}
|
|
962
|
+
} else if (options.every((x) => x._def.typeName === "ZodEnum")) {
|
|
963
|
+
return {
|
|
964
|
+
type: "string",
|
|
965
|
+
enum: options.reduce(
|
|
966
|
+
(acc, x) => [
|
|
967
|
+
...acc,
|
|
968
|
+
...x._def.values.filter((x2) => !acc.includes(x2))
|
|
969
|
+
],
|
|
970
|
+
[]
|
|
971
|
+
)
|
|
972
|
+
};
|
|
973
|
+
}
|
|
974
|
+
return asAnyOf(def, refs);
|
|
975
|
+
}
|
|
976
|
+
var asAnyOf = (def, refs) => {
|
|
977
|
+
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map(
|
|
978
|
+
(x, i) => parseDef(x._def, {
|
|
979
|
+
...refs,
|
|
980
|
+
currentPath: [...refs.currentPath, "anyOf", `${i}`]
|
|
981
|
+
})
|
|
982
|
+
).filter(
|
|
983
|
+
(x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)
|
|
984
|
+
);
|
|
985
|
+
return anyOf.length ? { anyOf } : void 0;
|
|
986
|
+
};
|
|
987
|
+
function parseNullableDef(def, refs) {
|
|
988
|
+
if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
|
|
989
|
+
def.innerType._def.typeName
|
|
990
|
+
) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
|
|
991
|
+
return {
|
|
992
|
+
type: [
|
|
993
|
+
primitiveMappings[def.innerType._def.typeName],
|
|
994
|
+
"null"
|
|
995
|
+
]
|
|
996
|
+
};
|
|
997
|
+
}
|
|
998
|
+
const base = parseDef(def.innerType._def, {
|
|
999
|
+
...refs,
|
|
1000
|
+
currentPath: [...refs.currentPath, "anyOf", "0"]
|
|
1001
|
+
});
|
|
1002
|
+
return base && { anyOf: [base, { type: "null" }] };
|
|
1003
|
+
}
|
|
1004
|
+
function parseNumberDef(def) {
|
|
1005
|
+
const res = {
|
|
1006
|
+
type: "number"
|
|
1007
|
+
};
|
|
1008
|
+
if (!def.checks) return res;
|
|
1009
|
+
for (const check of def.checks) {
|
|
1010
|
+
switch (check.kind) {
|
|
1011
|
+
case "int":
|
|
1012
|
+
res.type = "integer";
|
|
1013
|
+
break;
|
|
1014
|
+
case "min":
|
|
1015
|
+
if (check.inclusive) {
|
|
1016
|
+
res.minimum = check.value;
|
|
1017
|
+
} else {
|
|
1018
|
+
res.exclusiveMinimum = check.value;
|
|
1019
|
+
}
|
|
1020
|
+
break;
|
|
1021
|
+
case "max":
|
|
1022
|
+
if (check.inclusive) {
|
|
1023
|
+
res.maximum = check.value;
|
|
1024
|
+
} else {
|
|
1025
|
+
res.exclusiveMaximum = check.value;
|
|
1026
|
+
}
|
|
1027
|
+
break;
|
|
1028
|
+
case "multipleOf":
|
|
1029
|
+
res.multipleOf = check.value;
|
|
1030
|
+
break;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
return res;
|
|
1034
|
+
}
|
|
1035
|
+
function parseObjectDef(def, refs) {
|
|
1036
|
+
const result = {
|
|
1037
|
+
type: "object",
|
|
1038
|
+
properties: {}
|
|
1039
|
+
};
|
|
1040
|
+
const required = [];
|
|
1041
|
+
const shape = def.shape();
|
|
1042
|
+
for (const propName in shape) {
|
|
1043
|
+
let propDef = shape[propName];
|
|
1044
|
+
if (propDef === void 0 || propDef._def === void 0) {
|
|
1045
|
+
continue;
|
|
1046
|
+
}
|
|
1047
|
+
const propOptional = safeIsOptional(propDef);
|
|
1048
|
+
const parsedDef = parseDef(propDef._def, {
|
|
1049
|
+
...refs,
|
|
1050
|
+
currentPath: [...refs.currentPath, "properties", propName],
|
|
1051
|
+
propertyPath: [...refs.currentPath, "properties", propName]
|
|
1052
|
+
});
|
|
1053
|
+
if (parsedDef === void 0) {
|
|
1054
|
+
continue;
|
|
1055
|
+
}
|
|
1056
|
+
result.properties[propName] = parsedDef;
|
|
1057
|
+
if (!propOptional) {
|
|
1058
|
+
required.push(propName);
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
if (required.length) {
|
|
1062
|
+
result.required = required;
|
|
1063
|
+
}
|
|
1064
|
+
const additionalProperties = decideAdditionalProperties(def, refs);
|
|
1065
|
+
if (additionalProperties !== void 0) {
|
|
1066
|
+
result.additionalProperties = additionalProperties;
|
|
1067
|
+
}
|
|
1068
|
+
return result;
|
|
1069
|
+
}
|
|
1070
|
+
function decideAdditionalProperties(def, refs) {
|
|
1071
|
+
if (def.catchall._def.typeName !== "ZodNever") {
|
|
1072
|
+
return parseDef(def.catchall._def, {
|
|
1073
|
+
...refs,
|
|
1074
|
+
currentPath: [...refs.currentPath, "additionalProperties"]
|
|
1075
|
+
});
|
|
1076
|
+
}
|
|
1077
|
+
switch (def.unknownKeys) {
|
|
1078
|
+
case "passthrough":
|
|
1079
|
+
return refs.allowedAdditionalProperties;
|
|
1080
|
+
case "strict":
|
|
1081
|
+
return refs.rejectedAdditionalProperties;
|
|
1082
|
+
case "strip":
|
|
1083
|
+
return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
function safeIsOptional(schema) {
|
|
1087
|
+
try {
|
|
1088
|
+
return schema.isOptional();
|
|
1089
|
+
} catch (e) {
|
|
1090
|
+
return true;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
var parseOptionalDef = (def, refs) => {
|
|
1094
|
+
var _a17;
|
|
1095
|
+
if (refs.currentPath.toString() === ((_a17 = refs.propertyPath) == null ? void 0 : _a17.toString())) {
|
|
1096
|
+
return parseDef(def.innerType._def, refs);
|
|
1097
|
+
}
|
|
1098
|
+
const innerSchema = parseDef(def.innerType._def, {
|
|
1099
|
+
...refs,
|
|
1100
|
+
currentPath: [...refs.currentPath, "anyOf", "1"]
|
|
1101
|
+
});
|
|
1102
|
+
return innerSchema ? { anyOf: [{ not: parseAnyDef() }, innerSchema] } : parseAnyDef();
|
|
1103
|
+
};
|
|
1104
|
+
var parsePipelineDef = (def, refs) => {
|
|
1105
|
+
if (refs.pipeStrategy === "input") {
|
|
1106
|
+
return parseDef(def.in._def, refs);
|
|
1107
|
+
} else if (refs.pipeStrategy === "output") {
|
|
1108
|
+
return parseDef(def.out._def, refs);
|
|
1109
|
+
}
|
|
1110
|
+
const a = parseDef(def.in._def, {
|
|
1111
|
+
...refs,
|
|
1112
|
+
currentPath: [...refs.currentPath, "allOf", "0"]
|
|
1113
|
+
});
|
|
1114
|
+
const b = parseDef(def.out._def, {
|
|
1115
|
+
...refs,
|
|
1116
|
+
currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
|
|
1117
|
+
});
|
|
1118
|
+
return {
|
|
1119
|
+
allOf: [a, b].filter((x) => x !== void 0)
|
|
1120
|
+
};
|
|
1121
|
+
};
|
|
1122
|
+
function parsePromiseDef(def, refs) {
|
|
1123
|
+
return parseDef(def.type._def, refs);
|
|
1124
|
+
}
|
|
1125
|
+
function parseSetDef(def, refs) {
|
|
1126
|
+
const items = parseDef(def.valueType._def, {
|
|
1127
|
+
...refs,
|
|
1128
|
+
currentPath: [...refs.currentPath, "items"]
|
|
1129
|
+
});
|
|
1130
|
+
const schema = {
|
|
1131
|
+
type: "array",
|
|
1132
|
+
uniqueItems: true,
|
|
1133
|
+
items
|
|
1134
|
+
};
|
|
1135
|
+
if (def.minSize) {
|
|
1136
|
+
schema.minItems = def.minSize.value;
|
|
1137
|
+
}
|
|
1138
|
+
if (def.maxSize) {
|
|
1139
|
+
schema.maxItems = def.maxSize.value;
|
|
1140
|
+
}
|
|
1141
|
+
return schema;
|
|
1142
|
+
}
|
|
1143
|
+
function parseTupleDef(def, refs) {
|
|
1144
|
+
if (def.rest) {
|
|
1145
|
+
return {
|
|
1146
|
+
type: "array",
|
|
1147
|
+
minItems: def.items.length,
|
|
1148
|
+
items: def.items.map(
|
|
1149
|
+
(x, i) => parseDef(x._def, {
|
|
1150
|
+
...refs,
|
|
1151
|
+
currentPath: [...refs.currentPath, "items", `${i}`]
|
|
1152
|
+
})
|
|
1153
|
+
).reduce(
|
|
1154
|
+
(acc, x) => x === void 0 ? acc : [...acc, x],
|
|
1155
|
+
[]
|
|
1156
|
+
),
|
|
1157
|
+
additionalItems: parseDef(def.rest._def, {
|
|
1158
|
+
...refs,
|
|
1159
|
+
currentPath: [...refs.currentPath, "additionalItems"]
|
|
1160
|
+
})
|
|
1161
|
+
};
|
|
1162
|
+
} else {
|
|
1163
|
+
return {
|
|
1164
|
+
type: "array",
|
|
1165
|
+
minItems: def.items.length,
|
|
1166
|
+
maxItems: def.items.length,
|
|
1167
|
+
items: def.items.map(
|
|
1168
|
+
(x, i) => parseDef(x._def, {
|
|
1169
|
+
...refs,
|
|
1170
|
+
currentPath: [...refs.currentPath, "items", `${i}`]
|
|
1171
|
+
})
|
|
1172
|
+
).reduce(
|
|
1173
|
+
(acc, x) => x === void 0 ? acc : [...acc, x],
|
|
1174
|
+
[]
|
|
1175
|
+
)
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
function parseUndefinedDef() {
|
|
1180
|
+
return {
|
|
1181
|
+
not: parseAnyDef()
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
function parseUnknownDef() {
|
|
1185
|
+
return parseAnyDef();
|
|
1186
|
+
}
|
|
1187
|
+
var parseReadonlyDef = (def, refs) => {
|
|
1188
|
+
return parseDef(def.innerType._def, refs);
|
|
1189
|
+
};
|
|
1190
|
+
var selectParser = (def, typeName, refs) => {
|
|
1191
|
+
switch (typeName) {
|
|
1192
|
+
case v3.ZodFirstPartyTypeKind.ZodString:
|
|
1193
|
+
return parseStringDef(def, refs);
|
|
1194
|
+
case v3.ZodFirstPartyTypeKind.ZodNumber:
|
|
1195
|
+
return parseNumberDef(def);
|
|
1196
|
+
case v3.ZodFirstPartyTypeKind.ZodObject:
|
|
1197
|
+
return parseObjectDef(def, refs);
|
|
1198
|
+
case v3.ZodFirstPartyTypeKind.ZodBigInt:
|
|
1199
|
+
return parseBigintDef(def);
|
|
1200
|
+
case v3.ZodFirstPartyTypeKind.ZodBoolean:
|
|
1201
|
+
return parseBooleanDef();
|
|
1202
|
+
case v3.ZodFirstPartyTypeKind.ZodDate:
|
|
1203
|
+
return parseDateDef(def, refs);
|
|
1204
|
+
case v3.ZodFirstPartyTypeKind.ZodUndefined:
|
|
1205
|
+
return parseUndefinedDef();
|
|
1206
|
+
case v3.ZodFirstPartyTypeKind.ZodNull:
|
|
1207
|
+
return parseNullDef();
|
|
1208
|
+
case v3.ZodFirstPartyTypeKind.ZodArray:
|
|
1209
|
+
return parseArrayDef(def, refs);
|
|
1210
|
+
case v3.ZodFirstPartyTypeKind.ZodUnion:
|
|
1211
|
+
case v3.ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
|
|
1212
|
+
return parseUnionDef(def, refs);
|
|
1213
|
+
case v3.ZodFirstPartyTypeKind.ZodIntersection:
|
|
1214
|
+
return parseIntersectionDef(def, refs);
|
|
1215
|
+
case v3.ZodFirstPartyTypeKind.ZodTuple:
|
|
1216
|
+
return parseTupleDef(def, refs);
|
|
1217
|
+
case v3.ZodFirstPartyTypeKind.ZodRecord:
|
|
1218
|
+
return parseRecordDef(def, refs);
|
|
1219
|
+
case v3.ZodFirstPartyTypeKind.ZodLiteral:
|
|
1220
|
+
return parseLiteralDef(def);
|
|
1221
|
+
case v3.ZodFirstPartyTypeKind.ZodEnum:
|
|
1222
|
+
return parseEnumDef(def);
|
|
1223
|
+
case v3.ZodFirstPartyTypeKind.ZodNativeEnum:
|
|
1224
|
+
return parseNativeEnumDef(def);
|
|
1225
|
+
case v3.ZodFirstPartyTypeKind.ZodNullable:
|
|
1226
|
+
return parseNullableDef(def, refs);
|
|
1227
|
+
case v3.ZodFirstPartyTypeKind.ZodOptional:
|
|
1228
|
+
return parseOptionalDef(def, refs);
|
|
1229
|
+
case v3.ZodFirstPartyTypeKind.ZodMap:
|
|
1230
|
+
return parseMapDef(def, refs);
|
|
1231
|
+
case v3.ZodFirstPartyTypeKind.ZodSet:
|
|
1232
|
+
return parseSetDef(def, refs);
|
|
1233
|
+
case v3.ZodFirstPartyTypeKind.ZodLazy:
|
|
1234
|
+
return () => def.getter()._def;
|
|
1235
|
+
case v3.ZodFirstPartyTypeKind.ZodPromise:
|
|
1236
|
+
return parsePromiseDef(def, refs);
|
|
1237
|
+
case v3.ZodFirstPartyTypeKind.ZodNaN:
|
|
1238
|
+
case v3.ZodFirstPartyTypeKind.ZodNever:
|
|
1239
|
+
return parseNeverDef();
|
|
1240
|
+
case v3.ZodFirstPartyTypeKind.ZodEffects:
|
|
1241
|
+
return parseEffectsDef(def, refs);
|
|
1242
|
+
case v3.ZodFirstPartyTypeKind.ZodAny:
|
|
1243
|
+
return parseAnyDef();
|
|
1244
|
+
case v3.ZodFirstPartyTypeKind.ZodUnknown:
|
|
1245
|
+
return parseUnknownDef();
|
|
1246
|
+
case v3.ZodFirstPartyTypeKind.ZodDefault:
|
|
1247
|
+
return parseDefaultDef(def, refs);
|
|
1248
|
+
case v3.ZodFirstPartyTypeKind.ZodBranded:
|
|
1249
|
+
return parseBrandedDef(def, refs);
|
|
1250
|
+
case v3.ZodFirstPartyTypeKind.ZodReadonly:
|
|
1251
|
+
return parseReadonlyDef(def, refs);
|
|
1252
|
+
case v3.ZodFirstPartyTypeKind.ZodCatch:
|
|
1253
|
+
return parseCatchDef(def, refs);
|
|
1254
|
+
case v3.ZodFirstPartyTypeKind.ZodPipeline:
|
|
1255
|
+
return parsePipelineDef(def, refs);
|
|
1256
|
+
case v3.ZodFirstPartyTypeKind.ZodFunction:
|
|
1257
|
+
case v3.ZodFirstPartyTypeKind.ZodVoid:
|
|
1258
|
+
case v3.ZodFirstPartyTypeKind.ZodSymbol:
|
|
1259
|
+
return void 0;
|
|
1260
|
+
default:
|
|
1261
|
+
return /* @__PURE__ */ ((_) => void 0)();
|
|
1262
|
+
}
|
|
1263
|
+
};
|
|
1264
|
+
function parseDef(def, refs, forceResolution = false) {
|
|
1265
|
+
var _a17;
|
|
1266
|
+
const seenItem = refs.seen.get(def);
|
|
1267
|
+
if (refs.override) {
|
|
1268
|
+
const overrideResult = (_a17 = refs.override) == null ? void 0 : _a17.call(
|
|
1269
|
+
refs,
|
|
1270
|
+
def,
|
|
1271
|
+
refs,
|
|
1272
|
+
seenItem,
|
|
1273
|
+
forceResolution
|
|
1274
|
+
);
|
|
1275
|
+
if (overrideResult !== ignoreOverride) {
|
|
1276
|
+
return overrideResult;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
if (seenItem && !forceResolution) {
|
|
1280
|
+
const seenSchema = get$ref(seenItem, refs);
|
|
1281
|
+
if (seenSchema !== void 0) {
|
|
1282
|
+
return seenSchema;
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
|
|
1286
|
+
refs.seen.set(def, newItem);
|
|
1287
|
+
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
|
|
1288
|
+
const jsonSchema2 = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
|
|
1289
|
+
if (jsonSchema2) {
|
|
1290
|
+
addMeta(def, refs, jsonSchema2);
|
|
1291
|
+
}
|
|
1292
|
+
if (refs.postProcess) {
|
|
1293
|
+
const postProcessResult = refs.postProcess(jsonSchema2, def, refs);
|
|
1294
|
+
newItem.jsonSchema = jsonSchema2;
|
|
1295
|
+
return postProcessResult;
|
|
1296
|
+
}
|
|
1297
|
+
newItem.jsonSchema = jsonSchema2;
|
|
1298
|
+
return jsonSchema2;
|
|
1299
|
+
}
|
|
1300
|
+
var get$ref = (item, refs) => {
|
|
1301
|
+
switch (refs.$refStrategy) {
|
|
1302
|
+
case "root":
|
|
1303
|
+
return { $ref: item.path.join("/") };
|
|
1304
|
+
case "relative":
|
|
1305
|
+
return { $ref: getRelativePath(refs.currentPath, item.path) };
|
|
1306
|
+
case "none":
|
|
1307
|
+
case "seen": {
|
|
1308
|
+
if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
|
|
1309
|
+
console.warn(
|
|
1310
|
+
`Recursive reference detected at ${refs.currentPath.join(
|
|
1311
|
+
"/"
|
|
1312
|
+
)}! Defaulting to any`
|
|
1313
|
+
);
|
|
1314
|
+
return parseAnyDef();
|
|
1315
|
+
}
|
|
1316
|
+
return refs.$refStrategy === "seen" ? parseAnyDef() : void 0;
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
};
|
|
1320
|
+
var addMeta = (def, refs, jsonSchema2) => {
|
|
1321
|
+
if (def.description) {
|
|
1322
|
+
jsonSchema2.description = def.description;
|
|
1323
|
+
}
|
|
1324
|
+
return jsonSchema2;
|
|
1325
|
+
};
|
|
1326
|
+
var getRefs = (options) => {
|
|
1327
|
+
const _options = getDefaultOptions(options);
|
|
1328
|
+
const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
|
|
1329
|
+
return {
|
|
1330
|
+
..._options,
|
|
1331
|
+
currentPath,
|
|
1332
|
+
propertyPath: void 0,
|
|
1333
|
+
seen: new Map(
|
|
1334
|
+
Object.entries(_options.definitions).map(([name17, def]) => [
|
|
1335
|
+
def._def,
|
|
1336
|
+
{
|
|
1337
|
+
def: def._def,
|
|
1338
|
+
path: [..._options.basePath, _options.definitionPath, name17],
|
|
1339
|
+
// Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
|
|
1340
|
+
jsonSchema: void 0
|
|
1341
|
+
}
|
|
1342
|
+
])
|
|
1343
|
+
)
|
|
1344
|
+
};
|
|
1345
|
+
};
|
|
1346
|
+
var zodToJsonSchema = (schema, options) => {
|
|
1347
|
+
var _a17;
|
|
1348
|
+
const refs = getRefs(options);
|
|
1349
|
+
let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
|
|
1350
|
+
(acc, [name23, schema2]) => {
|
|
1351
|
+
var _a23;
|
|
1352
|
+
return {
|
|
1353
|
+
...acc,
|
|
1354
|
+
[name23]: (_a23 = parseDef(
|
|
1355
|
+
schema2._def,
|
|
1356
|
+
{
|
|
1357
|
+
...refs,
|
|
1358
|
+
currentPath: [...refs.basePath, refs.definitionPath, name23]
|
|
1359
|
+
},
|
|
1360
|
+
true
|
|
1361
|
+
)) != null ? _a23 : parseAnyDef()
|
|
1362
|
+
};
|
|
1363
|
+
},
|
|
1364
|
+
{}
|
|
1365
|
+
) : void 0;
|
|
1366
|
+
const name17 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
|
|
1367
|
+
const main = (_a17 = parseDef(
|
|
1368
|
+
schema._def,
|
|
1369
|
+
name17 === void 0 ? refs : {
|
|
1370
|
+
...refs,
|
|
1371
|
+
currentPath: [...refs.basePath, refs.definitionPath, name17]
|
|
1372
|
+
},
|
|
1373
|
+
false
|
|
1374
|
+
)) != null ? _a17 : parseAnyDef();
|
|
1375
|
+
const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
|
|
1376
|
+
if (title !== void 0) {
|
|
1377
|
+
main.title = title;
|
|
1378
|
+
}
|
|
1379
|
+
const combined = name17 === void 0 ? definitions ? {
|
|
1380
|
+
...main,
|
|
1381
|
+
[refs.definitionPath]: definitions
|
|
1382
|
+
} : main : {
|
|
1383
|
+
$ref: [
|
|
1384
|
+
...refs.$refStrategy === "relative" ? [] : refs.basePath,
|
|
1385
|
+
refs.definitionPath,
|
|
1386
|
+
name17
|
|
1387
|
+
].join("/"),
|
|
1388
|
+
[refs.definitionPath]: {
|
|
1389
|
+
...definitions,
|
|
1390
|
+
[name17]: main
|
|
1391
|
+
}
|
|
1392
|
+
};
|
|
1393
|
+
combined.$schema = "http://json-schema.org/draft-07/schema#";
|
|
1394
|
+
return combined;
|
|
1395
|
+
};
|
|
1396
|
+
var zod_to_json_schema_default = zodToJsonSchema;
|
|
1397
|
+
function zod3Schema(zodSchema2, options) {
|
|
1398
|
+
var _a17;
|
|
1399
|
+
const useReferences = (_a17 = void 0 ) != null ? _a17 : false;
|
|
1400
|
+
return jsonSchema(
|
|
1401
|
+
// defer json schema creation to avoid unnecessary computation when only validation is needed
|
|
1402
|
+
() => zod_to_json_schema_default(zodSchema2, {
|
|
1403
|
+
$refStrategy: useReferences ? "root" : "none"
|
|
1404
|
+
}),
|
|
1405
|
+
{
|
|
1406
|
+
validate: async (value) => {
|
|
1407
|
+
const result = await zodSchema2.safeParseAsync(value);
|
|
1408
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
);
|
|
1412
|
+
}
|
|
1413
|
+
function zod4Schema(zodSchema2, options) {
|
|
1414
|
+
var _a17;
|
|
1415
|
+
const useReferences = (_a17 = void 0 ) != null ? _a17 : false;
|
|
1416
|
+
return jsonSchema(
|
|
1417
|
+
// defer json schema creation to avoid unnecessary computation when only validation is needed
|
|
1418
|
+
() => z4__namespace.toJSONSchema(zodSchema2, {
|
|
1419
|
+
target: "draft-7",
|
|
1420
|
+
io: "output",
|
|
1421
|
+
reused: useReferences ? "ref" : "inline"
|
|
1422
|
+
}),
|
|
1423
|
+
{
|
|
1424
|
+
validate: async (value) => {
|
|
1425
|
+
const result = await z4__namespace.safeParseAsync(zodSchema2, value);
|
|
1426
|
+
return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
);
|
|
1430
|
+
}
|
|
1431
|
+
function isZod4Schema(zodSchema2) {
|
|
1432
|
+
return "_zod" in zodSchema2;
|
|
1433
|
+
}
|
|
1434
|
+
function zodSchema(zodSchema2, options) {
|
|
1435
|
+
if (isZod4Schema(zodSchema2)) {
|
|
1436
|
+
return zod4Schema(zodSchema2);
|
|
1437
|
+
} else {
|
|
1438
|
+
return zod3Schema(zodSchema2);
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
var schemaSymbol = Symbol.for("vercel.ai.schema");
|
|
1442
|
+
function jsonSchema(jsonSchema2, {
|
|
1443
|
+
validate
|
|
1444
|
+
} = {}) {
|
|
1445
|
+
return {
|
|
1446
|
+
[schemaSymbol]: true,
|
|
1447
|
+
_type: void 0,
|
|
1448
|
+
// should never be used directly
|
|
1449
|
+
[validatorSymbol]: true,
|
|
1450
|
+
get jsonSchema() {
|
|
1451
|
+
if (typeof jsonSchema2 === "function") {
|
|
1452
|
+
jsonSchema2 = jsonSchema2();
|
|
1453
|
+
}
|
|
1454
|
+
return jsonSchema2;
|
|
1455
|
+
},
|
|
1456
|
+
validate
|
|
1457
|
+
};
|
|
1458
|
+
}
|
|
1459
|
+
function isSchema(value) {
|
|
1460
|
+
return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true && "jsonSchema" in value && "validate" in value;
|
|
1461
|
+
}
|
|
1462
|
+
function asSchema(schema) {
|
|
1463
|
+
return schema == null ? jsonSchema({
|
|
1464
|
+
properties: {},
|
|
1465
|
+
additionalProperties: false
|
|
1466
|
+
}) : isSchema(schema) ? schema : typeof schema === "function" ? schema() : zodSchema(schema);
|
|
1467
|
+
}
|
|
1468
|
+
var __defProp = Object.defineProperty;
|
|
1469
|
+
var __export = (target, all) => {
|
|
1470
|
+
for (var name17 in all)
|
|
1471
|
+
__defProp(target, name17, { get: all[name17], enumerable: true });
|
|
1472
|
+
};
|
|
1473
|
+
var name72 = "AI_NoObjectGeneratedError";
|
|
1474
|
+
var marker72 = `vercel.ai.error.${name72}`;
|
|
1475
|
+
var symbol72 = Symbol.for(marker72);
|
|
1476
|
+
var _a72;
|
|
1477
|
+
var NoObjectGeneratedError = class extends AISDKError {
|
|
1478
|
+
constructor({
|
|
1479
|
+
message = "No object generated.",
|
|
1480
|
+
cause,
|
|
1481
|
+
text: text2,
|
|
1482
|
+
response,
|
|
1483
|
+
usage,
|
|
1484
|
+
finishReason
|
|
1485
|
+
}) {
|
|
1486
|
+
super({ name: name72, message, cause });
|
|
1487
|
+
this[_a72] = true;
|
|
1488
|
+
this.text = text2;
|
|
1489
|
+
this.response = response;
|
|
1490
|
+
this.usage = usage;
|
|
1491
|
+
this.finishReason = finishReason;
|
|
1492
|
+
}
|
|
1493
|
+
static isInstance(error) {
|
|
1494
|
+
return AISDKError.hasMarker(error, marker72);
|
|
1495
|
+
}
|
|
1496
|
+
};
|
|
1497
|
+
_a72 = symbol72;
|
|
1498
|
+
var dataContentSchema = z4.z.union([
|
|
1499
|
+
z4.z.string(),
|
|
1500
|
+
z4.z.instanceof(Uint8Array),
|
|
1501
|
+
z4.z.instanceof(ArrayBuffer),
|
|
1502
|
+
z4.z.custom(
|
|
1503
|
+
// Buffer might not be available in some environments such as CloudFlare:
|
|
1504
|
+
(value) => {
|
|
1505
|
+
var _a17, _b;
|
|
1506
|
+
return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
|
|
1507
|
+
},
|
|
1508
|
+
{ message: "Must be a Buffer" }
|
|
1509
|
+
)
|
|
1510
|
+
]);
|
|
1511
|
+
var jsonValueSchema = z4.z.lazy(
|
|
1512
|
+
() => z4.z.union([
|
|
1513
|
+
z4.z.null(),
|
|
1514
|
+
z4.z.string(),
|
|
1515
|
+
z4.z.number(),
|
|
1516
|
+
z4.z.boolean(),
|
|
1517
|
+
z4.z.record(z4.z.string(), jsonValueSchema),
|
|
1518
|
+
z4.z.array(jsonValueSchema)
|
|
1519
|
+
])
|
|
1520
|
+
);
|
|
1521
|
+
var providerMetadataSchema = z4.z.record(
|
|
1522
|
+
z4.z.string(),
|
|
1523
|
+
z4.z.record(z4.z.string(), jsonValueSchema)
|
|
1524
|
+
);
|
|
1525
|
+
var textPartSchema = z4.z.object({
|
|
1526
|
+
type: z4.z.literal("text"),
|
|
1527
|
+
text: z4.z.string(),
|
|
1528
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1529
|
+
});
|
|
1530
|
+
var imagePartSchema = z4.z.object({
|
|
1531
|
+
type: z4.z.literal("image"),
|
|
1532
|
+
image: z4.z.union([dataContentSchema, z4.z.instanceof(URL)]),
|
|
1533
|
+
mediaType: z4.z.string().optional(),
|
|
1534
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1535
|
+
});
|
|
1536
|
+
var filePartSchema = z4.z.object({
|
|
1537
|
+
type: z4.z.literal("file"),
|
|
1538
|
+
data: z4.z.union([dataContentSchema, z4.z.instanceof(URL)]),
|
|
1539
|
+
filename: z4.z.string().optional(),
|
|
1540
|
+
mediaType: z4.z.string(),
|
|
1541
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1542
|
+
});
|
|
1543
|
+
var reasoningPartSchema = z4.z.object({
|
|
1544
|
+
type: z4.z.literal("reasoning"),
|
|
1545
|
+
text: z4.z.string(),
|
|
1546
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1547
|
+
});
|
|
1548
|
+
var toolCallPartSchema = z4.z.object({
|
|
1549
|
+
type: z4.z.literal("tool-call"),
|
|
1550
|
+
toolCallId: z4.z.string(),
|
|
1551
|
+
toolName: z4.z.string(),
|
|
1552
|
+
input: z4.z.unknown(),
|
|
1553
|
+
providerOptions: providerMetadataSchema.optional(),
|
|
1554
|
+
providerExecuted: z4.z.boolean().optional()
|
|
1555
|
+
});
|
|
1556
|
+
var outputSchema = z4.z.discriminatedUnion("type", [
|
|
1557
|
+
z4.z.object({
|
|
1558
|
+
type: z4.z.literal("text"),
|
|
1559
|
+
value: z4.z.string()
|
|
1560
|
+
}),
|
|
1561
|
+
z4.z.object({
|
|
1562
|
+
type: z4.z.literal("json"),
|
|
1563
|
+
value: jsonValueSchema
|
|
1564
|
+
}),
|
|
1565
|
+
z4.z.object({
|
|
1566
|
+
type: z4.z.literal("error-text"),
|
|
1567
|
+
value: z4.z.string()
|
|
1568
|
+
}),
|
|
1569
|
+
z4.z.object({
|
|
1570
|
+
type: z4.z.literal("error-json"),
|
|
1571
|
+
value: jsonValueSchema
|
|
1572
|
+
}),
|
|
1573
|
+
z4.z.object({
|
|
1574
|
+
type: z4.z.literal("content"),
|
|
1575
|
+
value: z4.z.array(
|
|
1576
|
+
z4.z.union([
|
|
1577
|
+
z4.z.object({
|
|
1578
|
+
type: z4.z.literal("text"),
|
|
1579
|
+
text: z4.z.string()
|
|
1580
|
+
}),
|
|
1581
|
+
z4.z.object({
|
|
1582
|
+
type: z4.z.literal("media"),
|
|
1583
|
+
data: z4.z.string(),
|
|
1584
|
+
mediaType: z4.z.string()
|
|
1585
|
+
})
|
|
1586
|
+
])
|
|
1587
|
+
)
|
|
1588
|
+
})
|
|
1589
|
+
]);
|
|
1590
|
+
var toolResultPartSchema = z4.z.object({
|
|
1591
|
+
type: z4.z.literal("tool-result"),
|
|
1592
|
+
toolCallId: z4.z.string(),
|
|
1593
|
+
toolName: z4.z.string(),
|
|
1594
|
+
output: outputSchema,
|
|
1595
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1596
|
+
});
|
|
1597
|
+
var systemModelMessageSchema = z4.z.object(
|
|
1598
|
+
{
|
|
1599
|
+
role: z4.z.literal("system"),
|
|
1600
|
+
content: z4.z.string(),
|
|
1601
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1602
|
+
}
|
|
1603
|
+
);
|
|
1604
|
+
var userModelMessageSchema = z4.z.object({
|
|
1605
|
+
role: z4.z.literal("user"),
|
|
1606
|
+
content: z4.z.union([
|
|
1607
|
+
z4.z.string(),
|
|
1608
|
+
z4.z.array(z4.z.union([textPartSchema, imagePartSchema, filePartSchema]))
|
|
1609
|
+
]),
|
|
1610
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1611
|
+
});
|
|
1612
|
+
var assistantModelMessageSchema = z4.z.object({
|
|
1613
|
+
role: z4.z.literal("assistant"),
|
|
1614
|
+
content: z4.z.union([
|
|
1615
|
+
z4.z.string(),
|
|
1616
|
+
z4.z.array(
|
|
1617
|
+
z4.z.union([
|
|
1618
|
+
textPartSchema,
|
|
1619
|
+
filePartSchema,
|
|
1620
|
+
reasoningPartSchema,
|
|
1621
|
+
toolCallPartSchema,
|
|
1622
|
+
toolResultPartSchema
|
|
1623
|
+
])
|
|
1624
|
+
)
|
|
1625
|
+
]),
|
|
1626
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1627
|
+
});
|
|
1628
|
+
var toolModelMessageSchema = z4.z.object({
|
|
1629
|
+
role: z4.z.literal("tool"),
|
|
1630
|
+
content: z4.z.array(toolResultPartSchema),
|
|
1631
|
+
providerOptions: providerMetadataSchema.optional()
|
|
1632
|
+
});
|
|
1633
|
+
z4.z.union([
|
|
1634
|
+
systemModelMessageSchema,
|
|
1635
|
+
userModelMessageSchema,
|
|
1636
|
+
assistantModelMessageSchema,
|
|
1637
|
+
toolModelMessageSchema
|
|
1638
|
+
]);
|
|
1639
|
+
function asArray(value) {
|
|
1640
|
+
return value === void 0 ? [] : Array.isArray(value) ? value : [value];
|
|
1641
|
+
}
|
|
1642
|
+
createIdGenerator({
|
|
1643
|
+
prefix: "aitxt",
|
|
1644
|
+
size: 24
|
|
1645
|
+
});
|
|
1646
|
+
function prepareHeaders(headers, defaultHeaders) {
|
|
1647
|
+
const responseHeaders = new Headers(headers != null ? headers : {});
|
|
1648
|
+
for (const [key, value] of Object.entries(defaultHeaders)) {
|
|
1649
|
+
if (!responseHeaders.has(key)) {
|
|
1650
|
+
responseHeaders.set(key, value);
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
return responseHeaders;
|
|
1654
|
+
}
|
|
1655
|
+
var JsonToSseTransformStream = class extends TransformStream {
|
|
1656
|
+
constructor() {
|
|
1657
|
+
super({
|
|
1658
|
+
transform(part, controller) {
|
|
1659
|
+
controller.enqueue(`data: ${JSON.stringify(part)}
|
|
1660
|
+
|
|
1661
|
+
`);
|
|
1662
|
+
},
|
|
1663
|
+
flush(controller) {
|
|
1664
|
+
controller.enqueue("data: [DONE]\n\n");
|
|
1665
|
+
}
|
|
1666
|
+
});
|
|
1667
|
+
}
|
|
1668
|
+
};
|
|
1669
|
+
var UI_MESSAGE_STREAM_HEADERS = {
|
|
1670
|
+
"content-type": "text/event-stream",
|
|
1671
|
+
"cache-control": "no-cache",
|
|
1672
|
+
connection: "keep-alive",
|
|
1673
|
+
"x-vercel-ai-ui-message-stream": "v1",
|
|
1674
|
+
"x-accel-buffering": "no"
|
|
1675
|
+
// disable nginx buffering
|
|
1676
|
+
};
|
|
1677
|
+
function createUIMessageStreamResponse({
|
|
1678
|
+
status,
|
|
1679
|
+
statusText,
|
|
1680
|
+
headers,
|
|
1681
|
+
stream,
|
|
1682
|
+
consumeSseStream
|
|
1683
|
+
}) {
|
|
1684
|
+
let sseStream = stream.pipeThrough(new JsonToSseTransformStream());
|
|
1685
|
+
if (consumeSseStream) {
|
|
1686
|
+
const [stream1, stream2] = sseStream.tee();
|
|
1687
|
+
sseStream = stream1;
|
|
1688
|
+
consumeSseStream({ stream: stream2 });
|
|
1689
|
+
}
|
|
1690
|
+
return new Response(sseStream.pipeThrough(new TextEncoderStream()), {
|
|
1691
|
+
status,
|
|
1692
|
+
statusText,
|
|
1693
|
+
headers: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)
|
|
1694
|
+
});
|
|
1695
|
+
}
|
|
1696
|
+
function isDataUIMessageChunk(chunk) {
|
|
1697
|
+
return chunk.type.startsWith("data-");
|
|
1698
|
+
}
|
|
1699
|
+
function mergeObjects(base, overrides) {
|
|
1700
|
+
if (base === void 0 && overrides === void 0) {
|
|
1701
|
+
return void 0;
|
|
1702
|
+
}
|
|
1703
|
+
if (base === void 0) {
|
|
1704
|
+
return overrides;
|
|
1705
|
+
}
|
|
1706
|
+
if (overrides === void 0) {
|
|
1707
|
+
return base;
|
|
1708
|
+
}
|
|
1709
|
+
const result = { ...base };
|
|
1710
|
+
for (const key in overrides) {
|
|
1711
|
+
if (Object.prototype.hasOwnProperty.call(overrides, key)) {
|
|
1712
|
+
const overridesValue = overrides[key];
|
|
1713
|
+
if (overridesValue === void 0)
|
|
1714
|
+
continue;
|
|
1715
|
+
const baseValue = key in base ? base[key] : void 0;
|
|
1716
|
+
const isSourceObject = overridesValue !== null && typeof overridesValue === "object" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);
|
|
1717
|
+
const isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === "object" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);
|
|
1718
|
+
if (isSourceObject && isTargetObject) {
|
|
1719
|
+
result[key] = mergeObjects(
|
|
1720
|
+
baseValue,
|
|
1721
|
+
overridesValue
|
|
1722
|
+
);
|
|
1723
|
+
} else {
|
|
1724
|
+
result[key] = overridesValue;
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
return result;
|
|
1729
|
+
}
|
|
1730
|
+
function fixJson(input) {
|
|
1731
|
+
const stack = ["ROOT"];
|
|
1732
|
+
let lastValidIndex = -1;
|
|
1733
|
+
let literalStart = null;
|
|
1734
|
+
function processValueStart(char, i, swapState) {
|
|
1735
|
+
{
|
|
1736
|
+
switch (char) {
|
|
1737
|
+
case '"': {
|
|
1738
|
+
lastValidIndex = i;
|
|
1739
|
+
stack.pop();
|
|
1740
|
+
stack.push(swapState);
|
|
1741
|
+
stack.push("INSIDE_STRING");
|
|
1742
|
+
break;
|
|
1743
|
+
}
|
|
1744
|
+
case "f":
|
|
1745
|
+
case "t":
|
|
1746
|
+
case "n": {
|
|
1747
|
+
lastValidIndex = i;
|
|
1748
|
+
literalStart = i;
|
|
1749
|
+
stack.pop();
|
|
1750
|
+
stack.push(swapState);
|
|
1751
|
+
stack.push("INSIDE_LITERAL");
|
|
1752
|
+
break;
|
|
1753
|
+
}
|
|
1754
|
+
case "-": {
|
|
1755
|
+
stack.pop();
|
|
1756
|
+
stack.push(swapState);
|
|
1757
|
+
stack.push("INSIDE_NUMBER");
|
|
1758
|
+
break;
|
|
1759
|
+
}
|
|
1760
|
+
case "0":
|
|
1761
|
+
case "1":
|
|
1762
|
+
case "2":
|
|
1763
|
+
case "3":
|
|
1764
|
+
case "4":
|
|
1765
|
+
case "5":
|
|
1766
|
+
case "6":
|
|
1767
|
+
case "7":
|
|
1768
|
+
case "8":
|
|
1769
|
+
case "9": {
|
|
1770
|
+
lastValidIndex = i;
|
|
1771
|
+
stack.pop();
|
|
1772
|
+
stack.push(swapState);
|
|
1773
|
+
stack.push("INSIDE_NUMBER");
|
|
1774
|
+
break;
|
|
1775
|
+
}
|
|
1776
|
+
case "{": {
|
|
1777
|
+
lastValidIndex = i;
|
|
1778
|
+
stack.pop();
|
|
1779
|
+
stack.push(swapState);
|
|
1780
|
+
stack.push("INSIDE_OBJECT_START");
|
|
1781
|
+
break;
|
|
1782
|
+
}
|
|
1783
|
+
case "[": {
|
|
1784
|
+
lastValidIndex = i;
|
|
1785
|
+
stack.pop();
|
|
1786
|
+
stack.push(swapState);
|
|
1787
|
+
stack.push("INSIDE_ARRAY_START");
|
|
1788
|
+
break;
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
function processAfterObjectValue(char, i) {
|
|
1794
|
+
switch (char) {
|
|
1795
|
+
case ",": {
|
|
1796
|
+
stack.pop();
|
|
1797
|
+
stack.push("INSIDE_OBJECT_AFTER_COMMA");
|
|
1798
|
+
break;
|
|
1799
|
+
}
|
|
1800
|
+
case "}": {
|
|
1801
|
+
lastValidIndex = i;
|
|
1802
|
+
stack.pop();
|
|
1803
|
+
break;
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
function processAfterArrayValue(char, i) {
|
|
1808
|
+
switch (char) {
|
|
1809
|
+
case ",": {
|
|
1810
|
+
stack.pop();
|
|
1811
|
+
stack.push("INSIDE_ARRAY_AFTER_COMMA");
|
|
1812
|
+
break;
|
|
1813
|
+
}
|
|
1814
|
+
case "]": {
|
|
1815
|
+
lastValidIndex = i;
|
|
1816
|
+
stack.pop();
|
|
1817
|
+
break;
|
|
1818
|
+
}
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
for (let i = 0; i < input.length; i++) {
|
|
1822
|
+
const char = input[i];
|
|
1823
|
+
const currentState = stack[stack.length - 1];
|
|
1824
|
+
switch (currentState) {
|
|
1825
|
+
case "ROOT":
|
|
1826
|
+
processValueStart(char, i, "FINISH");
|
|
1827
|
+
break;
|
|
1828
|
+
case "INSIDE_OBJECT_START": {
|
|
1829
|
+
switch (char) {
|
|
1830
|
+
case '"': {
|
|
1831
|
+
stack.pop();
|
|
1832
|
+
stack.push("INSIDE_OBJECT_KEY");
|
|
1833
|
+
break;
|
|
1834
|
+
}
|
|
1835
|
+
case "}": {
|
|
1836
|
+
lastValidIndex = i;
|
|
1837
|
+
stack.pop();
|
|
1838
|
+
break;
|
|
1839
|
+
}
|
|
1840
|
+
}
|
|
1841
|
+
break;
|
|
1842
|
+
}
|
|
1843
|
+
case "INSIDE_OBJECT_AFTER_COMMA": {
|
|
1844
|
+
switch (char) {
|
|
1845
|
+
case '"': {
|
|
1846
|
+
stack.pop();
|
|
1847
|
+
stack.push("INSIDE_OBJECT_KEY");
|
|
1848
|
+
break;
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
break;
|
|
1852
|
+
}
|
|
1853
|
+
case "INSIDE_OBJECT_KEY": {
|
|
1854
|
+
switch (char) {
|
|
1855
|
+
case '"': {
|
|
1856
|
+
stack.pop();
|
|
1857
|
+
stack.push("INSIDE_OBJECT_AFTER_KEY");
|
|
1858
|
+
break;
|
|
1859
|
+
}
|
|
1860
|
+
}
|
|
1861
|
+
break;
|
|
1862
|
+
}
|
|
1863
|
+
case "INSIDE_OBJECT_AFTER_KEY": {
|
|
1864
|
+
switch (char) {
|
|
1865
|
+
case ":": {
|
|
1866
|
+
stack.pop();
|
|
1867
|
+
stack.push("INSIDE_OBJECT_BEFORE_VALUE");
|
|
1868
|
+
break;
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
break;
|
|
1872
|
+
}
|
|
1873
|
+
case "INSIDE_OBJECT_BEFORE_VALUE": {
|
|
1874
|
+
processValueStart(char, i, "INSIDE_OBJECT_AFTER_VALUE");
|
|
1875
|
+
break;
|
|
1876
|
+
}
|
|
1877
|
+
case "INSIDE_OBJECT_AFTER_VALUE": {
|
|
1878
|
+
processAfterObjectValue(char, i);
|
|
1879
|
+
break;
|
|
1880
|
+
}
|
|
1881
|
+
case "INSIDE_STRING": {
|
|
1882
|
+
switch (char) {
|
|
1883
|
+
case '"': {
|
|
1884
|
+
stack.pop();
|
|
1885
|
+
lastValidIndex = i;
|
|
1886
|
+
break;
|
|
1887
|
+
}
|
|
1888
|
+
case "\\": {
|
|
1889
|
+
stack.push("INSIDE_STRING_ESCAPE");
|
|
1890
|
+
break;
|
|
1891
|
+
}
|
|
1892
|
+
default: {
|
|
1893
|
+
lastValidIndex = i;
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
break;
|
|
1897
|
+
}
|
|
1898
|
+
case "INSIDE_ARRAY_START": {
|
|
1899
|
+
switch (char) {
|
|
1900
|
+
case "]": {
|
|
1901
|
+
lastValidIndex = i;
|
|
1902
|
+
stack.pop();
|
|
1903
|
+
break;
|
|
1904
|
+
}
|
|
1905
|
+
default: {
|
|
1906
|
+
lastValidIndex = i;
|
|
1907
|
+
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
|
|
1908
|
+
break;
|
|
1909
|
+
}
|
|
1910
|
+
}
|
|
1911
|
+
break;
|
|
1912
|
+
}
|
|
1913
|
+
case "INSIDE_ARRAY_AFTER_VALUE": {
|
|
1914
|
+
switch (char) {
|
|
1915
|
+
case ",": {
|
|
1916
|
+
stack.pop();
|
|
1917
|
+
stack.push("INSIDE_ARRAY_AFTER_COMMA");
|
|
1918
|
+
break;
|
|
1919
|
+
}
|
|
1920
|
+
case "]": {
|
|
1921
|
+
lastValidIndex = i;
|
|
1922
|
+
stack.pop();
|
|
1923
|
+
break;
|
|
1924
|
+
}
|
|
1925
|
+
default: {
|
|
1926
|
+
lastValidIndex = i;
|
|
1927
|
+
break;
|
|
1928
|
+
}
|
|
1929
|
+
}
|
|
1930
|
+
break;
|
|
1931
|
+
}
|
|
1932
|
+
case "INSIDE_ARRAY_AFTER_COMMA": {
|
|
1933
|
+
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
|
|
1934
|
+
break;
|
|
1935
|
+
}
|
|
1936
|
+
case "INSIDE_STRING_ESCAPE": {
|
|
1937
|
+
stack.pop();
|
|
1938
|
+
lastValidIndex = i;
|
|
1939
|
+
break;
|
|
1940
|
+
}
|
|
1941
|
+
case "INSIDE_NUMBER": {
|
|
1942
|
+
switch (char) {
|
|
1943
|
+
case "0":
|
|
1944
|
+
case "1":
|
|
1945
|
+
case "2":
|
|
1946
|
+
case "3":
|
|
1947
|
+
case "4":
|
|
1948
|
+
case "5":
|
|
1949
|
+
case "6":
|
|
1950
|
+
case "7":
|
|
1951
|
+
case "8":
|
|
1952
|
+
case "9": {
|
|
1953
|
+
lastValidIndex = i;
|
|
1954
|
+
break;
|
|
1955
|
+
}
|
|
1956
|
+
case "e":
|
|
1957
|
+
case "E":
|
|
1958
|
+
case "-":
|
|
1959
|
+
case ".": {
|
|
1960
|
+
break;
|
|
1961
|
+
}
|
|
1962
|
+
case ",": {
|
|
1963
|
+
stack.pop();
|
|
1964
|
+
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
|
|
1965
|
+
processAfterArrayValue(char, i);
|
|
1966
|
+
}
|
|
1967
|
+
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
|
|
1968
|
+
processAfterObjectValue(char, i);
|
|
1969
|
+
}
|
|
1970
|
+
break;
|
|
1971
|
+
}
|
|
1972
|
+
case "}": {
|
|
1973
|
+
stack.pop();
|
|
1974
|
+
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
|
|
1975
|
+
processAfterObjectValue(char, i);
|
|
1976
|
+
}
|
|
1977
|
+
break;
|
|
1978
|
+
}
|
|
1979
|
+
case "]": {
|
|
1980
|
+
stack.pop();
|
|
1981
|
+
if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
|
|
1982
|
+
processAfterArrayValue(char, i);
|
|
1983
|
+
}
|
|
1984
|
+
break;
|
|
1985
|
+
}
|
|
1986
|
+
default: {
|
|
1987
|
+
stack.pop();
|
|
1988
|
+
break;
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
break;
|
|
1992
|
+
}
|
|
1993
|
+
case "INSIDE_LITERAL": {
|
|
1994
|
+
const partialLiteral = input.substring(literalStart, i + 1);
|
|
1995
|
+
if (!"false".startsWith(partialLiteral) && !"true".startsWith(partialLiteral) && !"null".startsWith(partialLiteral)) {
|
|
1996
|
+
stack.pop();
|
|
1997
|
+
if (stack[stack.length - 1] === "INSIDE_OBJECT_AFTER_VALUE") {
|
|
1998
|
+
processAfterObjectValue(char, i);
|
|
1999
|
+
} else if (stack[stack.length - 1] === "INSIDE_ARRAY_AFTER_VALUE") {
|
|
2000
|
+
processAfterArrayValue(char, i);
|
|
2001
|
+
}
|
|
2002
|
+
} else {
|
|
2003
|
+
lastValidIndex = i;
|
|
2004
|
+
}
|
|
2005
|
+
break;
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
}
|
|
2009
|
+
let result = input.slice(0, lastValidIndex + 1);
|
|
2010
|
+
for (let i = stack.length - 1; i >= 0; i--) {
|
|
2011
|
+
const state = stack[i];
|
|
2012
|
+
switch (state) {
|
|
2013
|
+
case "INSIDE_STRING": {
|
|
2014
|
+
result += '"';
|
|
2015
|
+
break;
|
|
2016
|
+
}
|
|
2017
|
+
case "INSIDE_OBJECT_KEY":
|
|
2018
|
+
case "INSIDE_OBJECT_AFTER_KEY":
|
|
2019
|
+
case "INSIDE_OBJECT_AFTER_COMMA":
|
|
2020
|
+
case "INSIDE_OBJECT_START":
|
|
2021
|
+
case "INSIDE_OBJECT_BEFORE_VALUE":
|
|
2022
|
+
case "INSIDE_OBJECT_AFTER_VALUE": {
|
|
2023
|
+
result += "}";
|
|
2024
|
+
break;
|
|
2025
|
+
}
|
|
2026
|
+
case "INSIDE_ARRAY_START":
|
|
2027
|
+
case "INSIDE_ARRAY_AFTER_COMMA":
|
|
2028
|
+
case "INSIDE_ARRAY_AFTER_VALUE": {
|
|
2029
|
+
result += "]";
|
|
2030
|
+
break;
|
|
2031
|
+
}
|
|
2032
|
+
case "INSIDE_LITERAL": {
|
|
2033
|
+
const partialLiteral = input.substring(literalStart, input.length);
|
|
2034
|
+
if ("true".startsWith(partialLiteral)) {
|
|
2035
|
+
result += "true".slice(partialLiteral.length);
|
|
2036
|
+
} else if ("false".startsWith(partialLiteral)) {
|
|
2037
|
+
result += "false".slice(partialLiteral.length);
|
|
2038
|
+
} else if ("null".startsWith(partialLiteral)) {
|
|
2039
|
+
result += "null".slice(partialLiteral.length);
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
return result;
|
|
2045
|
+
}
|
|
2046
|
+
async function parsePartialJson(jsonText) {
|
|
2047
|
+
if (jsonText === void 0) {
|
|
2048
|
+
return { value: void 0, state: "undefined-input" };
|
|
2049
|
+
}
|
|
2050
|
+
let result = await safeParseJSON({ text: jsonText });
|
|
2051
|
+
if (result.success) {
|
|
2052
|
+
return { value: result.value, state: "successful-parse" };
|
|
2053
|
+
}
|
|
2054
|
+
result = await safeParseJSON({ text: fixJson(jsonText) });
|
|
2055
|
+
if (result.success) {
|
|
2056
|
+
return { value: result.value, state: "repaired-parse" };
|
|
2057
|
+
}
|
|
2058
|
+
return { value: void 0, state: "failed-parse" };
|
|
2059
|
+
}
|
|
2060
|
+
function isToolUIPart(part) {
|
|
2061
|
+
return part.type.startsWith("tool-");
|
|
2062
|
+
}
|
|
2063
|
+
function getToolName(part) {
|
|
2064
|
+
return part.type.split("-").slice(1).join("-");
|
|
2065
|
+
}
|
|
2066
|
+
function createStreamingUIMessageState({
|
|
2067
|
+
lastMessage,
|
|
2068
|
+
messageId
|
|
2069
|
+
}) {
|
|
2070
|
+
return {
|
|
2071
|
+
message: (lastMessage == null ? void 0 : lastMessage.role) === "assistant" ? lastMessage : {
|
|
2072
|
+
id: messageId,
|
|
2073
|
+
metadata: void 0,
|
|
2074
|
+
role: "assistant",
|
|
2075
|
+
parts: []
|
|
2076
|
+
},
|
|
2077
|
+
activeTextParts: {},
|
|
2078
|
+
activeReasoningParts: {},
|
|
2079
|
+
partialToolCalls: {}
|
|
2080
|
+
};
|
|
2081
|
+
}
|
|
2082
|
+
function processUIMessageStream({
|
|
2083
|
+
stream,
|
|
2084
|
+
messageMetadataSchema,
|
|
2085
|
+
dataPartSchemas,
|
|
2086
|
+
runUpdateMessageJob,
|
|
2087
|
+
onError,
|
|
2088
|
+
onToolCall,
|
|
2089
|
+
onData
|
|
2090
|
+
}) {
|
|
2091
|
+
return stream.pipeThrough(
|
|
2092
|
+
new TransformStream({
|
|
2093
|
+
async transform(chunk, controller) {
|
|
2094
|
+
await runUpdateMessageJob(async ({ state, write }) => {
|
|
2095
|
+
var _a17, _b, _c, _d;
|
|
2096
|
+
function getToolInvocation(toolCallId) {
|
|
2097
|
+
const toolInvocations = state.message.parts.filter(isToolUIPart);
|
|
2098
|
+
const toolInvocation = toolInvocations.find(
|
|
2099
|
+
(invocation) => invocation.toolCallId === toolCallId
|
|
2100
|
+
);
|
|
2101
|
+
if (toolInvocation == null) {
|
|
2102
|
+
throw new Error(
|
|
2103
|
+
"tool-output-error must be preceded by a tool-input-available"
|
|
2104
|
+
);
|
|
2105
|
+
}
|
|
2106
|
+
return toolInvocation;
|
|
2107
|
+
}
|
|
2108
|
+
function getDynamicToolInvocation(toolCallId) {
|
|
2109
|
+
const toolInvocations = state.message.parts.filter(
|
|
2110
|
+
(part) => part.type === "dynamic-tool"
|
|
2111
|
+
);
|
|
2112
|
+
const toolInvocation = toolInvocations.find(
|
|
2113
|
+
(invocation) => invocation.toolCallId === toolCallId
|
|
2114
|
+
);
|
|
2115
|
+
if (toolInvocation == null) {
|
|
2116
|
+
throw new Error(
|
|
2117
|
+
"tool-output-error must be preceded by a tool-input-available"
|
|
2118
|
+
);
|
|
2119
|
+
}
|
|
2120
|
+
return toolInvocation;
|
|
2121
|
+
}
|
|
2122
|
+
function updateToolPart(options) {
|
|
2123
|
+
var _a18;
|
|
2124
|
+
const part = state.message.parts.find(
|
|
2125
|
+
(part2) => isToolUIPart(part2) && part2.toolCallId === options.toolCallId
|
|
2126
|
+
);
|
|
2127
|
+
const anyOptions = options;
|
|
2128
|
+
const anyPart = part;
|
|
2129
|
+
if (part != null) {
|
|
2130
|
+
part.state = options.state;
|
|
2131
|
+
anyPart.input = anyOptions.input;
|
|
2132
|
+
anyPart.output = anyOptions.output;
|
|
2133
|
+
anyPart.errorText = anyOptions.errorText;
|
|
2134
|
+
anyPart.rawInput = anyOptions.rawInput;
|
|
2135
|
+
anyPart.preliminary = anyOptions.preliminary;
|
|
2136
|
+
anyPart.providerExecuted = (_a18 = anyOptions.providerExecuted) != null ? _a18 : part.providerExecuted;
|
|
2137
|
+
if (anyOptions.providerMetadata != null && part.state === "input-available") {
|
|
2138
|
+
part.callProviderMetadata = anyOptions.providerMetadata;
|
|
2139
|
+
}
|
|
2140
|
+
} else {
|
|
2141
|
+
state.message.parts.push({
|
|
2142
|
+
type: `tool-${options.toolName}`,
|
|
2143
|
+
toolCallId: options.toolCallId,
|
|
2144
|
+
state: options.state,
|
|
2145
|
+
input: anyOptions.input,
|
|
2146
|
+
output: anyOptions.output,
|
|
2147
|
+
rawInput: anyOptions.rawInput,
|
|
2148
|
+
errorText: anyOptions.errorText,
|
|
2149
|
+
providerExecuted: anyOptions.providerExecuted,
|
|
2150
|
+
preliminary: anyOptions.preliminary,
|
|
2151
|
+
...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
|
|
2152
|
+
});
|
|
2153
|
+
}
|
|
2154
|
+
}
|
|
2155
|
+
function updateDynamicToolPart(options) {
|
|
2156
|
+
var _a18;
|
|
2157
|
+
const part = state.message.parts.find(
|
|
2158
|
+
(part2) => part2.type === "dynamic-tool" && part2.toolCallId === options.toolCallId
|
|
2159
|
+
);
|
|
2160
|
+
const anyOptions = options;
|
|
2161
|
+
const anyPart = part;
|
|
2162
|
+
if (part != null) {
|
|
2163
|
+
part.state = options.state;
|
|
2164
|
+
anyPart.toolName = options.toolName;
|
|
2165
|
+
anyPart.input = anyOptions.input;
|
|
2166
|
+
anyPart.output = anyOptions.output;
|
|
2167
|
+
anyPart.errorText = anyOptions.errorText;
|
|
2168
|
+
anyPart.rawInput = (_a18 = anyOptions.rawInput) != null ? _a18 : anyPart.rawInput;
|
|
2169
|
+
anyPart.preliminary = anyOptions.preliminary;
|
|
2170
|
+
if (anyOptions.providerMetadata != null && part.state === "input-available") {
|
|
2171
|
+
part.callProviderMetadata = anyOptions.providerMetadata;
|
|
2172
|
+
}
|
|
2173
|
+
} else {
|
|
2174
|
+
state.message.parts.push({
|
|
2175
|
+
type: "dynamic-tool",
|
|
2176
|
+
toolName: options.toolName,
|
|
2177
|
+
toolCallId: options.toolCallId,
|
|
2178
|
+
state: options.state,
|
|
2179
|
+
input: anyOptions.input,
|
|
2180
|
+
output: anyOptions.output,
|
|
2181
|
+
errorText: anyOptions.errorText,
|
|
2182
|
+
preliminary: anyOptions.preliminary,
|
|
2183
|
+
...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
|
|
2184
|
+
});
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
async function updateMessageMetadata(metadata) {
|
|
2188
|
+
if (metadata != null) {
|
|
2189
|
+
const mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;
|
|
2190
|
+
if (messageMetadataSchema != null) {
|
|
2191
|
+
await validateTypes({
|
|
2192
|
+
value: mergedMetadata,
|
|
2193
|
+
schema: messageMetadataSchema
|
|
2194
|
+
});
|
|
2195
|
+
}
|
|
2196
|
+
state.message.metadata = mergedMetadata;
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
switch (chunk.type) {
|
|
2200
|
+
case "text-start": {
|
|
2201
|
+
const textPart = {
|
|
2202
|
+
type: "text",
|
|
2203
|
+
text: "",
|
|
2204
|
+
providerMetadata: chunk.providerMetadata,
|
|
2205
|
+
state: "streaming"
|
|
2206
|
+
};
|
|
2207
|
+
state.activeTextParts[chunk.id] = textPart;
|
|
2208
|
+
state.message.parts.push(textPart);
|
|
2209
|
+
write();
|
|
2210
|
+
break;
|
|
2211
|
+
}
|
|
2212
|
+
case "text-delta": {
|
|
2213
|
+
const textPart = state.activeTextParts[chunk.id];
|
|
2214
|
+
textPart.text += chunk.delta;
|
|
2215
|
+
textPart.providerMetadata = (_a17 = chunk.providerMetadata) != null ? _a17 : textPart.providerMetadata;
|
|
2216
|
+
write();
|
|
2217
|
+
break;
|
|
2218
|
+
}
|
|
2219
|
+
case "text-end": {
|
|
2220
|
+
const textPart = state.activeTextParts[chunk.id];
|
|
2221
|
+
textPart.state = "done";
|
|
2222
|
+
textPart.providerMetadata = (_b = chunk.providerMetadata) != null ? _b : textPart.providerMetadata;
|
|
2223
|
+
delete state.activeTextParts[chunk.id];
|
|
2224
|
+
write();
|
|
2225
|
+
break;
|
|
2226
|
+
}
|
|
2227
|
+
case "reasoning-start": {
|
|
2228
|
+
const reasoningPart = {
|
|
2229
|
+
type: "reasoning",
|
|
2230
|
+
text: "",
|
|
2231
|
+
providerMetadata: chunk.providerMetadata,
|
|
2232
|
+
state: "streaming"
|
|
2233
|
+
};
|
|
2234
|
+
state.activeReasoningParts[chunk.id] = reasoningPart;
|
|
2235
|
+
state.message.parts.push(reasoningPart);
|
|
2236
|
+
write();
|
|
2237
|
+
break;
|
|
2238
|
+
}
|
|
2239
|
+
case "reasoning-delta": {
|
|
2240
|
+
const reasoningPart = state.activeReasoningParts[chunk.id];
|
|
2241
|
+
reasoningPart.text += chunk.delta;
|
|
2242
|
+
reasoningPart.providerMetadata = (_c = chunk.providerMetadata) != null ? _c : reasoningPart.providerMetadata;
|
|
2243
|
+
write();
|
|
2244
|
+
break;
|
|
2245
|
+
}
|
|
2246
|
+
case "reasoning-end": {
|
|
2247
|
+
const reasoningPart = state.activeReasoningParts[chunk.id];
|
|
2248
|
+
reasoningPart.providerMetadata = (_d = chunk.providerMetadata) != null ? _d : reasoningPart.providerMetadata;
|
|
2249
|
+
reasoningPart.state = "done";
|
|
2250
|
+
delete state.activeReasoningParts[chunk.id];
|
|
2251
|
+
write();
|
|
2252
|
+
break;
|
|
2253
|
+
}
|
|
2254
|
+
case "file": {
|
|
2255
|
+
state.message.parts.push({
|
|
2256
|
+
type: "file",
|
|
2257
|
+
mediaType: chunk.mediaType,
|
|
2258
|
+
url: chunk.url
|
|
2259
|
+
});
|
|
2260
|
+
write();
|
|
2261
|
+
break;
|
|
2262
|
+
}
|
|
2263
|
+
case "source-url": {
|
|
2264
|
+
state.message.parts.push({
|
|
2265
|
+
type: "source-url",
|
|
2266
|
+
sourceId: chunk.sourceId,
|
|
2267
|
+
url: chunk.url,
|
|
2268
|
+
title: chunk.title,
|
|
2269
|
+
providerMetadata: chunk.providerMetadata
|
|
2270
|
+
});
|
|
2271
|
+
write();
|
|
2272
|
+
break;
|
|
2273
|
+
}
|
|
2274
|
+
case "source-document": {
|
|
2275
|
+
state.message.parts.push({
|
|
2276
|
+
type: "source-document",
|
|
2277
|
+
sourceId: chunk.sourceId,
|
|
2278
|
+
mediaType: chunk.mediaType,
|
|
2279
|
+
title: chunk.title,
|
|
2280
|
+
filename: chunk.filename,
|
|
2281
|
+
providerMetadata: chunk.providerMetadata
|
|
2282
|
+
});
|
|
2283
|
+
write();
|
|
2284
|
+
break;
|
|
2285
|
+
}
|
|
2286
|
+
case "tool-input-start": {
|
|
2287
|
+
const toolInvocations = state.message.parts.filter(isToolUIPart);
|
|
2288
|
+
state.partialToolCalls[chunk.toolCallId] = {
|
|
2289
|
+
text: "",
|
|
2290
|
+
toolName: chunk.toolName,
|
|
2291
|
+
index: toolInvocations.length,
|
|
2292
|
+
dynamic: chunk.dynamic
|
|
2293
|
+
};
|
|
2294
|
+
if (chunk.dynamic) {
|
|
2295
|
+
updateDynamicToolPart({
|
|
2296
|
+
toolCallId: chunk.toolCallId,
|
|
2297
|
+
toolName: chunk.toolName,
|
|
2298
|
+
state: "input-streaming",
|
|
2299
|
+
input: void 0
|
|
2300
|
+
});
|
|
2301
|
+
} else {
|
|
2302
|
+
updateToolPart({
|
|
2303
|
+
toolCallId: chunk.toolCallId,
|
|
2304
|
+
toolName: chunk.toolName,
|
|
2305
|
+
state: "input-streaming",
|
|
2306
|
+
input: void 0,
|
|
2307
|
+
providerExecuted: chunk.providerExecuted
|
|
2308
|
+
});
|
|
2309
|
+
}
|
|
2310
|
+
write();
|
|
2311
|
+
break;
|
|
2312
|
+
}
|
|
2313
|
+
case "tool-input-delta": {
|
|
2314
|
+
const partialToolCall = state.partialToolCalls[chunk.toolCallId];
|
|
2315
|
+
partialToolCall.text += chunk.inputTextDelta;
|
|
2316
|
+
const { value: partialArgs } = await parsePartialJson(
|
|
2317
|
+
partialToolCall.text
|
|
2318
|
+
);
|
|
2319
|
+
if (partialToolCall.dynamic) {
|
|
2320
|
+
updateDynamicToolPart({
|
|
2321
|
+
toolCallId: chunk.toolCallId,
|
|
2322
|
+
toolName: partialToolCall.toolName,
|
|
2323
|
+
state: "input-streaming",
|
|
2324
|
+
input: partialArgs
|
|
2325
|
+
});
|
|
2326
|
+
} else {
|
|
2327
|
+
updateToolPart({
|
|
2328
|
+
toolCallId: chunk.toolCallId,
|
|
2329
|
+
toolName: partialToolCall.toolName,
|
|
2330
|
+
state: "input-streaming",
|
|
2331
|
+
input: partialArgs
|
|
2332
|
+
});
|
|
2333
|
+
}
|
|
2334
|
+
write();
|
|
2335
|
+
break;
|
|
2336
|
+
}
|
|
2337
|
+
case "tool-input-available": {
|
|
2338
|
+
if (chunk.dynamic) {
|
|
2339
|
+
updateDynamicToolPart({
|
|
2340
|
+
toolCallId: chunk.toolCallId,
|
|
2341
|
+
toolName: chunk.toolName,
|
|
2342
|
+
state: "input-available",
|
|
2343
|
+
input: chunk.input,
|
|
2344
|
+
providerMetadata: chunk.providerMetadata
|
|
2345
|
+
});
|
|
2346
|
+
} else {
|
|
2347
|
+
updateToolPart({
|
|
2348
|
+
toolCallId: chunk.toolCallId,
|
|
2349
|
+
toolName: chunk.toolName,
|
|
2350
|
+
state: "input-available",
|
|
2351
|
+
input: chunk.input,
|
|
2352
|
+
providerExecuted: chunk.providerExecuted,
|
|
2353
|
+
providerMetadata: chunk.providerMetadata
|
|
2354
|
+
});
|
|
2355
|
+
}
|
|
2356
|
+
write();
|
|
2357
|
+
if (onToolCall && !chunk.providerExecuted) {
|
|
2358
|
+
await onToolCall({
|
|
2359
|
+
toolCall: chunk
|
|
2360
|
+
});
|
|
2361
|
+
}
|
|
2362
|
+
break;
|
|
2363
|
+
}
|
|
2364
|
+
case "tool-input-error": {
|
|
2365
|
+
if (chunk.dynamic) {
|
|
2366
|
+
updateDynamicToolPart({
|
|
2367
|
+
toolCallId: chunk.toolCallId,
|
|
2368
|
+
toolName: chunk.toolName,
|
|
2369
|
+
state: "output-error",
|
|
2370
|
+
input: chunk.input,
|
|
2371
|
+
errorText: chunk.errorText,
|
|
2372
|
+
providerMetadata: chunk.providerMetadata
|
|
2373
|
+
});
|
|
2374
|
+
} else {
|
|
2375
|
+
updateToolPart({
|
|
2376
|
+
toolCallId: chunk.toolCallId,
|
|
2377
|
+
toolName: chunk.toolName,
|
|
2378
|
+
state: "output-error",
|
|
2379
|
+
input: void 0,
|
|
2380
|
+
rawInput: chunk.input,
|
|
2381
|
+
errorText: chunk.errorText,
|
|
2382
|
+
providerExecuted: chunk.providerExecuted,
|
|
2383
|
+
providerMetadata: chunk.providerMetadata
|
|
2384
|
+
});
|
|
2385
|
+
}
|
|
2386
|
+
write();
|
|
2387
|
+
break;
|
|
2388
|
+
}
|
|
2389
|
+
case "tool-output-available": {
|
|
2390
|
+
if (chunk.dynamic) {
|
|
2391
|
+
const toolInvocation = getDynamicToolInvocation(
|
|
2392
|
+
chunk.toolCallId
|
|
2393
|
+
);
|
|
2394
|
+
updateDynamicToolPart({
|
|
2395
|
+
toolCallId: chunk.toolCallId,
|
|
2396
|
+
toolName: toolInvocation.toolName,
|
|
2397
|
+
state: "output-available",
|
|
2398
|
+
input: toolInvocation.input,
|
|
2399
|
+
output: chunk.output,
|
|
2400
|
+
preliminary: chunk.preliminary
|
|
2401
|
+
});
|
|
2402
|
+
} else {
|
|
2403
|
+
const toolInvocation = getToolInvocation(chunk.toolCallId);
|
|
2404
|
+
updateToolPart({
|
|
2405
|
+
toolCallId: chunk.toolCallId,
|
|
2406
|
+
toolName: getToolName(toolInvocation),
|
|
2407
|
+
state: "output-available",
|
|
2408
|
+
input: toolInvocation.input,
|
|
2409
|
+
output: chunk.output,
|
|
2410
|
+
providerExecuted: chunk.providerExecuted,
|
|
2411
|
+
preliminary: chunk.preliminary
|
|
2412
|
+
});
|
|
2413
|
+
}
|
|
2414
|
+
write();
|
|
2415
|
+
break;
|
|
2416
|
+
}
|
|
2417
|
+
case "tool-output-error": {
|
|
2418
|
+
if (chunk.dynamic) {
|
|
2419
|
+
const toolInvocation = getDynamicToolInvocation(
|
|
2420
|
+
chunk.toolCallId
|
|
2421
|
+
);
|
|
2422
|
+
updateDynamicToolPart({
|
|
2423
|
+
toolCallId: chunk.toolCallId,
|
|
2424
|
+
toolName: toolInvocation.toolName,
|
|
2425
|
+
state: "output-error",
|
|
2426
|
+
input: toolInvocation.input,
|
|
2427
|
+
errorText: chunk.errorText
|
|
2428
|
+
});
|
|
2429
|
+
} else {
|
|
2430
|
+
const toolInvocation = getToolInvocation(chunk.toolCallId);
|
|
2431
|
+
updateToolPart({
|
|
2432
|
+
toolCallId: chunk.toolCallId,
|
|
2433
|
+
toolName: getToolName(toolInvocation),
|
|
2434
|
+
state: "output-error",
|
|
2435
|
+
input: toolInvocation.input,
|
|
2436
|
+
rawInput: toolInvocation.rawInput,
|
|
2437
|
+
errorText: chunk.errorText
|
|
2438
|
+
});
|
|
2439
|
+
}
|
|
2440
|
+
write();
|
|
2441
|
+
break;
|
|
2442
|
+
}
|
|
2443
|
+
case "start-step": {
|
|
2444
|
+
state.message.parts.push({ type: "step-start" });
|
|
2445
|
+
break;
|
|
2446
|
+
}
|
|
2447
|
+
case "finish-step": {
|
|
2448
|
+
state.activeTextParts = {};
|
|
2449
|
+
state.activeReasoningParts = {};
|
|
2450
|
+
break;
|
|
2451
|
+
}
|
|
2452
|
+
case "start": {
|
|
2453
|
+
if (chunk.messageId != null) {
|
|
2454
|
+
state.message.id = chunk.messageId;
|
|
2455
|
+
}
|
|
2456
|
+
await updateMessageMetadata(chunk.messageMetadata);
|
|
2457
|
+
if (chunk.messageId != null || chunk.messageMetadata != null) {
|
|
2458
|
+
write();
|
|
2459
|
+
}
|
|
2460
|
+
break;
|
|
2461
|
+
}
|
|
2462
|
+
case "finish": {
|
|
2463
|
+
await updateMessageMetadata(chunk.messageMetadata);
|
|
2464
|
+
if (chunk.messageMetadata != null) {
|
|
2465
|
+
write();
|
|
2466
|
+
}
|
|
2467
|
+
break;
|
|
2468
|
+
}
|
|
2469
|
+
case "message-metadata": {
|
|
2470
|
+
await updateMessageMetadata(chunk.messageMetadata);
|
|
2471
|
+
if (chunk.messageMetadata != null) {
|
|
2472
|
+
write();
|
|
2473
|
+
}
|
|
2474
|
+
break;
|
|
2475
|
+
}
|
|
2476
|
+
case "error": {
|
|
2477
|
+
onError == null ? void 0 : onError(new Error(chunk.errorText));
|
|
2478
|
+
break;
|
|
2479
|
+
}
|
|
2480
|
+
default: {
|
|
2481
|
+
if (isDataUIMessageChunk(chunk)) {
|
|
2482
|
+
if ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk.type]) != null) {
|
|
2483
|
+
await validateTypes({
|
|
2484
|
+
value: chunk.data,
|
|
2485
|
+
schema: dataPartSchemas[chunk.type]
|
|
2486
|
+
});
|
|
2487
|
+
}
|
|
2488
|
+
const dataChunk = chunk;
|
|
2489
|
+
if (dataChunk.transient) {
|
|
2490
|
+
onData == null ? void 0 : onData(dataChunk);
|
|
2491
|
+
break;
|
|
2492
|
+
}
|
|
2493
|
+
const existingUIPart = dataChunk.id != null ? state.message.parts.find(
|
|
2494
|
+
(chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id
|
|
2495
|
+
) : void 0;
|
|
2496
|
+
if (existingUIPart != null) {
|
|
2497
|
+
existingUIPart.data = dataChunk.data;
|
|
2498
|
+
} else {
|
|
2499
|
+
state.message.parts.push(dataChunk);
|
|
2500
|
+
}
|
|
2501
|
+
onData == null ? void 0 : onData(dataChunk);
|
|
2502
|
+
write();
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
controller.enqueue(chunk);
|
|
2507
|
+
});
|
|
2508
|
+
}
|
|
2509
|
+
})
|
|
2510
|
+
);
|
|
2511
|
+
}
|
|
2512
|
+
function handleUIMessageStreamFinish({
|
|
2513
|
+
messageId,
|
|
2514
|
+
originalMessages = [],
|
|
2515
|
+
onFinish,
|
|
2516
|
+
onError,
|
|
2517
|
+
stream
|
|
2518
|
+
}) {
|
|
2519
|
+
let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];
|
|
2520
|
+
if ((lastMessage == null ? void 0 : lastMessage.role) !== "assistant") {
|
|
2521
|
+
lastMessage = void 0;
|
|
2522
|
+
} else {
|
|
2523
|
+
messageId = lastMessage.id;
|
|
2524
|
+
}
|
|
2525
|
+
let isAborted = false;
|
|
2526
|
+
const idInjectedStream = stream.pipeThrough(
|
|
2527
|
+
new TransformStream({
|
|
2528
|
+
transform(chunk, controller) {
|
|
2529
|
+
if (chunk.type === "start") {
|
|
2530
|
+
const startChunk = chunk;
|
|
2531
|
+
if (startChunk.messageId == null && messageId != null) {
|
|
2532
|
+
startChunk.messageId = messageId;
|
|
2533
|
+
}
|
|
2534
|
+
}
|
|
2535
|
+
if (chunk.type === "abort") {
|
|
2536
|
+
isAborted = true;
|
|
2537
|
+
}
|
|
2538
|
+
controller.enqueue(chunk);
|
|
2539
|
+
}
|
|
2540
|
+
})
|
|
2541
|
+
);
|
|
2542
|
+
if (onFinish == null) {
|
|
2543
|
+
return idInjectedStream;
|
|
2544
|
+
}
|
|
2545
|
+
const state = createStreamingUIMessageState({
|
|
2546
|
+
lastMessage: lastMessage ? structuredClone(lastMessage) : void 0,
|
|
2547
|
+
messageId: messageId != null ? messageId : ""
|
|
2548
|
+
// will be overridden by the stream
|
|
2549
|
+
});
|
|
2550
|
+
const runUpdateMessageJob = async (job) => {
|
|
2551
|
+
await job({ state, write: () => {
|
|
2552
|
+
} });
|
|
2553
|
+
};
|
|
2554
|
+
let finishCalled = false;
|
|
2555
|
+
const callOnFinish = async () => {
|
|
2556
|
+
if (finishCalled || !onFinish) {
|
|
2557
|
+
return;
|
|
2558
|
+
}
|
|
2559
|
+
finishCalled = true;
|
|
2560
|
+
const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
|
|
2561
|
+
await onFinish({
|
|
2562
|
+
isAborted,
|
|
2563
|
+
isContinuation,
|
|
2564
|
+
responseMessage: state.message,
|
|
2565
|
+
messages: [
|
|
2566
|
+
...isContinuation ? originalMessages.slice(0, -1) : originalMessages,
|
|
2567
|
+
state.message
|
|
2568
|
+
]
|
|
2569
|
+
});
|
|
2570
|
+
};
|
|
2571
|
+
return processUIMessageStream({
|
|
2572
|
+
stream: idInjectedStream,
|
|
2573
|
+
runUpdateMessageJob,
|
|
2574
|
+
onError
|
|
2575
|
+
}).pipeThrough(
|
|
2576
|
+
new TransformStream({
|
|
2577
|
+
transform(chunk, controller) {
|
|
2578
|
+
controller.enqueue(chunk);
|
|
2579
|
+
},
|
|
2580
|
+
// @ts-expect-error cancel is still new and missing from types https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility
|
|
2581
|
+
async cancel() {
|
|
2582
|
+
await callOnFinish();
|
|
2583
|
+
},
|
|
2584
|
+
async flush() {
|
|
2585
|
+
await callOnFinish();
|
|
2586
|
+
}
|
|
2587
|
+
})
|
|
2588
|
+
);
|
|
2589
|
+
}
|
|
2590
|
+
createIdGenerator({
|
|
2591
|
+
prefix: "aitxt",
|
|
2592
|
+
size: 24
|
|
2593
|
+
});
|
|
2594
|
+
createIdGenerator({ prefix: "aiobj", size: 24 });
|
|
2595
|
+
createIdGenerator({ prefix: "aiobj", size: 24 });
|
|
2596
|
+
var output_exports = {};
|
|
2597
|
+
__export(output_exports, {
|
|
2598
|
+
object: () => object,
|
|
2599
|
+
text: () => text
|
|
2600
|
+
});
|
|
2601
|
+
var text = () => ({
|
|
2602
|
+
type: "text",
|
|
2603
|
+
responseFormat: { type: "text" },
|
|
2604
|
+
async parsePartial({ text: text2 }) {
|
|
2605
|
+
return { partial: text2 };
|
|
2606
|
+
},
|
|
2607
|
+
async parseOutput({ text: text2 }) {
|
|
2608
|
+
return text2;
|
|
2609
|
+
}
|
|
2610
|
+
});
|
|
2611
|
+
var object = ({
|
|
2612
|
+
schema: inputSchema
|
|
2613
|
+
}) => {
|
|
2614
|
+
const schema = asSchema(inputSchema);
|
|
2615
|
+
return {
|
|
2616
|
+
type: "object",
|
|
2617
|
+
responseFormat: {
|
|
2618
|
+
type: "json",
|
|
2619
|
+
schema: schema.jsonSchema
|
|
2620
|
+
},
|
|
2621
|
+
async parsePartial({ text: text2 }) {
|
|
2622
|
+
const result = await parsePartialJson(text2);
|
|
2623
|
+
switch (result.state) {
|
|
2624
|
+
case "failed-parse":
|
|
2625
|
+
case "undefined-input":
|
|
2626
|
+
return void 0;
|
|
2627
|
+
case "repaired-parse":
|
|
2628
|
+
case "successful-parse":
|
|
2629
|
+
return {
|
|
2630
|
+
// Note: currently no validation of partial results:
|
|
2631
|
+
partial: result.value
|
|
2632
|
+
};
|
|
2633
|
+
default: {
|
|
2634
|
+
const _exhaustiveCheck = result.state;
|
|
2635
|
+
throw new Error(`Unsupported parse state: ${_exhaustiveCheck}`);
|
|
2636
|
+
}
|
|
2637
|
+
}
|
|
2638
|
+
},
|
|
2639
|
+
async parseOutput({ text: text2 }, context) {
|
|
2640
|
+
const parseResult = await safeParseJSON({ text: text2 });
|
|
2641
|
+
if (!parseResult.success) {
|
|
2642
|
+
throw new NoObjectGeneratedError({
|
|
2643
|
+
message: "No object generated: could not parse the response.",
|
|
2644
|
+
cause: parseResult.error,
|
|
2645
|
+
text: text2,
|
|
2646
|
+
response: context.response,
|
|
2647
|
+
usage: context.usage,
|
|
2648
|
+
finishReason: context.finishReason
|
|
2649
|
+
});
|
|
2650
|
+
}
|
|
2651
|
+
const validationResult = await safeValidateTypes({
|
|
2652
|
+
value: parseResult.value,
|
|
2653
|
+
schema
|
|
2654
|
+
});
|
|
2655
|
+
if (!validationResult.success) {
|
|
2656
|
+
throw new NoObjectGeneratedError({
|
|
2657
|
+
message: "No object generated: response did not match schema.",
|
|
2658
|
+
cause: validationResult.error,
|
|
2659
|
+
text: text2,
|
|
2660
|
+
response: context.response,
|
|
2661
|
+
usage: context.usage,
|
|
2662
|
+
finishReason: context.finishReason
|
|
2663
|
+
});
|
|
2664
|
+
}
|
|
2665
|
+
return validationResult.value;
|
|
2666
|
+
}
|
|
2667
|
+
};
|
|
2668
|
+
};
|
|
2669
|
+
var wrapLanguageModel = ({
|
|
2670
|
+
model,
|
|
2671
|
+
middleware: middlewareArg,
|
|
2672
|
+
modelId,
|
|
2673
|
+
providerId
|
|
2674
|
+
}) => {
|
|
2675
|
+
return asArray(middlewareArg).reverse().reduce((wrappedModel, middleware) => {
|
|
2676
|
+
return doWrap({ model: wrappedModel, middleware, modelId, providerId });
|
|
2677
|
+
}, model);
|
|
2678
|
+
};
|
|
2679
|
+
var doWrap = ({
|
|
2680
|
+
model,
|
|
2681
|
+
middleware: {
|
|
2682
|
+
transformParams,
|
|
2683
|
+
wrapGenerate,
|
|
2684
|
+
wrapStream,
|
|
2685
|
+
overrideProvider,
|
|
2686
|
+
overrideModelId,
|
|
2687
|
+
overrideSupportedUrls
|
|
2688
|
+
},
|
|
2689
|
+
modelId,
|
|
2690
|
+
providerId
|
|
2691
|
+
}) => {
|
|
2692
|
+
var _a17, _b, _c;
|
|
2693
|
+
async function doTransform({
|
|
2694
|
+
params,
|
|
2695
|
+
type
|
|
2696
|
+
}) {
|
|
2697
|
+
return transformParams ? await transformParams({ params, type, model }) : params;
|
|
2698
|
+
}
|
|
2699
|
+
return {
|
|
2700
|
+
specificationVersion: "v2",
|
|
2701
|
+
provider: (_a17 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a17 : model.provider,
|
|
2702
|
+
modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
|
|
2703
|
+
supportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,
|
|
2704
|
+
async doGenerate(params) {
|
|
2705
|
+
const transformedParams = await doTransform({ params, type: "generate" });
|
|
2706
|
+
const doGenerate = async () => model.doGenerate(transformedParams);
|
|
2707
|
+
const doStream = async () => model.doStream(transformedParams);
|
|
2708
|
+
return wrapGenerate ? wrapGenerate({
|
|
2709
|
+
doGenerate,
|
|
2710
|
+
doStream,
|
|
2711
|
+
params: transformedParams,
|
|
2712
|
+
model
|
|
2713
|
+
}) : doGenerate();
|
|
2714
|
+
},
|
|
2715
|
+
async doStream(params) {
|
|
2716
|
+
const transformedParams = await doTransform({ params, type: "stream" });
|
|
2717
|
+
const doGenerate = async () => model.doGenerate(transformedParams);
|
|
2718
|
+
const doStream = async () => model.doStream(transformedParams);
|
|
2719
|
+
return wrapStream ? wrapStream({ doGenerate, doStream, params: transformedParams, model }) : doStream();
|
|
2720
|
+
}
|
|
2721
|
+
};
|
|
2722
|
+
};
|
|
2723
|
+
var ClientOrServerImplementationSchema = z4.z.looseObject({
|
|
2724
|
+
name: z4.z.string(),
|
|
2725
|
+
version: z4.z.string()
|
|
2726
|
+
});
|
|
2727
|
+
var BaseParamsSchema = z4.z.looseObject({
|
|
2728
|
+
_meta: z4.z.optional(z4.z.object({}).loose())
|
|
2729
|
+
});
|
|
2730
|
+
var ResultSchema = BaseParamsSchema;
|
|
2731
|
+
var RequestSchema = z4.z.object({
|
|
2732
|
+
method: z4.z.string(),
|
|
2733
|
+
params: z4.z.optional(BaseParamsSchema)
|
|
2734
|
+
});
|
|
2735
|
+
var ServerCapabilitiesSchema = z4.z.looseObject({
|
|
2736
|
+
experimental: z4.z.optional(z4.z.object({}).loose()),
|
|
2737
|
+
logging: z4.z.optional(z4.z.object({}).loose()),
|
|
2738
|
+
prompts: z4.z.optional(
|
|
2739
|
+
z4.z.looseObject({
|
|
2740
|
+
listChanged: z4.z.optional(z4.z.boolean())
|
|
2741
|
+
})
|
|
2742
|
+
),
|
|
2743
|
+
resources: z4.z.optional(
|
|
2744
|
+
z4.z.looseObject({
|
|
2745
|
+
subscribe: z4.z.optional(z4.z.boolean()),
|
|
2746
|
+
listChanged: z4.z.optional(z4.z.boolean())
|
|
2747
|
+
})
|
|
2748
|
+
),
|
|
2749
|
+
tools: z4.z.optional(
|
|
2750
|
+
z4.z.looseObject({
|
|
2751
|
+
listChanged: z4.z.optional(z4.z.boolean())
|
|
2752
|
+
})
|
|
2753
|
+
)
|
|
2754
|
+
});
|
|
2755
|
+
ResultSchema.extend({
|
|
2756
|
+
protocolVersion: z4.z.string(),
|
|
2757
|
+
capabilities: ServerCapabilitiesSchema,
|
|
2758
|
+
serverInfo: ClientOrServerImplementationSchema,
|
|
2759
|
+
instructions: z4.z.optional(z4.z.string())
|
|
2760
|
+
});
|
|
2761
|
+
var PaginatedResultSchema = ResultSchema.extend({
|
|
2762
|
+
nextCursor: z4.z.optional(z4.z.string())
|
|
2763
|
+
});
|
|
2764
|
+
var ToolSchema = z4.z.object({
|
|
2765
|
+
name: z4.z.string(),
|
|
2766
|
+
description: z4.z.optional(z4.z.string()),
|
|
2767
|
+
inputSchema: z4.z.object({
|
|
2768
|
+
type: z4.z.literal("object"),
|
|
2769
|
+
properties: z4.z.optional(z4.z.object({}).loose())
|
|
2770
|
+
}).loose()
|
|
2771
|
+
}).loose();
|
|
2772
|
+
PaginatedResultSchema.extend({
|
|
2773
|
+
tools: z4.z.array(ToolSchema)
|
|
2774
|
+
});
|
|
2775
|
+
var TextContentSchema = z4.z.object({
|
|
2776
|
+
type: z4.z.literal("text"),
|
|
2777
|
+
text: z4.z.string()
|
|
2778
|
+
}).loose();
|
|
2779
|
+
var ImageContentSchema = z4.z.object({
|
|
2780
|
+
type: z4.z.literal("image"),
|
|
2781
|
+
data: z4.z.base64(),
|
|
2782
|
+
mimeType: z4.z.string()
|
|
2783
|
+
}).loose();
|
|
2784
|
+
var ResourceContentsSchema = z4.z.object({
|
|
2785
|
+
/**
|
|
2786
|
+
* The URI of this resource.
|
|
2787
|
+
*/
|
|
2788
|
+
uri: z4.z.string(),
|
|
2789
|
+
/**
|
|
2790
|
+
* The MIME type of this resource, if known.
|
|
2791
|
+
*/
|
|
2792
|
+
mimeType: z4.z.optional(z4.z.string())
|
|
2793
|
+
}).loose();
|
|
2794
|
+
var TextResourceContentsSchema = ResourceContentsSchema.extend({
|
|
2795
|
+
text: z4.z.string()
|
|
2796
|
+
});
|
|
2797
|
+
var BlobResourceContentsSchema = ResourceContentsSchema.extend({
|
|
2798
|
+
blob: z4.z.base64()
|
|
2799
|
+
});
|
|
2800
|
+
var EmbeddedResourceSchema = z4.z.object({
|
|
2801
|
+
type: z4.z.literal("resource"),
|
|
2802
|
+
resource: z4.z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
|
|
2803
|
+
}).loose();
|
|
2804
|
+
ResultSchema.extend({
|
|
2805
|
+
content: z4.z.array(
|
|
2806
|
+
z4.z.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
|
|
2807
|
+
),
|
|
2808
|
+
isError: z4.z.boolean().default(false).optional()
|
|
2809
|
+
}).or(
|
|
2810
|
+
ResultSchema.extend({
|
|
2811
|
+
toolResult: z4.z.unknown()
|
|
2812
|
+
})
|
|
2813
|
+
);
|
|
2814
|
+
var JSONRPC_VERSION = "2.0";
|
|
2815
|
+
var JSONRPCRequestSchema = z4.z.object({
|
|
2816
|
+
jsonrpc: z4.z.literal(JSONRPC_VERSION),
|
|
2817
|
+
id: z4.z.union([z4.z.string(), z4.z.number().int()])
|
|
2818
|
+
}).merge(RequestSchema).strict();
|
|
2819
|
+
var JSONRPCResponseSchema = z4.z.object({
|
|
2820
|
+
jsonrpc: z4.z.literal(JSONRPC_VERSION),
|
|
2821
|
+
id: z4.z.union([z4.z.string(), z4.z.number().int()]),
|
|
2822
|
+
result: ResultSchema
|
|
2823
|
+
}).strict();
|
|
2824
|
+
var JSONRPCErrorSchema = z4.z.object({
|
|
2825
|
+
jsonrpc: z4.z.literal(JSONRPC_VERSION),
|
|
2826
|
+
id: z4.z.union([z4.z.string(), z4.z.number().int()]),
|
|
2827
|
+
error: z4.z.object({
|
|
2828
|
+
code: z4.z.number().int(),
|
|
2829
|
+
message: z4.z.string(),
|
|
2830
|
+
data: z4.z.optional(z4.z.unknown())
|
|
2831
|
+
})
|
|
2832
|
+
}).strict();
|
|
2833
|
+
var JSONRPCNotificationSchema = z4.z.object({
|
|
2834
|
+
jsonrpc: z4.z.literal(JSONRPC_VERSION)
|
|
2835
|
+
}).merge(
|
|
2836
|
+
z4.z.object({
|
|
2837
|
+
method: z4.z.string(),
|
|
2838
|
+
params: z4.z.optional(BaseParamsSchema)
|
|
2839
|
+
})
|
|
2840
|
+
).strict();
|
|
2841
|
+
z4.z.union([
|
|
2842
|
+
JSONRPCRequestSchema,
|
|
2843
|
+
JSONRPCNotificationSchema,
|
|
2844
|
+
JSONRPCResponseSchema,
|
|
2845
|
+
JSONRPCErrorSchema
|
|
2846
|
+
]);
|
|
2847
|
+
function createUIMessageStream({
|
|
2848
|
+
execute,
|
|
2849
|
+
onError = getErrorMessage2,
|
|
2850
|
+
originalMessages,
|
|
2851
|
+
onFinish,
|
|
2852
|
+
generateId: generateId3 = generateId
|
|
2853
|
+
}) {
|
|
2854
|
+
let controller;
|
|
2855
|
+
const ongoingStreamPromises = [];
|
|
2856
|
+
const stream = new ReadableStream({
|
|
2857
|
+
start(controllerArg) {
|
|
2858
|
+
controller = controllerArg;
|
|
2859
|
+
}
|
|
2860
|
+
});
|
|
2861
|
+
function safeEnqueue(data) {
|
|
2862
|
+
try {
|
|
2863
|
+
controller.enqueue(data);
|
|
2864
|
+
} catch (error) {
|
|
2865
|
+
}
|
|
2866
|
+
}
|
|
2867
|
+
try {
|
|
2868
|
+
const result = execute({
|
|
2869
|
+
writer: {
|
|
2870
|
+
write(part) {
|
|
2871
|
+
safeEnqueue(part);
|
|
2872
|
+
},
|
|
2873
|
+
merge(streamArg) {
|
|
2874
|
+
ongoingStreamPromises.push(
|
|
2875
|
+
(async () => {
|
|
2876
|
+
const reader = streamArg.getReader();
|
|
2877
|
+
while (true) {
|
|
2878
|
+
const { done, value } = await reader.read();
|
|
2879
|
+
if (done)
|
|
2880
|
+
break;
|
|
2881
|
+
safeEnqueue(value);
|
|
2882
|
+
}
|
|
2883
|
+
})().catch((error) => {
|
|
2884
|
+
safeEnqueue({
|
|
2885
|
+
type: "error",
|
|
2886
|
+
errorText: onError(error)
|
|
2887
|
+
});
|
|
2888
|
+
})
|
|
2889
|
+
);
|
|
2890
|
+
},
|
|
2891
|
+
onError
|
|
2892
|
+
}
|
|
2893
|
+
});
|
|
2894
|
+
if (result) {
|
|
2895
|
+
ongoingStreamPromises.push(
|
|
2896
|
+
result.catch((error) => {
|
|
2897
|
+
safeEnqueue({
|
|
2898
|
+
type: "error",
|
|
2899
|
+
errorText: onError(error)
|
|
2900
|
+
});
|
|
2901
|
+
})
|
|
2902
|
+
);
|
|
2903
|
+
}
|
|
2904
|
+
} catch (error) {
|
|
2905
|
+
safeEnqueue({
|
|
2906
|
+
type: "error",
|
|
2907
|
+
errorText: onError(error)
|
|
2908
|
+
});
|
|
2909
|
+
}
|
|
2910
|
+
const waitForStreams = new Promise(async (resolve2) => {
|
|
2911
|
+
while (ongoingStreamPromises.length > 0) {
|
|
2912
|
+
await ongoingStreamPromises.shift();
|
|
2913
|
+
}
|
|
2914
|
+
resolve2();
|
|
2915
|
+
});
|
|
2916
|
+
waitForStreams.finally(() => {
|
|
2917
|
+
try {
|
|
2918
|
+
controller.close();
|
|
2919
|
+
} catch (error) {
|
|
2920
|
+
}
|
|
2921
|
+
});
|
|
2922
|
+
return handleUIMessageStreamFinish({
|
|
2923
|
+
stream,
|
|
2924
|
+
messageId: generateId3(),
|
|
2925
|
+
originalMessages,
|
|
2926
|
+
onFinish,
|
|
2927
|
+
onError
|
|
2928
|
+
});
|
|
2929
|
+
}
|
|
8
2930
|
|
|
9
2931
|
// src/utils.ts
|
|
10
2932
|
var isDataChunkType = (chunk) => {
|
|
11
2933
|
return chunk && typeof chunk === "object" && "type" in chunk && chunk.type?.startsWith("data-");
|
|
12
2934
|
};
|
|
2935
|
+
var isMastraTextStreamChunk = (chunk) => {
|
|
2936
|
+
return chunk && typeof chunk === "object" && "type" in chunk && typeof chunk.type === "string" && [
|
|
2937
|
+
"text-start",
|
|
2938
|
+
"text-delta",
|
|
2939
|
+
"text-end",
|
|
2940
|
+
"reasoning-start",
|
|
2941
|
+
"reasoning-delta",
|
|
2942
|
+
"reasoning-end",
|
|
2943
|
+
"file",
|
|
2944
|
+
"source",
|
|
2945
|
+
"tool-input-start",
|
|
2946
|
+
"tool-input-delta",
|
|
2947
|
+
"tool-call-approval",
|
|
2948
|
+
"tool-call-suspended",
|
|
2949
|
+
"tool-call",
|
|
2950
|
+
"tool-result",
|
|
2951
|
+
"tool-error",
|
|
2952
|
+
"error",
|
|
2953
|
+
"start-step",
|
|
2954
|
+
"finish-step",
|
|
2955
|
+
"start",
|
|
2956
|
+
"finish",
|
|
2957
|
+
"abort",
|
|
2958
|
+
"tool-input-end",
|
|
2959
|
+
"object",
|
|
2960
|
+
"tripwire",
|
|
2961
|
+
"raw"
|
|
2962
|
+
].includes(chunk.type);
|
|
2963
|
+
};
|
|
13
2964
|
function safeParseErrorObject(obj) {
|
|
14
2965
|
if (typeof obj !== "object" || obj === null) {
|
|
15
2966
|
return String(obj);
|
|
@@ -32,6 +2983,12 @@ var isWorkflowExecutionDataChunkType = (chunk) => {
|
|
|
32
2983
|
};
|
|
33
2984
|
|
|
34
2985
|
// src/helpers.ts
|
|
2986
|
+
function toAISDKFinishReason(reason) {
|
|
2987
|
+
if (reason === "tripwire" || reason === "retry") {
|
|
2988
|
+
return "other";
|
|
2989
|
+
}
|
|
2990
|
+
return reason;
|
|
2991
|
+
}
|
|
35
2992
|
function convertMastraChunkToAISDKv5({
|
|
36
2993
|
chunk,
|
|
37
2994
|
mode = "stream"
|
|
@@ -39,7 +2996,9 @@ function convertMastraChunkToAISDKv5({
|
|
|
39
2996
|
switch (chunk.type) {
|
|
40
2997
|
case "start":
|
|
41
2998
|
return {
|
|
42
|
-
type: "start"
|
|
2999
|
+
type: "start",
|
|
3000
|
+
// Preserve messageId from the payload so it can be sent to useChat
|
|
3001
|
+
...chunk.payload?.messageId ? { messageId: chunk.payload.messageId } : {}
|
|
43
3002
|
};
|
|
44
3003
|
case "step-start":
|
|
45
3004
|
const { messageId: _messageId, ...rest } = chunk.payload;
|
|
@@ -56,7 +3015,8 @@ function convertMastraChunkToAISDKv5({
|
|
|
56
3015
|
case "finish": {
|
|
57
3016
|
return {
|
|
58
3017
|
type: "finish",
|
|
59
|
-
finishReason: chunk.payload.stepResult.reason,
|
|
3018
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
|
|
3019
|
+
// Cast needed: Mastra's LanguageModelUsage has optional properties, AI SDK has required-but-nullable
|
|
60
3020
|
totalUsage: chunk.payload.output.usage
|
|
61
3021
|
};
|
|
62
3022
|
}
|
|
@@ -140,6 +3100,28 @@ function convertMastraChunkToAISDKv5({
|
|
|
140
3100
|
toolName: chunk.payload.toolName,
|
|
141
3101
|
input: chunk.payload.args
|
|
142
3102
|
};
|
|
3103
|
+
case "tool-call-approval":
|
|
3104
|
+
return {
|
|
3105
|
+
type: "data-tool-call-approval",
|
|
3106
|
+
id: chunk.payload.toolCallId,
|
|
3107
|
+
data: {
|
|
3108
|
+
runId: chunk.runId,
|
|
3109
|
+
toolCallId: chunk.payload.toolCallId,
|
|
3110
|
+
toolName: chunk.payload.toolName,
|
|
3111
|
+
args: chunk.payload.args
|
|
3112
|
+
}
|
|
3113
|
+
};
|
|
3114
|
+
case "tool-call-suspended":
|
|
3115
|
+
return {
|
|
3116
|
+
type: "data-tool-call-suspended",
|
|
3117
|
+
id: chunk.payload.toolCallId,
|
|
3118
|
+
data: {
|
|
3119
|
+
runId: chunk.runId,
|
|
3120
|
+
toolCallId: chunk.payload.toolCallId,
|
|
3121
|
+
toolName: chunk.payload.toolName,
|
|
3122
|
+
suspendPayload: chunk.payload.suspendPayload
|
|
3123
|
+
}
|
|
3124
|
+
};
|
|
143
3125
|
case "tool-call-input-streaming-start":
|
|
144
3126
|
return {
|
|
145
3127
|
type: "tool-input-start",
|
|
@@ -173,7 +3155,7 @@ function convertMastraChunkToAISDKv5({
|
|
|
173
3155
|
...rest2
|
|
174
3156
|
},
|
|
175
3157
|
usage: chunk.payload.output.usage,
|
|
176
|
-
finishReason: chunk.payload.stepResult.reason,
|
|
3158
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
|
|
177
3159
|
providerMetadata
|
|
178
3160
|
};
|
|
179
3161
|
}
|
|
@@ -230,6 +3212,16 @@ function convertMastraChunkToAISDKv5({
|
|
|
230
3212
|
type: "object",
|
|
231
3213
|
object: chunk.object
|
|
232
3214
|
};
|
|
3215
|
+
case "tripwire":
|
|
3216
|
+
return {
|
|
3217
|
+
type: "data-tripwire",
|
|
3218
|
+
data: {
|
|
3219
|
+
reason: chunk.payload.reason,
|
|
3220
|
+
retry: chunk.payload.retry,
|
|
3221
|
+
metadata: chunk.payload.metadata,
|
|
3222
|
+
processorId: chunk.payload.processorId
|
|
3223
|
+
}
|
|
3224
|
+
};
|
|
233
3225
|
default:
|
|
234
3226
|
if (chunk.type && "payload" in chunk && chunk.payload) {
|
|
235
3227
|
return {
|
|
@@ -285,6 +3277,14 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
285
3277
|
};
|
|
286
3278
|
}
|
|
287
3279
|
case "reasoning-delta": {
|
|
3280
|
+
if (sendReasoning) {
|
|
3281
|
+
return {
|
|
3282
|
+
type: "reasoning-delta",
|
|
3283
|
+
id: part.id,
|
|
3284
|
+
delta: part.text,
|
|
3285
|
+
...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
|
|
3286
|
+
};
|
|
3287
|
+
}
|
|
288
3288
|
return;
|
|
289
3289
|
}
|
|
290
3290
|
case "reasoning-end": {
|
|
@@ -302,6 +3302,25 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
302
3302
|
};
|
|
303
3303
|
}
|
|
304
3304
|
case "source": {
|
|
3305
|
+
if (sendSources && part.sourceType === "url") {
|
|
3306
|
+
return {
|
|
3307
|
+
type: "source-url",
|
|
3308
|
+
sourceId: part.id,
|
|
3309
|
+
url: part.url,
|
|
3310
|
+
title: part.title,
|
|
3311
|
+
...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
|
|
3312
|
+
};
|
|
3313
|
+
}
|
|
3314
|
+
if (sendSources && part.sourceType === "document") {
|
|
3315
|
+
return {
|
|
3316
|
+
type: "source-document",
|
|
3317
|
+
sourceId: part.id,
|
|
3318
|
+
mediaType: part.mediaType,
|
|
3319
|
+
title: part.title,
|
|
3320
|
+
filename: part.filename,
|
|
3321
|
+
...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
|
|
3322
|
+
};
|
|
3323
|
+
}
|
|
305
3324
|
return;
|
|
306
3325
|
}
|
|
307
3326
|
case "tool-input-start": {
|
|
@@ -359,6 +3378,14 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
359
3378
|
toolCallId: part.toolCallId,
|
|
360
3379
|
payload: part.output
|
|
361
3380
|
};
|
|
3381
|
+
} else if (isDataChunkType(part.output)) {
|
|
3382
|
+
if (!("data" in part.output)) {
|
|
3383
|
+
throw new Error(
|
|
3384
|
+
`UI Messages require a data property when using data- prefixed chunks
|
|
3385
|
+
${JSON.stringify(part)}`
|
|
3386
|
+
);
|
|
3387
|
+
}
|
|
3388
|
+
return part.output;
|
|
362
3389
|
}
|
|
363
3390
|
return;
|
|
364
3391
|
}
|
|
@@ -384,21 +3411,24 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
384
3411
|
return { type: "finish-step" };
|
|
385
3412
|
}
|
|
386
3413
|
case "start": {
|
|
387
|
-
{
|
|
3414
|
+
if (sendStart) {
|
|
3415
|
+
const messageId = ("messageId" in part ? part.messageId : void 0) || responseMessageId;
|
|
388
3416
|
return {
|
|
389
3417
|
type: "start",
|
|
390
3418
|
...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},
|
|
391
|
-
...
|
|
3419
|
+
...messageId != null ? { messageId } : {}
|
|
392
3420
|
};
|
|
393
3421
|
}
|
|
3422
|
+
return;
|
|
394
3423
|
}
|
|
395
3424
|
case "finish": {
|
|
396
|
-
{
|
|
3425
|
+
if (sendFinish) {
|
|
397
3426
|
return {
|
|
398
3427
|
type: "finish",
|
|
399
3428
|
...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}
|
|
400
3429
|
};
|
|
401
3430
|
}
|
|
3431
|
+
return;
|
|
402
3432
|
}
|
|
403
3433
|
case "abort": {
|
|
404
3434
|
return part;
|
|
@@ -425,7 +3455,10 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
425
3455
|
}
|
|
426
3456
|
|
|
427
3457
|
// src/transformers.ts
|
|
428
|
-
|
|
3458
|
+
var PRIMITIVE_CACHE_SYMBOL = Symbol("primitive-cache");
|
|
3459
|
+
function WorkflowStreamToAISDKTransformer({
|
|
3460
|
+
includeTextStreamParts
|
|
3461
|
+
} = {}) {
|
|
429
3462
|
const bufferedWorkflows = /* @__PURE__ */ new Map();
|
|
430
3463
|
return new TransformStream({
|
|
431
3464
|
start(controller) {
|
|
@@ -439,7 +3472,7 @@ function WorkflowStreamToAISDKTransformer() {
|
|
|
439
3472
|
});
|
|
440
3473
|
},
|
|
441
3474
|
transform(chunk, controller) {
|
|
442
|
-
const transformed = transformWorkflow(chunk, bufferedWorkflows);
|
|
3475
|
+
const transformed = transformWorkflow(chunk, bufferedWorkflows, false, includeTextStreamParts);
|
|
443
3476
|
if (transformed) controller.enqueue(transformed);
|
|
444
3477
|
}
|
|
445
3478
|
});
|
|
@@ -463,20 +3496,37 @@ function AgentNetworkToAISDKTransformer() {
|
|
|
463
3496
|
}
|
|
464
3497
|
});
|
|
465
3498
|
}
|
|
466
|
-
function AgentStreamToAISDKTransformer(
|
|
3499
|
+
function AgentStreamToAISDKTransformer({
|
|
3500
|
+
lastMessageId,
|
|
3501
|
+
sendStart,
|
|
3502
|
+
sendFinish,
|
|
3503
|
+
sendReasoning,
|
|
3504
|
+
sendSources,
|
|
3505
|
+
messageMetadata,
|
|
3506
|
+
onError
|
|
3507
|
+
}) {
|
|
467
3508
|
let bufferedSteps = /* @__PURE__ */ new Map();
|
|
3509
|
+
let tripwireOccurred = false;
|
|
3510
|
+
let finishEventSent = false;
|
|
468
3511
|
return new TransformStream({
|
|
469
3512
|
transform(chunk, controller) {
|
|
3513
|
+
if (chunk.type === "tripwire") {
|
|
3514
|
+
tripwireOccurred = true;
|
|
3515
|
+
}
|
|
3516
|
+
if (chunk.type === "finish") {
|
|
3517
|
+
finishEventSent = true;
|
|
3518
|
+
}
|
|
470
3519
|
const part = convertMastraChunkToAISDKv5({ chunk, mode: "stream" });
|
|
471
3520
|
const transformedChunk = convertFullStreamChunkToUIMessageStream({
|
|
472
3521
|
part,
|
|
473
|
-
sendReasoning
|
|
474
|
-
sendSources
|
|
475
|
-
|
|
476
|
-
|
|
3522
|
+
sendReasoning,
|
|
3523
|
+
sendSources,
|
|
3524
|
+
messageMetadataValue: messageMetadata?.({ part }),
|
|
3525
|
+
sendStart,
|
|
3526
|
+
sendFinish,
|
|
477
3527
|
responseMessageId: lastMessageId,
|
|
478
3528
|
onError(error) {
|
|
479
|
-
return safeParseErrorObject(error);
|
|
3529
|
+
return onError ? onError(error) : safeParseErrorObject(error);
|
|
480
3530
|
}
|
|
481
3531
|
});
|
|
482
3532
|
if (transformedChunk) {
|
|
@@ -496,6 +3546,14 @@ function AgentStreamToAISDKTransformer(lastMessageId) {
|
|
|
496
3546
|
controller.enqueue(transformedChunk);
|
|
497
3547
|
}
|
|
498
3548
|
}
|
|
3549
|
+
},
|
|
3550
|
+
flush(controller) {
|
|
3551
|
+
if (tripwireOccurred && !finishEventSent && sendFinish) {
|
|
3552
|
+
controller.enqueue({
|
|
3553
|
+
type: "finish",
|
|
3554
|
+
finishReason: "other"
|
|
3555
|
+
});
|
|
3556
|
+
}
|
|
499
3557
|
}
|
|
500
3558
|
});
|
|
501
3559
|
}
|
|
@@ -635,7 +3693,7 @@ function transformAgent(payload, bufferedSteps) {
|
|
|
635
3693
|
}
|
|
636
3694
|
return null;
|
|
637
3695
|
}
|
|
638
|
-
function transformWorkflow(payload, bufferedWorkflows, isNested) {
|
|
3696
|
+
function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStreamParts) {
|
|
639
3697
|
switch (payload.type) {
|
|
640
3698
|
case "workflow-start":
|
|
641
3699
|
bufferedWorkflows.set(payload.runId, {
|
|
@@ -728,6 +3786,29 @@ function transformWorkflow(payload, bufferedWorkflows, isNested) {
|
|
|
728
3786
|
}
|
|
729
3787
|
};
|
|
730
3788
|
}
|
|
3789
|
+
case "workflow-step-output": {
|
|
3790
|
+
const output = payload.payload.output;
|
|
3791
|
+
if (includeTextStreamParts && output && isMastraTextStreamChunk(output)) {
|
|
3792
|
+
const part = convertMastraChunkToAISDKv5({ chunk: output, mode: "stream" });
|
|
3793
|
+
const transformedChunk = convertFullStreamChunkToUIMessageStream({
|
|
3794
|
+
part,
|
|
3795
|
+
onError(error) {
|
|
3796
|
+
return safeParseErrorObject(error);
|
|
3797
|
+
}
|
|
3798
|
+
});
|
|
3799
|
+
return transformedChunk;
|
|
3800
|
+
}
|
|
3801
|
+
if (output && isDataChunkType(output)) {
|
|
3802
|
+
if (!("data" in output)) {
|
|
3803
|
+
throw new Error(
|
|
3804
|
+
`UI Messages require a data property when using data- prefixed chunks
|
|
3805
|
+
${JSON.stringify(output)}`
|
|
3806
|
+
);
|
|
3807
|
+
}
|
|
3808
|
+
return output;
|
|
3809
|
+
}
|
|
3810
|
+
return null;
|
|
3811
|
+
}
|
|
731
3812
|
default: {
|
|
732
3813
|
if (isDataChunkType(payload)) {
|
|
733
3814
|
if (!("data" in payload)) {
|
|
@@ -747,12 +3828,29 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
747
3828
|
case "routing-agent-start": {
|
|
748
3829
|
if (!bufferedNetworks.has(payload.runId)) {
|
|
749
3830
|
bufferedNetworks.set(payload.runId, {
|
|
750
|
-
name: payload.payload.
|
|
3831
|
+
name: payload.payload.networkId,
|
|
751
3832
|
steps: [],
|
|
752
3833
|
usage: null,
|
|
753
3834
|
output: null
|
|
754
3835
|
});
|
|
755
3836
|
}
|
|
3837
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
3838
|
+
current.steps.push({
|
|
3839
|
+
id: payload.payload.runId,
|
|
3840
|
+
name: payload.payload.agentId,
|
|
3841
|
+
status: "running",
|
|
3842
|
+
iteration: payload.payload.inputData.iteration,
|
|
3843
|
+
input: {
|
|
3844
|
+
task: payload.payload.inputData.task,
|
|
3845
|
+
threadId: payload.payload.inputData.threadId,
|
|
3846
|
+
threadResourceId: payload.payload.inputData.threadResourceId
|
|
3847
|
+
},
|
|
3848
|
+
output: "",
|
|
3849
|
+
task: null,
|
|
3850
|
+
suspendPayload: null,
|
|
3851
|
+
resumePayload: null,
|
|
3852
|
+
[PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
|
|
3853
|
+
});
|
|
756
3854
|
return {
|
|
757
3855
|
type: isNested ? "data-tool-network" : "data-network",
|
|
758
3856
|
id: payload.runId,
|
|
@@ -783,14 +3881,19 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
783
3881
|
};
|
|
784
3882
|
}
|
|
785
3883
|
case "agent-execution-start": {
|
|
786
|
-
const current = bufferedNetworks.get(payload.runId)
|
|
3884
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
3885
|
+
if (!current) return null;
|
|
787
3886
|
current.steps.push({
|
|
3887
|
+
id: payload.payload.runId,
|
|
788
3888
|
name: payload.payload.agentId,
|
|
789
3889
|
status: "running",
|
|
790
|
-
|
|
3890
|
+
iteration: payload.payload.args?.iteration ?? 0,
|
|
3891
|
+
input: { prompt: payload.payload.args?.prompt ?? "" },
|
|
791
3892
|
output: null,
|
|
3893
|
+
task: null,
|
|
792
3894
|
suspendPayload: null,
|
|
793
|
-
resumePayload: null
|
|
3895
|
+
resumePayload: null,
|
|
3896
|
+
[PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
|
|
794
3897
|
});
|
|
795
3898
|
bufferedNetworks.set(payload.runId, current);
|
|
796
3899
|
return {
|
|
@@ -803,14 +3906,19 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
803
3906
|
};
|
|
804
3907
|
}
|
|
805
3908
|
case "workflow-execution-start": {
|
|
806
|
-
const current = bufferedNetworks.get(payload.runId)
|
|
3909
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
3910
|
+
if (!current) return null;
|
|
807
3911
|
current.steps.push({
|
|
808
|
-
|
|
3912
|
+
id: payload.payload.runId,
|
|
3913
|
+
name: payload.payload.workflowId,
|
|
809
3914
|
status: "running",
|
|
810
|
-
|
|
3915
|
+
iteration: payload.payload.args?.iteration ?? 0,
|
|
3916
|
+
input: { prompt: payload.payload.args?.prompt ?? "" },
|
|
811
3917
|
output: null,
|
|
3918
|
+
task: null,
|
|
812
3919
|
suspendPayload: null,
|
|
813
|
-
resumePayload: null
|
|
3920
|
+
resumePayload: null,
|
|
3921
|
+
[PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
|
|
814
3922
|
});
|
|
815
3923
|
bufferedNetworks.set(payload.runId, current);
|
|
816
3924
|
return {
|
|
@@ -823,14 +3931,21 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
823
3931
|
};
|
|
824
3932
|
}
|
|
825
3933
|
case "tool-execution-start": {
|
|
826
|
-
const current = bufferedNetworks.get(payload.runId)
|
|
3934
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
3935
|
+
if (!current) return null;
|
|
827
3936
|
current.steps.push({
|
|
3937
|
+
id: payload.payload.args.toolCallId,
|
|
828
3938
|
name: payload.payload.args?.toolName,
|
|
829
3939
|
status: "running",
|
|
3940
|
+
iteration: payload.payload.args?.iteration ? Number(payload.payload.args.iteration) : 0,
|
|
3941
|
+
task: {
|
|
3942
|
+
id: payload.payload.args?.toolName
|
|
3943
|
+
},
|
|
830
3944
|
input: payload.payload.args?.args || null,
|
|
831
3945
|
output: null,
|
|
832
3946
|
suspendPayload: null,
|
|
833
|
-
resumePayload: null
|
|
3947
|
+
resumePayload: null,
|
|
3948
|
+
[PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
|
|
834
3949
|
});
|
|
835
3950
|
bufferedNetworks.set(payload.runId, current);
|
|
836
3951
|
return {
|
|
@@ -845,14 +3960,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
845
3960
|
case "agent-execution-end": {
|
|
846
3961
|
const current = bufferedNetworks.get(payload.runId);
|
|
847
3962
|
if (!current) return null;
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
});
|
|
3963
|
+
const stepId = payload.payload.runId;
|
|
3964
|
+
const step = current.steps.find((step2) => step2.id === stepId);
|
|
3965
|
+
if (!step) {
|
|
3966
|
+
return null;
|
|
3967
|
+
}
|
|
3968
|
+
step.status = "success";
|
|
3969
|
+
step.output = payload.payload.result;
|
|
856
3970
|
return {
|
|
857
3971
|
type: isNested ? "data-tool-network" : "data-network",
|
|
858
3972
|
id: payload.runId,
|
|
@@ -867,14 +3981,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
867
3981
|
case "tool-execution-end": {
|
|
868
3982
|
const current = bufferedNetworks.get(payload.runId);
|
|
869
3983
|
if (!current) return null;
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
});
|
|
3984
|
+
const stepId = payload.payload.toolCallId;
|
|
3985
|
+
const step = current.steps.find((step2) => step2.id === stepId);
|
|
3986
|
+
if (!step) {
|
|
3987
|
+
return null;
|
|
3988
|
+
}
|
|
3989
|
+
step.status = "success";
|
|
3990
|
+
step.output = payload.payload.result;
|
|
878
3991
|
return {
|
|
879
3992
|
type: isNested ? "data-tool-network" : "data-network",
|
|
880
3993
|
id: payload.runId,
|
|
@@ -887,15 +4000,14 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
887
4000
|
}
|
|
888
4001
|
case "workflow-execution-end": {
|
|
889
4002
|
const current = bufferedNetworks.get(payload.runId);
|
|
890
|
-
if (!current) return null;
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
});
|
|
4003
|
+
if (!current) return null;
|
|
4004
|
+
const stepId = payload.payload.runId;
|
|
4005
|
+
const step = current.steps.find((step2) => step2.id === stepId);
|
|
4006
|
+
if (!step) {
|
|
4007
|
+
return null;
|
|
4008
|
+
}
|
|
4009
|
+
step.status = "success";
|
|
4010
|
+
step.output = payload.payload.result;
|
|
899
4011
|
return {
|
|
900
4012
|
type: isNested ? "data-tool-network" : "data-network",
|
|
901
4013
|
id: payload.runId,
|
|
@@ -910,12 +4022,24 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
910
4022
|
case "routing-agent-end": {
|
|
911
4023
|
const current = bufferedNetworks.get(payload.runId);
|
|
912
4024
|
if (!current) return null;
|
|
4025
|
+
const stepId = payload.payload.runId;
|
|
4026
|
+
const step = current.steps.find((step2) => step2.id === stepId);
|
|
4027
|
+
if (!step) {
|
|
4028
|
+
return null;
|
|
4029
|
+
}
|
|
4030
|
+
step.status = "success";
|
|
4031
|
+
step.task = {
|
|
4032
|
+
id: payload.payload.primitiveId,
|
|
4033
|
+
type: payload.payload.primitiveType,
|
|
4034
|
+
name: payload.payload.task,
|
|
4035
|
+
reason: payload.payload.selectionReason
|
|
4036
|
+
};
|
|
4037
|
+
step.output = payload.payload.result;
|
|
913
4038
|
return {
|
|
914
4039
|
type: isNested ? "data-tool-network" : "data-network",
|
|
915
4040
|
id: payload.runId,
|
|
916
4041
|
data: {
|
|
917
4042
|
...current,
|
|
918
|
-
status: "finished",
|
|
919
4043
|
usage: payload.payload?.usage ?? current.usage,
|
|
920
4044
|
output: payload.payload?.result ?? current.output
|
|
921
4045
|
}
|
|
@@ -949,32 +4073,86 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
949
4073
|
};
|
|
950
4074
|
}
|
|
951
4075
|
default: {
|
|
952
|
-
if (
|
|
953
|
-
if (!("data" in payload)) {
|
|
4076
|
+
if (isAgentExecutionDataChunkType(payload)) {
|
|
4077
|
+
if (!("data" in payload.payload)) {
|
|
954
4078
|
throw new Error(
|
|
955
4079
|
`UI Messages require a data property when using data- prefixed chunks
|
|
956
4080
|
${JSON.stringify(payload)}`
|
|
957
4081
|
);
|
|
958
4082
|
}
|
|
959
|
-
|
|
4083
|
+
const { type, data } = payload.payload;
|
|
4084
|
+
return { type, data };
|
|
960
4085
|
}
|
|
961
|
-
if (
|
|
4086
|
+
if (isWorkflowExecutionDataChunkType(payload)) {
|
|
962
4087
|
if (!("data" in payload.payload)) {
|
|
963
4088
|
throw new Error(
|
|
964
4089
|
`UI Messages require a data property when using data- prefixed chunks
|
|
965
4090
|
${JSON.stringify(payload)}`
|
|
966
4091
|
);
|
|
967
4092
|
}
|
|
968
|
-
|
|
4093
|
+
const { type, data } = payload.payload;
|
|
4094
|
+
return { type, data };
|
|
969
4095
|
}
|
|
970
|
-
if (
|
|
971
|
-
|
|
4096
|
+
if (payload.type.startsWith("agent-execution-event-")) {
|
|
4097
|
+
const stepId = payload.payload.runId;
|
|
4098
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
4099
|
+
if (!current) return null;
|
|
4100
|
+
const step = current.steps.find((step2) => step2.id === stepId);
|
|
4101
|
+
if (!step) {
|
|
4102
|
+
return null;
|
|
4103
|
+
}
|
|
4104
|
+
step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
|
|
4105
|
+
const result = transformAgent(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
|
|
4106
|
+
if (result) {
|
|
4107
|
+
const { request, response, ...data } = result.data;
|
|
4108
|
+
step.task = data;
|
|
4109
|
+
}
|
|
4110
|
+
bufferedNetworks.set(payload.runId, current);
|
|
4111
|
+
return {
|
|
4112
|
+
type: isNested ? "data-tool-network" : "data-network",
|
|
4113
|
+
id: payload.runId,
|
|
4114
|
+
data: {
|
|
4115
|
+
...current,
|
|
4116
|
+
status: "running"
|
|
4117
|
+
}
|
|
4118
|
+
};
|
|
4119
|
+
}
|
|
4120
|
+
if (payload.type.startsWith("workflow-execution-event-")) {
|
|
4121
|
+
const stepId = payload.payload.runId;
|
|
4122
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
4123
|
+
if (!current) return null;
|
|
4124
|
+
const step = current.steps.find((step2) => step2.id === stepId);
|
|
4125
|
+
if (!step) {
|
|
4126
|
+
return null;
|
|
4127
|
+
}
|
|
4128
|
+
step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
|
|
4129
|
+
const result = transformWorkflow(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
|
|
4130
|
+
if (result && "data" in result) {
|
|
4131
|
+
const data = result.data;
|
|
4132
|
+
step.task = data;
|
|
4133
|
+
if (data.name && step.task) {
|
|
4134
|
+
step.task.id = data.name;
|
|
4135
|
+
}
|
|
4136
|
+
}
|
|
4137
|
+
bufferedNetworks.set(payload.runId, current);
|
|
4138
|
+
return {
|
|
4139
|
+
type: isNested ? "data-tool-network" : "data-network",
|
|
4140
|
+
id: payload.runId,
|
|
4141
|
+
data: {
|
|
4142
|
+
...current,
|
|
4143
|
+
status: "running"
|
|
4144
|
+
}
|
|
4145
|
+
};
|
|
4146
|
+
}
|
|
4147
|
+
if (isDataChunkType(payload)) {
|
|
4148
|
+
if (!("data" in payload)) {
|
|
972
4149
|
throw new Error(
|
|
973
4150
|
`UI Messages require a data property when using data- prefixed chunks
|
|
974
4151
|
${JSON.stringify(payload)}`
|
|
975
4152
|
);
|
|
976
4153
|
}
|
|
977
|
-
|
|
4154
|
+
const { type, data } = payload;
|
|
4155
|
+
return { type, data };
|
|
978
4156
|
}
|
|
979
4157
|
return null;
|
|
980
4158
|
}
|
|
@@ -982,23 +4160,95 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
982
4160
|
}
|
|
983
4161
|
|
|
984
4162
|
// src/convert-streams.ts
|
|
985
|
-
function toAISdkV5Stream(stream, options = {
|
|
4163
|
+
function toAISdkV5Stream(stream, options = {
|
|
4164
|
+
from: "agent",
|
|
4165
|
+
sendStart: true,
|
|
4166
|
+
sendFinish: true
|
|
4167
|
+
}) {
|
|
986
4168
|
const from = options?.from;
|
|
987
4169
|
if (from === "workflow") {
|
|
988
|
-
|
|
4170
|
+
const includeTextStreamParts = options?.includeTextStreamParts ?? true;
|
|
4171
|
+
return stream.pipeThrough(
|
|
4172
|
+
WorkflowStreamToAISDKTransformer({ includeTextStreamParts })
|
|
4173
|
+
);
|
|
989
4174
|
}
|
|
990
4175
|
if (from === "network") {
|
|
991
4176
|
return stream.pipeThrough(AgentNetworkToAISDKTransformer());
|
|
992
4177
|
}
|
|
993
4178
|
const agentReadable = "fullStream" in stream ? stream.fullStream : stream;
|
|
994
|
-
return agentReadable.pipeThrough(
|
|
4179
|
+
return agentReadable.pipeThrough(
|
|
4180
|
+
AgentStreamToAISDKTransformer({
|
|
4181
|
+
lastMessageId: options?.lastMessageId,
|
|
4182
|
+
sendStart: options?.sendStart,
|
|
4183
|
+
sendFinish: options?.sendFinish,
|
|
4184
|
+
sendReasoning: options?.sendReasoning,
|
|
4185
|
+
sendSources: options?.sendSources,
|
|
4186
|
+
messageMetadata: options?.messageMetadata,
|
|
4187
|
+
onError: options?.onError
|
|
4188
|
+
})
|
|
4189
|
+
);
|
|
995
4190
|
}
|
|
996
4191
|
|
|
997
4192
|
// src/chat-route.ts
|
|
4193
|
+
async function handleChatStream({
|
|
4194
|
+
mastra,
|
|
4195
|
+
agentId,
|
|
4196
|
+
params,
|
|
4197
|
+
defaultOptions: defaultOptions2,
|
|
4198
|
+
sendStart = true,
|
|
4199
|
+
sendFinish = true,
|
|
4200
|
+
sendReasoning = false,
|
|
4201
|
+
sendSources = false
|
|
4202
|
+
}) {
|
|
4203
|
+
const { messages, resumeData, runId, requestContext, ...rest } = params;
|
|
4204
|
+
if (resumeData && !runId) {
|
|
4205
|
+
throw new Error("runId is required when resumeData is provided");
|
|
4206
|
+
}
|
|
4207
|
+
const agentObj = mastra.getAgentById(agentId);
|
|
4208
|
+
if (!agentObj) {
|
|
4209
|
+
throw new Error(`Agent ${agentId} not found`);
|
|
4210
|
+
}
|
|
4211
|
+
if (!Array.isArray(messages)) {
|
|
4212
|
+
throw new Error("Messages must be an array of UIMessage objects");
|
|
4213
|
+
}
|
|
4214
|
+
const mergedOptions = {
|
|
4215
|
+
...defaultOptions2,
|
|
4216
|
+
...rest,
|
|
4217
|
+
...runId && { runId },
|
|
4218
|
+
requestContext: requestContext || defaultOptions2?.requestContext
|
|
4219
|
+
};
|
|
4220
|
+
const result = resumeData ? await agentObj.resumeStream(resumeData, mergedOptions) : await agentObj.stream(messages, mergedOptions);
|
|
4221
|
+
let lastMessageId;
|
|
4222
|
+
if (messages.length) {
|
|
4223
|
+
const lastMessage = messages[messages.length - 1];
|
|
4224
|
+
if (lastMessage?.role === "assistant") {
|
|
4225
|
+
lastMessageId = lastMessage.id;
|
|
4226
|
+
}
|
|
4227
|
+
}
|
|
4228
|
+
return createUIMessageStream({
|
|
4229
|
+
originalMessages: messages,
|
|
4230
|
+
execute: async ({ writer }) => {
|
|
4231
|
+
for await (const part of toAISdkV5Stream(result, {
|
|
4232
|
+
from: "agent",
|
|
4233
|
+
lastMessageId,
|
|
4234
|
+
sendStart,
|
|
4235
|
+
sendFinish,
|
|
4236
|
+
sendReasoning,
|
|
4237
|
+
sendSources
|
|
4238
|
+
})) {
|
|
4239
|
+
writer.write(part);
|
|
4240
|
+
}
|
|
4241
|
+
}
|
|
4242
|
+
});
|
|
4243
|
+
}
|
|
998
4244
|
function chatRoute({
|
|
999
4245
|
path = "/chat/:agentId",
|
|
1000
4246
|
agent,
|
|
1001
|
-
defaultOptions
|
|
4247
|
+
defaultOptions: defaultOptions2,
|
|
4248
|
+
sendStart = true,
|
|
4249
|
+
sendFinish = true,
|
|
4250
|
+
sendReasoning = false,
|
|
4251
|
+
sendSources = false
|
|
1002
4252
|
}) {
|
|
1003
4253
|
if (!agent && !path.includes("/:agentId")) {
|
|
1004
4254
|
throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
|
|
@@ -1027,6 +4277,14 @@ function chatRoute({
|
|
|
1027
4277
|
schema: {
|
|
1028
4278
|
type: "object",
|
|
1029
4279
|
properties: {
|
|
4280
|
+
resumeData: {
|
|
4281
|
+
type: "object",
|
|
4282
|
+
description: "Resume data for the agent"
|
|
4283
|
+
},
|
|
4284
|
+
runId: {
|
|
4285
|
+
type: "string",
|
|
4286
|
+
description: "The run ID required when resuming an agent execution"
|
|
4287
|
+
},
|
|
1030
4288
|
messages: {
|
|
1031
4289
|
type: "array",
|
|
1032
4290
|
description: "Array of messages in the conversation",
|
|
@@ -1097,9 +4355,9 @@ function chatRoute({
|
|
|
1097
4355
|
}
|
|
1098
4356
|
},
|
|
1099
4357
|
handler: async (c) => {
|
|
1100
|
-
const
|
|
4358
|
+
const params = await c.req.json();
|
|
1101
4359
|
const mastra = c.get("mastra");
|
|
1102
|
-
const
|
|
4360
|
+
const contextRequestContext = c.get("requestContext");
|
|
1103
4361
|
let agentToUse = agent;
|
|
1104
4362
|
if (!agent) {
|
|
1105
4363
|
const agentId = c.req.param("agentId");
|
|
@@ -1110,42 +4368,57 @@ function chatRoute({
|
|
|
1110
4368
|
`Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
|
|
1111
4369
|
);
|
|
1112
4370
|
}
|
|
1113
|
-
|
|
1114
|
-
|
|
4371
|
+
const effectiveRequestContext = contextRequestContext || defaultOptions2?.requestContext || params.requestContext;
|
|
4372
|
+
if (contextRequestContext && defaultOptions2?.requestContext || contextRequestContext && params.requestContext || defaultOptions2?.requestContext && params.requestContext) {
|
|
4373
|
+
mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
|
|
1115
4374
|
}
|
|
1116
4375
|
if (!agentToUse) {
|
|
1117
4376
|
throw new Error("Agent ID is required");
|
|
1118
4377
|
}
|
|
1119
|
-
const
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
}
|
|
1132
|
-
const uiMessageStream = ai.createUIMessageStream({
|
|
1133
|
-
originalMessages: messages,
|
|
1134
|
-
execute: async ({ writer }) => {
|
|
1135
|
-
for await (const part of toAISdkV5Stream(result, { from: "agent", lastMessageId })) {
|
|
1136
|
-
writer.write(part);
|
|
1137
|
-
}
|
|
1138
|
-
}
|
|
4378
|
+
const uiMessageStream = await handleChatStream({
|
|
4379
|
+
mastra,
|
|
4380
|
+
agentId: agentToUse,
|
|
4381
|
+
params: {
|
|
4382
|
+
...params,
|
|
4383
|
+
requestContext: effectiveRequestContext
|
|
4384
|
+
},
|
|
4385
|
+
defaultOptions: defaultOptions2,
|
|
4386
|
+
sendStart,
|
|
4387
|
+
sendFinish,
|
|
4388
|
+
sendReasoning,
|
|
4389
|
+
sendSources
|
|
1139
4390
|
});
|
|
1140
|
-
return
|
|
4391
|
+
return createUIMessageStreamResponse({
|
|
1141
4392
|
stream: uiMessageStream
|
|
1142
4393
|
});
|
|
1143
4394
|
}
|
|
1144
4395
|
});
|
|
1145
4396
|
}
|
|
4397
|
+
async function handleWorkflowStream({
|
|
4398
|
+
mastra,
|
|
4399
|
+
workflowId,
|
|
4400
|
+
params,
|
|
4401
|
+
includeTextStreamParts = true
|
|
4402
|
+
}) {
|
|
4403
|
+
const { runId, resourceId, inputData, resumeData, requestContext, ...rest } = params;
|
|
4404
|
+
const workflowObj = mastra.getWorkflowById(workflowId);
|
|
4405
|
+
if (!workflowObj) {
|
|
4406
|
+
throw new Error(`Workflow ${workflowId} not found`);
|
|
4407
|
+
}
|
|
4408
|
+
const run = await workflowObj.createRun({ runId, resourceId, ...rest });
|
|
4409
|
+
const stream = resumeData ? run.resumeStream({ resumeData, ...rest, requestContext }) : run.stream({ inputData, ...rest, requestContext });
|
|
4410
|
+
return createUIMessageStream({
|
|
4411
|
+
execute: async ({ writer }) => {
|
|
4412
|
+
for await (const part of toAISdkV5Stream(stream, { from: "workflow", includeTextStreamParts })) {
|
|
4413
|
+
writer.write(part);
|
|
4414
|
+
}
|
|
4415
|
+
}
|
|
4416
|
+
});
|
|
4417
|
+
}
|
|
1146
4418
|
function workflowRoute({
|
|
1147
4419
|
path = "/api/workflows/:workflowId/stream",
|
|
1148
|
-
workflow
|
|
4420
|
+
workflow,
|
|
4421
|
+
includeTextStreamParts = true
|
|
1149
4422
|
}) {
|
|
1150
4423
|
if (!workflow && !path.includes("/:workflowId")) {
|
|
1151
4424
|
throw new Error("Path must include :workflowId to route to the correct workflow or pass the workflow explicitly");
|
|
@@ -1172,9 +4445,13 @@ function workflowRoute({
|
|
|
1172
4445
|
schema: {
|
|
1173
4446
|
type: "object",
|
|
1174
4447
|
properties: {
|
|
4448
|
+
runId: { type: "string" },
|
|
4449
|
+
resourceId: { type: "string" },
|
|
1175
4450
|
inputData: { type: "object", additionalProperties: true },
|
|
4451
|
+
resumeData: { type: "object", additionalProperties: true },
|
|
1176
4452
|
requestContext: { type: "object", additionalProperties: true },
|
|
1177
|
-
tracingOptions: { type: "object", additionalProperties: true }
|
|
4453
|
+
tracingOptions: { type: "object", additionalProperties: true },
|
|
4454
|
+
step: { type: "string" }
|
|
1178
4455
|
}
|
|
1179
4456
|
}
|
|
1180
4457
|
}
|
|
@@ -1192,8 +4469,9 @@ function workflowRoute({
|
|
|
1192
4469
|
}
|
|
1193
4470
|
},
|
|
1194
4471
|
handler: async (c) => {
|
|
1195
|
-
const
|
|
4472
|
+
const params = await c.req.json();
|
|
1196
4473
|
const mastra = c.get("mastra");
|
|
4474
|
+
const contextRequestContext = c.get("requestContext");
|
|
1197
4475
|
let workflowToUse = workflow;
|
|
1198
4476
|
if (!workflow) {
|
|
1199
4477
|
const workflowId = c.req.param("workflowId");
|
|
@@ -1207,27 +4485,51 @@ function workflowRoute({
|
|
|
1207
4485
|
if (!workflowToUse) {
|
|
1208
4486
|
throw new Error("Workflow ID is required");
|
|
1209
4487
|
}
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
4488
|
+
if (contextRequestContext && params.requestContext) {
|
|
4489
|
+
mastra.getLogger()?.warn(
|
|
4490
|
+
`"requestContext" from the request body will be ignored because "requestContext" is already set in the route options.`
|
|
4491
|
+
);
|
|
1213
4492
|
}
|
|
1214
|
-
const
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
4493
|
+
const uiMessageStream = await handleWorkflowStream({
|
|
4494
|
+
mastra,
|
|
4495
|
+
workflowId: workflowToUse,
|
|
4496
|
+
params: {
|
|
4497
|
+
...params,
|
|
4498
|
+
requestContext: contextRequestContext || params.requestContext
|
|
4499
|
+
},
|
|
4500
|
+
includeTextStreamParts
|
|
1222
4501
|
});
|
|
1223
|
-
return
|
|
4502
|
+
return createUIMessageStreamResponse({ stream: uiMessageStream });
|
|
4503
|
+
}
|
|
4504
|
+
});
|
|
4505
|
+
}
|
|
4506
|
+
async function handleNetworkStream({
|
|
4507
|
+
mastra,
|
|
4508
|
+
agentId,
|
|
4509
|
+
params,
|
|
4510
|
+
defaultOptions: defaultOptions2
|
|
4511
|
+
}) {
|
|
4512
|
+
const { messages, ...rest } = params;
|
|
4513
|
+
const agentObj = mastra.getAgentById(agentId);
|
|
4514
|
+
if (!agentObj) {
|
|
4515
|
+
throw new Error(`Agent ${agentId} not found`);
|
|
4516
|
+
}
|
|
4517
|
+
const result = await agentObj.network(messages, {
|
|
4518
|
+
...defaultOptions2,
|
|
4519
|
+
...rest
|
|
4520
|
+
});
|
|
4521
|
+
return createUIMessageStream({
|
|
4522
|
+
execute: async ({ writer }) => {
|
|
4523
|
+
for await (const part of toAISdkV5Stream(result, { from: "network" })) {
|
|
4524
|
+
writer.write(part);
|
|
4525
|
+
}
|
|
1224
4526
|
}
|
|
1225
4527
|
});
|
|
1226
4528
|
}
|
|
1227
4529
|
function networkRoute({
|
|
1228
4530
|
path = "/network/:agentId",
|
|
1229
4531
|
agent,
|
|
1230
|
-
defaultOptions
|
|
4532
|
+
defaultOptions: defaultOptions2
|
|
1231
4533
|
}) {
|
|
1232
4534
|
if (!agent && !path.includes("/:agentId")) {
|
|
1233
4535
|
throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
|
|
@@ -1284,8 +4586,9 @@ function networkRoute({
|
|
|
1284
4586
|
}
|
|
1285
4587
|
},
|
|
1286
4588
|
handler: async (c) => {
|
|
1287
|
-
const
|
|
4589
|
+
const params = await c.req.json();
|
|
1288
4590
|
const mastra = c.get("mastra");
|
|
4591
|
+
const contextRequestContext = c.get("requestContext");
|
|
1289
4592
|
let agentToUse = agent;
|
|
1290
4593
|
if (!agent) {
|
|
1291
4594
|
const agentId = c.req.param("agentId");
|
|
@@ -1296,28 +4599,475 @@ function networkRoute({
|
|
|
1296
4599
|
`Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
|
|
1297
4600
|
);
|
|
1298
4601
|
}
|
|
4602
|
+
const effectiveRequestContext = contextRequestContext || defaultOptions2?.requestContext || params.requestContext;
|
|
4603
|
+
if (contextRequestContext && defaultOptions2?.requestContext || contextRequestContext && params.requestContext || defaultOptions2?.requestContext && params.requestContext) {
|
|
4604
|
+
mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
|
|
4605
|
+
}
|
|
1299
4606
|
if (!agentToUse) {
|
|
1300
4607
|
throw new Error("Agent ID is required");
|
|
1301
4608
|
}
|
|
1302
|
-
const
|
|
1303
|
-
|
|
1304
|
-
|
|
4609
|
+
const uiMessageStream = await handleNetworkStream({
|
|
4610
|
+
mastra,
|
|
4611
|
+
agentId: agentToUse,
|
|
4612
|
+
params: {
|
|
4613
|
+
...params,
|
|
4614
|
+
requestContext: effectiveRequestContext
|
|
4615
|
+
},
|
|
4616
|
+
defaultOptions: defaultOptions2
|
|
4617
|
+
});
|
|
4618
|
+
return createUIMessageStreamResponse({ stream: uiMessageStream });
|
|
4619
|
+
}
|
|
4620
|
+
});
|
|
4621
|
+
}
|
|
4622
|
+
function withMastra(model, options = {}) {
|
|
4623
|
+
const { memory, inputProcessors = [], outputProcessors = [] } = options;
|
|
4624
|
+
const allInputProcessors = [...inputProcessors];
|
|
4625
|
+
const allOutputProcessors = [...outputProcessors];
|
|
4626
|
+
if (memory) {
|
|
4627
|
+
const { storage, lastMessages, semanticRecall, workingMemory } = memory;
|
|
4628
|
+
const isWorkingMemoryEnabled = typeof workingMemory === "object" && workingMemory.enabled !== false;
|
|
4629
|
+
if (isWorkingMemoryEnabled && typeof workingMemory === "object") {
|
|
4630
|
+
let template;
|
|
4631
|
+
if (workingMemory.template) {
|
|
4632
|
+
template = {
|
|
4633
|
+
format: "markdown",
|
|
4634
|
+
content: workingMemory.template
|
|
4635
|
+
};
|
|
4636
|
+
}
|
|
4637
|
+
const workingMemoryProcessor = new processors.WorkingMemory({
|
|
4638
|
+
storage,
|
|
4639
|
+
template,
|
|
4640
|
+
scope: workingMemory.scope,
|
|
4641
|
+
useVNext: "version" in workingMemory && workingMemory.version === "vnext"
|
|
4642
|
+
});
|
|
4643
|
+
allInputProcessors.push(workingMemoryProcessor);
|
|
4644
|
+
}
|
|
4645
|
+
if (lastMessages !== false && lastMessages !== void 0) {
|
|
4646
|
+
const messageHistory = new processors.MessageHistory({
|
|
4647
|
+
storage,
|
|
4648
|
+
lastMessages: typeof lastMessages === "number" ? lastMessages : void 0
|
|
4649
|
+
});
|
|
4650
|
+
allInputProcessors.push(messageHistory);
|
|
4651
|
+
allOutputProcessors.push(messageHistory);
|
|
4652
|
+
}
|
|
4653
|
+
if (semanticRecall) {
|
|
4654
|
+
const { vector, embedder, indexName, ...semanticConfig } = semanticRecall;
|
|
4655
|
+
const semanticRecallProcessor = new processors.SemanticRecall({
|
|
4656
|
+
storage,
|
|
4657
|
+
vector,
|
|
4658
|
+
embedder,
|
|
4659
|
+
indexName: indexName || "memory_messages",
|
|
4660
|
+
...semanticConfig
|
|
4661
|
+
});
|
|
4662
|
+
allInputProcessors.push(semanticRecallProcessor);
|
|
4663
|
+
allOutputProcessors.push(semanticRecallProcessor);
|
|
4664
|
+
}
|
|
4665
|
+
}
|
|
4666
|
+
return wrapLanguageModel({
|
|
4667
|
+
model,
|
|
4668
|
+
middleware: createProcessorMiddleware({
|
|
4669
|
+
inputProcessors: allInputProcessors,
|
|
4670
|
+
outputProcessors: allOutputProcessors,
|
|
4671
|
+
memory: memory ? {
|
|
4672
|
+
threadId: memory.threadId,
|
|
4673
|
+
resourceId: memory.resourceId
|
|
4674
|
+
} : void 0
|
|
4675
|
+
})
|
|
4676
|
+
});
|
|
4677
|
+
}
|
|
4678
|
+
function createProcessorMiddleware(options) {
|
|
4679
|
+
const { inputProcessors = [], outputProcessors = [], memory } = options;
|
|
4680
|
+
const requestContext = new di.RequestContext();
|
|
4681
|
+
if (memory) {
|
|
4682
|
+
requestContext.set("MastraMemory", {
|
|
4683
|
+
thread: memory.threadId ? { id: memory.threadId } : void 0,
|
|
4684
|
+
resourceId: memory.resourceId,
|
|
4685
|
+
memoryConfig: memory.config
|
|
4686
|
+
});
|
|
4687
|
+
}
|
|
4688
|
+
return {
|
|
4689
|
+
middlewareVersion: "v2",
|
|
4690
|
+
/**
|
|
4691
|
+
* Transform params runs input processors (processInput)
|
|
4692
|
+
*/
|
|
4693
|
+
async transformParams({ params }) {
|
|
4694
|
+
const messageList = new agent.MessageList({
|
|
4695
|
+
threadId: memory?.threadId,
|
|
4696
|
+
resourceId: memory?.resourceId
|
|
4697
|
+
});
|
|
4698
|
+
for (const msg of params.prompt) {
|
|
4699
|
+
if (msg.role === "system") {
|
|
4700
|
+
messageList.addSystem(msg.content);
|
|
4701
|
+
} else {
|
|
4702
|
+
messageList.add(msg, "input");
|
|
4703
|
+
}
|
|
4704
|
+
}
|
|
4705
|
+
for (const processor of inputProcessors) {
|
|
4706
|
+
if (processor.processInput) {
|
|
4707
|
+
try {
|
|
4708
|
+
await processor.processInput({
|
|
4709
|
+
messages: messageList.get.input.db(),
|
|
4710
|
+
systemMessages: messageList.getAllSystemMessages(),
|
|
4711
|
+
messageList,
|
|
4712
|
+
requestContext,
|
|
4713
|
+
abort: (reason) => {
|
|
4714
|
+
throw new agent.TripWire(reason || "Aborted by processor");
|
|
4715
|
+
}
|
|
4716
|
+
});
|
|
4717
|
+
} catch (error) {
|
|
4718
|
+
if (error instanceof agent.TripWire) {
|
|
4719
|
+
return {
|
|
4720
|
+
...params,
|
|
4721
|
+
providerOptions: {
|
|
4722
|
+
...params.providerOptions,
|
|
4723
|
+
mastraProcessors: {
|
|
4724
|
+
tripwire: true,
|
|
4725
|
+
reason: error.message
|
|
4726
|
+
}
|
|
4727
|
+
}
|
|
4728
|
+
};
|
|
4729
|
+
}
|
|
4730
|
+
throw error;
|
|
4731
|
+
}
|
|
4732
|
+
}
|
|
4733
|
+
}
|
|
4734
|
+
const newPrompt = messageList.get.all.aiV5.prompt().map(agent.MessageList.aiV5ModelMessageToV2PromptMessage);
|
|
4735
|
+
return {
|
|
4736
|
+
...params,
|
|
4737
|
+
prompt: newPrompt
|
|
4738
|
+
};
|
|
4739
|
+
},
|
|
4740
|
+
/**
|
|
4741
|
+
* Wrap generate for non-streaming output processing
|
|
4742
|
+
*/
|
|
4743
|
+
async wrapGenerate({ doGenerate, params }) {
|
|
4744
|
+
const processorState = params.providerOptions?.mastraProcessors;
|
|
4745
|
+
if (processorState?.tripwire) {
|
|
4746
|
+
const reason = processorState.reason || "Blocked by processor";
|
|
4747
|
+
return {
|
|
4748
|
+
content: [{ type: "text", text: reason }],
|
|
4749
|
+
finishReason: "stop",
|
|
4750
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
4751
|
+
warnings: [{ type: "other", message: `Tripwire: ${reason}` }]
|
|
4752
|
+
};
|
|
1305
4753
|
}
|
|
1306
|
-
const result = await
|
|
1307
|
-
|
|
1308
|
-
|
|
4754
|
+
const result = await doGenerate();
|
|
4755
|
+
if (!outputProcessors.length) return result;
|
|
4756
|
+
const messageList = new agent.MessageList({
|
|
4757
|
+
threadId: memory?.threadId,
|
|
4758
|
+
resourceId: memory?.resourceId
|
|
1309
4759
|
});
|
|
1310
|
-
const
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
4760
|
+
for (const msg of params.prompt) {
|
|
4761
|
+
if (msg.role === "system") {
|
|
4762
|
+
messageList.addSystem(msg.content);
|
|
4763
|
+
} else {
|
|
4764
|
+
messageList.add(msg, "input");
|
|
4765
|
+
}
|
|
4766
|
+
}
|
|
4767
|
+
const textContent = result.content.filter((c) => c.type === "text").map((c) => c.text).join("");
|
|
4768
|
+
const responseMessage = {
|
|
4769
|
+
id: crypto.randomUUID(),
|
|
4770
|
+
role: "assistant",
|
|
4771
|
+
content: {
|
|
4772
|
+
format: 2,
|
|
4773
|
+
parts: [{ type: "text", text: textContent }]
|
|
4774
|
+
},
|
|
4775
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
4776
|
+
...memory?.threadId && { threadId: memory.threadId },
|
|
4777
|
+
...memory?.resourceId && { resourceId: memory.resourceId }
|
|
4778
|
+
};
|
|
4779
|
+
messageList.add(responseMessage, "response");
|
|
4780
|
+
for (const processor of outputProcessors) {
|
|
4781
|
+
if (processor.processOutputResult) {
|
|
4782
|
+
try {
|
|
4783
|
+
await processor.processOutputResult({
|
|
4784
|
+
messages: messageList.get.all.db(),
|
|
4785
|
+
messageList,
|
|
4786
|
+
requestContext,
|
|
4787
|
+
abort: (reason) => {
|
|
4788
|
+
throw new agent.TripWire(reason || "Aborted by processor");
|
|
4789
|
+
}
|
|
4790
|
+
});
|
|
4791
|
+
} catch (error) {
|
|
4792
|
+
if (error instanceof agent.TripWire) {
|
|
4793
|
+
return {
|
|
4794
|
+
content: [{ type: "text", text: error.message }],
|
|
4795
|
+
finishReason: "stop",
|
|
4796
|
+
usage: result.usage,
|
|
4797
|
+
warnings: [{ type: "other", message: `Output blocked: ${error.message}` }]
|
|
4798
|
+
};
|
|
4799
|
+
}
|
|
4800
|
+
throw error;
|
|
1314
4801
|
}
|
|
1315
4802
|
}
|
|
4803
|
+
}
|
|
4804
|
+
const processedText = messageList.get.response.db().map((m) => extractTextFromMastraMessage(m)).join("");
|
|
4805
|
+
return {
|
|
4806
|
+
...result,
|
|
4807
|
+
content: [{ type: "text", text: processedText }]
|
|
4808
|
+
};
|
|
4809
|
+
},
|
|
4810
|
+
/**
|
|
4811
|
+
* Wrap stream for streaming output processing
|
|
4812
|
+
*/
|
|
4813
|
+
async wrapStream({ doStream, params }) {
|
|
4814
|
+
const processorState = params.providerOptions?.mastraProcessors;
|
|
4815
|
+
if (processorState?.tripwire) {
|
|
4816
|
+
const reason = processorState.reason || "Blocked by processor";
|
|
4817
|
+
return {
|
|
4818
|
+
stream: createBlockedStream(reason)
|
|
4819
|
+
};
|
|
4820
|
+
}
|
|
4821
|
+
const { stream: stream$1, ...rest } = await doStream();
|
|
4822
|
+
if (!outputProcessors.length) return { stream: stream$1, ...rest };
|
|
4823
|
+
const processorStates = /* @__PURE__ */ new Map();
|
|
4824
|
+
const runId = crypto.randomUUID();
|
|
4825
|
+
const transformedStream = stream$1.pipeThrough(
|
|
4826
|
+
new TransformStream({
|
|
4827
|
+
async transform(chunk, controller) {
|
|
4828
|
+
let mastraChunk = stream.convertFullStreamChunkToMastra(
|
|
4829
|
+
chunk,
|
|
4830
|
+
{ runId }
|
|
4831
|
+
);
|
|
4832
|
+
if (!mastraChunk) {
|
|
4833
|
+
controller.enqueue(chunk);
|
|
4834
|
+
return;
|
|
4835
|
+
}
|
|
4836
|
+
for (const processor of outputProcessors) {
|
|
4837
|
+
if (processor.processOutputStream && mastraChunk) {
|
|
4838
|
+
let state = processorStates.get(processor.id);
|
|
4839
|
+
if (!state) {
|
|
4840
|
+
state = { streamParts: [], customState: {} };
|
|
4841
|
+
processorStates.set(processor.id, state);
|
|
4842
|
+
}
|
|
4843
|
+
state.streamParts.push(mastraChunk);
|
|
4844
|
+
try {
|
|
4845
|
+
const result = await processor.processOutputStream({
|
|
4846
|
+
part: mastraChunk,
|
|
4847
|
+
streamParts: state.streamParts,
|
|
4848
|
+
state: state.customState,
|
|
4849
|
+
requestContext,
|
|
4850
|
+
abort: (reason) => {
|
|
4851
|
+
throw new agent.TripWire(reason || "Aborted by processor");
|
|
4852
|
+
}
|
|
4853
|
+
});
|
|
4854
|
+
if (result === null || result === void 0) {
|
|
4855
|
+
mastraChunk = void 0;
|
|
4856
|
+
} else {
|
|
4857
|
+
mastraChunk = result;
|
|
4858
|
+
}
|
|
4859
|
+
} catch (error) {
|
|
4860
|
+
if (error instanceof agent.TripWire) {
|
|
4861
|
+
controller.enqueue({
|
|
4862
|
+
type: "error",
|
|
4863
|
+
error: new Error(error.message)
|
|
4864
|
+
});
|
|
4865
|
+
controller.terminate();
|
|
4866
|
+
return;
|
|
4867
|
+
}
|
|
4868
|
+
throw error;
|
|
4869
|
+
}
|
|
4870
|
+
}
|
|
4871
|
+
}
|
|
4872
|
+
if (mastraChunk) {
|
|
4873
|
+
const aiChunk = convertMastraChunkToAISDKStreamPart(mastraChunk);
|
|
4874
|
+
if (aiChunk) {
|
|
4875
|
+
controller.enqueue(aiChunk);
|
|
4876
|
+
}
|
|
4877
|
+
}
|
|
4878
|
+
}
|
|
4879
|
+
})
|
|
4880
|
+
);
|
|
4881
|
+
return { stream: transformedStream, ...rest };
|
|
4882
|
+
}
|
|
4883
|
+
};
|
|
4884
|
+
}
|
|
4885
|
+
function createBlockedStream(reason) {
|
|
4886
|
+
return new ReadableStream({
|
|
4887
|
+
start(controller) {
|
|
4888
|
+
const id = crypto.randomUUID();
|
|
4889
|
+
controller.enqueue({
|
|
4890
|
+
type: "text-start",
|
|
4891
|
+
id
|
|
4892
|
+
});
|
|
4893
|
+
controller.enqueue({
|
|
4894
|
+
type: "text-delta",
|
|
4895
|
+
id,
|
|
4896
|
+
delta: reason
|
|
4897
|
+
});
|
|
4898
|
+
controller.enqueue({
|
|
4899
|
+
type: "text-end",
|
|
4900
|
+
id
|
|
4901
|
+
});
|
|
4902
|
+
controller.enqueue({
|
|
4903
|
+
type: "finish",
|
|
4904
|
+
finishReason: "stop",
|
|
4905
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
|
|
1316
4906
|
});
|
|
1317
|
-
|
|
4907
|
+
controller.close();
|
|
1318
4908
|
}
|
|
1319
4909
|
});
|
|
1320
4910
|
}
|
|
4911
|
+
function extractTextFromMastraMessage(msg) {
|
|
4912
|
+
const content = msg.content;
|
|
4913
|
+
if (typeof content === "string") {
|
|
4914
|
+
return content;
|
|
4915
|
+
}
|
|
4916
|
+
if (content?.parts) {
|
|
4917
|
+
return content.parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join("");
|
|
4918
|
+
}
|
|
4919
|
+
return "";
|
|
4920
|
+
}
|
|
4921
|
+
function convertMastraChunkToAISDKStreamPart(chunk) {
|
|
4922
|
+
switch (chunk.type) {
|
|
4923
|
+
// Text streaming
|
|
4924
|
+
case "text-start":
|
|
4925
|
+
return {
|
|
4926
|
+
type: "text-start",
|
|
4927
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4928
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4929
|
+
};
|
|
4930
|
+
case "text-delta":
|
|
4931
|
+
return {
|
|
4932
|
+
type: "text-delta",
|
|
4933
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4934
|
+
delta: chunk.payload.text,
|
|
4935
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4936
|
+
};
|
|
4937
|
+
case "text-end":
|
|
4938
|
+
return {
|
|
4939
|
+
type: "text-end",
|
|
4940
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4941
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4942
|
+
};
|
|
4943
|
+
// Reasoning streaming
|
|
4944
|
+
case "reasoning-start":
|
|
4945
|
+
return {
|
|
4946
|
+
type: "reasoning-start",
|
|
4947
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4948
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4949
|
+
};
|
|
4950
|
+
case "reasoning-delta":
|
|
4951
|
+
return {
|
|
4952
|
+
type: "reasoning-delta",
|
|
4953
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4954
|
+
delta: chunk.payload.text,
|
|
4955
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4956
|
+
};
|
|
4957
|
+
case "reasoning-end":
|
|
4958
|
+
return {
|
|
4959
|
+
type: "reasoning-end",
|
|
4960
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4961
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4962
|
+
};
|
|
4963
|
+
// Tool call (complete)
|
|
4964
|
+
case "tool-call":
|
|
4965
|
+
return {
|
|
4966
|
+
type: "tool-call",
|
|
4967
|
+
toolCallId: chunk.payload.toolCallId,
|
|
4968
|
+
toolName: chunk.payload.toolName,
|
|
4969
|
+
input: JSON.stringify(chunk.payload.args),
|
|
4970
|
+
providerExecuted: chunk.payload.providerExecuted,
|
|
4971
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4972
|
+
};
|
|
4973
|
+
// Tool call input streaming
|
|
4974
|
+
case "tool-call-input-streaming-start":
|
|
4975
|
+
return {
|
|
4976
|
+
type: "tool-input-start",
|
|
4977
|
+
id: chunk.payload.toolCallId,
|
|
4978
|
+
toolName: chunk.payload.toolName,
|
|
4979
|
+
providerExecuted: chunk.payload.providerExecuted,
|
|
4980
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4981
|
+
};
|
|
4982
|
+
case "tool-call-delta":
|
|
4983
|
+
return {
|
|
4984
|
+
type: "tool-input-delta",
|
|
4985
|
+
id: chunk.payload.toolCallId,
|
|
4986
|
+
delta: chunk.payload.argsTextDelta,
|
|
4987
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4988
|
+
};
|
|
4989
|
+
case "tool-call-input-streaming-end":
|
|
4990
|
+
return {
|
|
4991
|
+
type: "tool-input-end",
|
|
4992
|
+
id: chunk.payload.toolCallId,
|
|
4993
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4994
|
+
};
|
|
4995
|
+
// Tool result
|
|
4996
|
+
case "tool-result":
|
|
4997
|
+
return {
|
|
4998
|
+
type: "tool-result",
|
|
4999
|
+
toolCallId: chunk.payload.toolCallId,
|
|
5000
|
+
toolName: chunk.payload.toolName,
|
|
5001
|
+
result: { type: "json", value: chunk.payload.result },
|
|
5002
|
+
isError: chunk.payload.isError,
|
|
5003
|
+
providerExecuted: chunk.payload.providerExecuted,
|
|
5004
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
5005
|
+
};
|
|
5006
|
+
// Source (citations)
|
|
5007
|
+
case "source":
|
|
5008
|
+
if (chunk.payload.sourceType === "url") {
|
|
5009
|
+
return {
|
|
5010
|
+
type: "source",
|
|
5011
|
+
sourceType: "url",
|
|
5012
|
+
id: chunk.payload.id,
|
|
5013
|
+
url: chunk.payload.url,
|
|
5014
|
+
title: chunk.payload.title,
|
|
5015
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
5016
|
+
};
|
|
5017
|
+
} else {
|
|
5018
|
+
return {
|
|
5019
|
+
type: "source",
|
|
5020
|
+
sourceType: "document",
|
|
5021
|
+
id: chunk.payload.id,
|
|
5022
|
+
mediaType: chunk.payload.mimeType,
|
|
5023
|
+
title: chunk.payload.title,
|
|
5024
|
+
filename: chunk.payload.filename,
|
|
5025
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
5026
|
+
};
|
|
5027
|
+
}
|
|
5028
|
+
// File output
|
|
5029
|
+
case "file":
|
|
5030
|
+
return {
|
|
5031
|
+
type: "file",
|
|
5032
|
+
data: chunk.payload.data || chunk.payload.base64,
|
|
5033
|
+
mediaType: chunk.payload.mimeType
|
|
5034
|
+
};
|
|
5035
|
+
// Response metadata
|
|
5036
|
+
case "response-metadata":
|
|
5037
|
+
return {
|
|
5038
|
+
type: "response-metadata",
|
|
5039
|
+
...chunk.payload
|
|
5040
|
+
};
|
|
5041
|
+
// Raw provider data
|
|
5042
|
+
case "raw":
|
|
5043
|
+
return {
|
|
5044
|
+
type: "raw",
|
|
5045
|
+
rawValue: chunk.payload
|
|
5046
|
+
};
|
|
5047
|
+
// Finish
|
|
5048
|
+
case "finish": {
|
|
5049
|
+
const usage = chunk.payload.output?.usage;
|
|
5050
|
+
return {
|
|
5051
|
+
type: "finish",
|
|
5052
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult?.reason || "stop"),
|
|
5053
|
+
usage: usage ? {
|
|
5054
|
+
inputTokens: usage.inputTokens || 0,
|
|
5055
|
+
outputTokens: usage.outputTokens || 0,
|
|
5056
|
+
totalTokens: usage.totalTokens || 0
|
|
5057
|
+
} : { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
5058
|
+
providerMetadata: chunk.payload.metadata?.providerMetadata
|
|
5059
|
+
};
|
|
5060
|
+
}
|
|
5061
|
+
// Error
|
|
5062
|
+
case "error":
|
|
5063
|
+
return {
|
|
5064
|
+
type: "error",
|
|
5065
|
+
error: chunk.payload.error || chunk.payload
|
|
5066
|
+
};
|
|
5067
|
+
default:
|
|
5068
|
+
return null;
|
|
5069
|
+
}
|
|
5070
|
+
}
|
|
1321
5071
|
|
|
1322
5072
|
// src/to-ai-sdk-format.ts
|
|
1323
5073
|
function toAISdkFormat() {
|
|
@@ -1327,9 +5077,13 @@ function toAISdkFormat() {
|
|
|
1327
5077
|
}
|
|
1328
5078
|
|
|
1329
5079
|
exports.chatRoute = chatRoute;
|
|
5080
|
+
exports.handleChatStream = handleChatStream;
|
|
5081
|
+
exports.handleNetworkStream = handleNetworkStream;
|
|
5082
|
+
exports.handleWorkflowStream = handleWorkflowStream;
|
|
1330
5083
|
exports.networkRoute = networkRoute;
|
|
1331
5084
|
exports.toAISdkFormat = toAISdkFormat;
|
|
1332
5085
|
exports.toAISdkStream = toAISdkV5Stream;
|
|
5086
|
+
exports.withMastra = withMastra;
|
|
1333
5087
|
exports.workflowRoute = workflowRoute;
|
|
1334
5088
|
//# sourceMappingURL=index.cjs.map
|
|
1335
5089
|
//# sourceMappingURL=index.cjs.map
|