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