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