@mastra/ai-sdk 0.0.0-allow-to-pass-a-mastra-url-instance-20251105224938 → 0.0.0-alternative-angelfish-f7665c-20260119184917
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 +947 -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 +93 -5
- package/dist/chat-route.d.ts.map +1 -1
- package/dist/chunk-AAQDCHJY.js +293 -0
- package/dist/chunk-AAQDCHJY.js.map +1 -0
- package/dist/chunk-CCJXHQQO.cjs +296 -0
- package/dist/chunk-CCJXHQQO.cjs.map +1 -0
- package/dist/chunk-DES3K4SD.cjs +17 -0
- package/dist/chunk-DES3K4SD.cjs.map +1 -0
- package/dist/chunk-VUNV25KB.js +14 -0
- package/dist/chunk-VUNV25KB.js.map +1 -0
- package/dist/convert-messages.d.ts +83 -3
- package/dist/convert-messages.d.ts.map +1 -1
- package/dist/convert-streams.d.ts +67 -4
- package/dist/convert-streams.d.ts.map +1 -1
- package/dist/helpers.d.ts +10 -4
- package/dist/helpers.d.ts.map +1 -1
- package/dist/index.cjs +3807 -123
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +8 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3784 -123
- package/dist/index.js.map +1 -1
- package/dist/middleware.d.ts +157 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/network-route.d.ts +65 -5
- package/dist/network-route.d.ts.map +1 -1
- package/dist/token-36YTPVWD.cjs +63 -0
- package/dist/token-36YTPVWD.cjs.map +1 -0
- package/dist/token-ZFKXETJY.js +61 -0
- package/dist/token-ZFKXETJY.js.map +1 -0
- package/dist/token-util-737PGIQA.cjs +9 -0
- package/dist/token-util-737PGIQA.cjs.map +1 -0
- package/dist/token-util-SD2EI4DD.js +7 -0
- package/dist/token-util-SD2EI4DD.js.map +1 -0
- package/dist/transformers.d.ts +145 -18
- package/dist/transformers.d.ts.map +1 -1
- package/dist/ui.cjs +0 -1
- package/dist/ui.cjs.map +1 -1
- package/dist/ui.js +0 -1
- package/dist/ui.js.map +1 -1
- package/dist/utils.d.ts +2 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/workflow-route.d.ts +68 -1
- package/dist/workflow-route.d.ts.map +1 -1
- package/package.json +12 -10
package/dist/index.js
CHANGED
|
@@ -1,13 +1,2836 @@
|
|
|
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, aiV5ModelMessageToV2PromptMessage } 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
|
+
};
|
|
11
2834
|
function safeParseErrorObject(obj) {
|
|
12
2835
|
if (typeof obj !== "object" || obj === null) {
|
|
13
2836
|
return String(obj);
|
|
@@ -30,6 +2853,12 @@ var isWorkflowExecutionDataChunkType = (chunk) => {
|
|
|
30
2853
|
};
|
|
31
2854
|
|
|
32
2855
|
// src/helpers.ts
|
|
2856
|
+
function toAISDKFinishReason(reason) {
|
|
2857
|
+
if (reason === "tripwire" || reason === "retry") {
|
|
2858
|
+
return "other";
|
|
2859
|
+
}
|
|
2860
|
+
return reason;
|
|
2861
|
+
}
|
|
33
2862
|
function convertMastraChunkToAISDKv5({
|
|
34
2863
|
chunk,
|
|
35
2864
|
mode = "stream"
|
|
@@ -37,7 +2866,9 @@ function convertMastraChunkToAISDKv5({
|
|
|
37
2866
|
switch (chunk.type) {
|
|
38
2867
|
case "start":
|
|
39
2868
|
return {
|
|
40
|
-
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 } : {}
|
|
41
2872
|
};
|
|
42
2873
|
case "step-start":
|
|
43
2874
|
const { messageId: _messageId, ...rest } = chunk.payload;
|
|
@@ -54,7 +2885,8 @@ function convertMastraChunkToAISDKv5({
|
|
|
54
2885
|
case "finish": {
|
|
55
2886
|
return {
|
|
56
2887
|
type: "finish",
|
|
57
|
-
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
|
|
58
2890
|
totalUsage: chunk.payload.output.usage
|
|
59
2891
|
};
|
|
60
2892
|
}
|
|
@@ -138,6 +2970,30 @@ function convertMastraChunkToAISDKv5({
|
|
|
138
2970
|
toolName: chunk.payload.toolName,
|
|
139
2971
|
input: chunk.payload.args
|
|
140
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
|
+
};
|
|
141
2997
|
case "tool-call-input-streaming-start":
|
|
142
2998
|
return {
|
|
143
2999
|
type: "tool-input-start",
|
|
@@ -171,7 +3027,7 @@ function convertMastraChunkToAISDKv5({
|
|
|
171
3027
|
...rest2
|
|
172
3028
|
},
|
|
173
3029
|
usage: chunk.payload.output.usage,
|
|
174
|
-
finishReason: chunk.payload.stepResult.reason,
|
|
3030
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult.reason),
|
|
175
3031
|
providerMetadata
|
|
176
3032
|
};
|
|
177
3033
|
}
|
|
@@ -228,6 +3084,16 @@ function convertMastraChunkToAISDKv5({
|
|
|
228
3084
|
type: "object",
|
|
229
3085
|
object: chunk.object
|
|
230
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
|
+
};
|
|
231
3097
|
default:
|
|
232
3098
|
if (chunk.type && "payload" in chunk && chunk.payload) {
|
|
233
3099
|
return {
|
|
@@ -283,6 +3149,14 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
283
3149
|
};
|
|
284
3150
|
}
|
|
285
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
|
+
}
|
|
286
3160
|
return;
|
|
287
3161
|
}
|
|
288
3162
|
case "reasoning-end": {
|
|
@@ -300,6 +3174,25 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
300
3174
|
};
|
|
301
3175
|
}
|
|
302
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
|
+
}
|
|
303
3196
|
return;
|
|
304
3197
|
}
|
|
305
3198
|
case "tool-input-start": {
|
|
@@ -357,6 +3250,15 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
357
3250
|
toolCallId: part.toolCallId,
|
|
358
3251
|
payload: part.output
|
|
359
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 } };
|
|
360
3262
|
}
|
|
361
3263
|
return;
|
|
362
3264
|
}
|
|
@@ -382,21 +3284,24 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
382
3284
|
return { type: "finish-step" };
|
|
383
3285
|
}
|
|
384
3286
|
case "start": {
|
|
385
|
-
{
|
|
3287
|
+
if (sendStart) {
|
|
3288
|
+
const messageId = ("messageId" in part ? part.messageId : void 0) || responseMessageId;
|
|
386
3289
|
return {
|
|
387
3290
|
type: "start",
|
|
388
3291
|
...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},
|
|
389
|
-
...
|
|
3292
|
+
...messageId != null ? { messageId } : {}
|
|
390
3293
|
};
|
|
391
3294
|
}
|
|
3295
|
+
return;
|
|
392
3296
|
}
|
|
393
3297
|
case "finish": {
|
|
394
|
-
{
|
|
3298
|
+
if (sendFinish) {
|
|
395
3299
|
return {
|
|
396
3300
|
type: "finish",
|
|
397
3301
|
...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}
|
|
398
3302
|
};
|
|
399
3303
|
}
|
|
3304
|
+
return;
|
|
400
3305
|
}
|
|
401
3306
|
case "abort": {
|
|
402
3307
|
return part;
|
|
@@ -415,7 +3320,8 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
415
3320
|
${JSON.stringify(part)}`
|
|
416
3321
|
);
|
|
417
3322
|
}
|
|
418
|
-
|
|
3323
|
+
const { type, data, id } = part;
|
|
3324
|
+
return { type, data, ...id !== void 0 && { id } };
|
|
419
3325
|
}
|
|
420
3326
|
return;
|
|
421
3327
|
}
|
|
@@ -423,7 +3329,10 @@ function convertFullStreamChunkToUIMessageStream({
|
|
|
423
3329
|
}
|
|
424
3330
|
|
|
425
3331
|
// src/transformers.ts
|
|
426
|
-
|
|
3332
|
+
var PRIMITIVE_CACHE_SYMBOL = /* @__PURE__ */ Symbol("primitive-cache");
|
|
3333
|
+
function WorkflowStreamToAISDKTransformer({
|
|
3334
|
+
includeTextStreamParts
|
|
3335
|
+
} = {}) {
|
|
427
3336
|
const bufferedWorkflows = /* @__PURE__ */ new Map();
|
|
428
3337
|
return new TransformStream({
|
|
429
3338
|
start(controller) {
|
|
@@ -437,7 +3346,7 @@ function WorkflowStreamToAISDKTransformer() {
|
|
|
437
3346
|
});
|
|
438
3347
|
},
|
|
439
3348
|
transform(chunk, controller) {
|
|
440
|
-
const transformed = transformWorkflow(chunk, bufferedWorkflows);
|
|
3349
|
+
const transformed = transformWorkflow(chunk, bufferedWorkflows, false, includeTextStreamParts);
|
|
441
3350
|
if (transformed) controller.enqueue(transformed);
|
|
442
3351
|
}
|
|
443
3352
|
});
|
|
@@ -457,24 +3366,49 @@ function AgentNetworkToAISDKTransformer() {
|
|
|
457
3366
|
},
|
|
458
3367
|
transform(chunk, controller) {
|
|
459
3368
|
const transformed = transformNetwork(chunk, bufferedNetworks);
|
|
460
|
-
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
|
+
}
|
|
461
3378
|
}
|
|
462
3379
|
});
|
|
463
3380
|
}
|
|
464
|
-
function AgentStreamToAISDKTransformer(
|
|
3381
|
+
function AgentStreamToAISDKTransformer({
|
|
3382
|
+
lastMessageId,
|
|
3383
|
+
sendStart,
|
|
3384
|
+
sendFinish,
|
|
3385
|
+
sendReasoning,
|
|
3386
|
+
sendSources,
|
|
3387
|
+
messageMetadata,
|
|
3388
|
+
onError
|
|
3389
|
+
}) {
|
|
465
3390
|
let bufferedSteps = /* @__PURE__ */ new Map();
|
|
3391
|
+
let tripwireOccurred = false;
|
|
3392
|
+
let finishEventSent = false;
|
|
466
3393
|
return new TransformStream({
|
|
467
3394
|
transform(chunk, controller) {
|
|
3395
|
+
if (chunk.type === "tripwire") {
|
|
3396
|
+
tripwireOccurred = true;
|
|
3397
|
+
}
|
|
3398
|
+
if (chunk.type === "finish") {
|
|
3399
|
+
finishEventSent = true;
|
|
3400
|
+
}
|
|
468
3401
|
const part = convertMastraChunkToAISDKv5({ chunk, mode: "stream" });
|
|
469
3402
|
const transformedChunk = convertFullStreamChunkToUIMessageStream({
|
|
470
3403
|
part,
|
|
471
|
-
sendReasoning
|
|
472
|
-
sendSources
|
|
473
|
-
|
|
474
|
-
|
|
3404
|
+
sendReasoning,
|
|
3405
|
+
sendSources,
|
|
3406
|
+
messageMetadataValue: messageMetadata?.({ part }),
|
|
3407
|
+
sendStart,
|
|
3408
|
+
sendFinish,
|
|
475
3409
|
responseMessageId: lastMessageId,
|
|
476
3410
|
onError(error) {
|
|
477
|
-
return safeParseErrorObject(error);
|
|
3411
|
+
return onError ? onError(error) : safeParseErrorObject(error);
|
|
478
3412
|
}
|
|
479
3413
|
});
|
|
480
3414
|
if (transformedChunk) {
|
|
@@ -494,6 +3428,14 @@ function AgentStreamToAISDKTransformer(lastMessageId) {
|
|
|
494
3428
|
controller.enqueue(transformedChunk);
|
|
495
3429
|
}
|
|
496
3430
|
}
|
|
3431
|
+
},
|
|
3432
|
+
flush(controller) {
|
|
3433
|
+
if (tripwireOccurred && !finishEventSent && sendFinish) {
|
|
3434
|
+
controller.enqueue({
|
|
3435
|
+
type: "finish",
|
|
3436
|
+
finishReason: "other"
|
|
3437
|
+
});
|
|
3438
|
+
}
|
|
497
3439
|
}
|
|
498
3440
|
});
|
|
499
3441
|
}
|
|
@@ -633,7 +3575,7 @@ function transformAgent(payload, bufferedSteps) {
|
|
|
633
3575
|
}
|
|
634
3576
|
return null;
|
|
635
3577
|
}
|
|
636
|
-
function transformWorkflow(payload, bufferedWorkflows, isNested) {
|
|
3578
|
+
function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStreamParts) {
|
|
637
3579
|
switch (payload.type) {
|
|
638
3580
|
case "workflow-start":
|
|
639
3581
|
bufferedWorkflows.set(payload.runId, {
|
|
@@ -726,6 +3668,30 @@ function transformWorkflow(payload, bufferedWorkflows, isNested) {
|
|
|
726
3668
|
}
|
|
727
3669
|
};
|
|
728
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
|
+
}
|
|
729
3695
|
default: {
|
|
730
3696
|
if (isDataChunkType(payload)) {
|
|
731
3697
|
if (!("data" in payload)) {
|
|
@@ -734,7 +3700,12 @@ function transformWorkflow(payload, bufferedWorkflows, isNested) {
|
|
|
734
3700
|
${JSON.stringify(payload)}`
|
|
735
3701
|
);
|
|
736
3702
|
}
|
|
737
|
-
|
|
3703
|
+
const { type, data, id } = payload;
|
|
3704
|
+
return {
|
|
3705
|
+
type,
|
|
3706
|
+
data,
|
|
3707
|
+
...id !== void 0 && { id }
|
|
3708
|
+
};
|
|
738
3709
|
}
|
|
739
3710
|
return null;
|
|
740
3711
|
}
|
|
@@ -745,12 +3716,30 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
745
3716
|
case "routing-agent-start": {
|
|
746
3717
|
if (!bufferedNetworks.has(payload.runId)) {
|
|
747
3718
|
bufferedNetworks.set(payload.runId, {
|
|
748
|
-
name: payload.payload.
|
|
3719
|
+
name: payload.payload.networkId,
|
|
749
3720
|
steps: [],
|
|
750
3721
|
usage: null,
|
|
751
|
-
output: null
|
|
3722
|
+
output: null,
|
|
3723
|
+
hasEmittedText: false
|
|
752
3724
|
});
|
|
753
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
|
+
});
|
|
754
3743
|
return {
|
|
755
3744
|
type: isNested ? "data-tool-network" : "data-network",
|
|
756
3745
|
id: payload.runId,
|
|
@@ -766,6 +3755,7 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
766
3755
|
case "routing-agent-text-start": {
|
|
767
3756
|
const current = bufferedNetworks.get(payload.runId);
|
|
768
3757
|
if (!current) return null;
|
|
3758
|
+
current.hasEmittedText = true;
|
|
769
3759
|
return {
|
|
770
3760
|
type: "text-start",
|
|
771
3761
|
id: payload.runId
|
|
@@ -774,6 +3764,7 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
774
3764
|
case "routing-agent-text-delta": {
|
|
775
3765
|
const current = bufferedNetworks.get(payload.runId);
|
|
776
3766
|
if (!current) return null;
|
|
3767
|
+
current.hasEmittedText = true;
|
|
777
3768
|
return {
|
|
778
3769
|
type: "text-delta",
|
|
779
3770
|
id: payload.runId,
|
|
@@ -781,14 +3772,19 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
781
3772
|
};
|
|
782
3773
|
}
|
|
783
3774
|
case "agent-execution-start": {
|
|
784
|
-
const current = bufferedNetworks.get(payload.runId)
|
|
3775
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
3776
|
+
if (!current) return null;
|
|
785
3777
|
current.steps.push({
|
|
3778
|
+
id: payload.payload.runId,
|
|
786
3779
|
name: payload.payload.agentId,
|
|
787
3780
|
status: "running",
|
|
788
|
-
|
|
3781
|
+
iteration: payload.payload.args?.iteration ?? 0,
|
|
3782
|
+
input: { prompt: payload.payload.args?.prompt ?? "" },
|
|
789
3783
|
output: null,
|
|
3784
|
+
task: null,
|
|
790
3785
|
suspendPayload: null,
|
|
791
|
-
resumePayload: null
|
|
3786
|
+
resumePayload: null,
|
|
3787
|
+
[PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
|
|
792
3788
|
});
|
|
793
3789
|
bufferedNetworks.set(payload.runId, current);
|
|
794
3790
|
return {
|
|
@@ -801,14 +3797,19 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
801
3797
|
};
|
|
802
3798
|
}
|
|
803
3799
|
case "workflow-execution-start": {
|
|
804
|
-
const current = bufferedNetworks.get(payload.runId)
|
|
3800
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
3801
|
+
if (!current) return null;
|
|
805
3802
|
current.steps.push({
|
|
806
|
-
|
|
3803
|
+
id: payload.payload.runId,
|
|
3804
|
+
name: payload.payload.workflowId,
|
|
807
3805
|
status: "running",
|
|
808
|
-
|
|
3806
|
+
iteration: payload.payload.args?.iteration ?? 0,
|
|
3807
|
+
input: { prompt: payload.payload.args?.prompt ?? "" },
|
|
809
3808
|
output: null,
|
|
3809
|
+
task: null,
|
|
810
3810
|
suspendPayload: null,
|
|
811
|
-
resumePayload: null
|
|
3811
|
+
resumePayload: null,
|
|
3812
|
+
[PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
|
|
812
3813
|
});
|
|
813
3814
|
bufferedNetworks.set(payload.runId, current);
|
|
814
3815
|
return {
|
|
@@ -821,14 +3822,21 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
821
3822
|
};
|
|
822
3823
|
}
|
|
823
3824
|
case "tool-execution-start": {
|
|
824
|
-
const current = bufferedNetworks.get(payload.runId)
|
|
3825
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
3826
|
+
if (!current) return null;
|
|
825
3827
|
current.steps.push({
|
|
3828
|
+
id: payload.payload.args.toolCallId,
|
|
826
3829
|
name: payload.payload.args?.toolName,
|
|
827
3830
|
status: "running",
|
|
3831
|
+
iteration: payload.payload.args?.iteration ? Number(payload.payload.args.iteration) : 0,
|
|
3832
|
+
task: {
|
|
3833
|
+
id: payload.payload.args?.toolName
|
|
3834
|
+
},
|
|
828
3835
|
input: payload.payload.args?.args || null,
|
|
829
3836
|
output: null,
|
|
830
3837
|
suspendPayload: null,
|
|
831
|
-
resumePayload: null
|
|
3838
|
+
resumePayload: null,
|
|
3839
|
+
[PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
|
|
832
3840
|
});
|
|
833
3841
|
bufferedNetworks.set(payload.runId, current);
|
|
834
3842
|
return {
|
|
@@ -843,14 +3851,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
843
3851
|
case "agent-execution-end": {
|
|
844
3852
|
const current = bufferedNetworks.get(payload.runId);
|
|
845
3853
|
if (!current) return null;
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
});
|
|
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;
|
|
854
3861
|
return {
|
|
855
3862
|
type: isNested ? "data-tool-network" : "data-network",
|
|
856
3863
|
id: payload.runId,
|
|
@@ -865,14 +3872,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
865
3872
|
case "tool-execution-end": {
|
|
866
3873
|
const current = bufferedNetworks.get(payload.runId);
|
|
867
3874
|
if (!current) return null;
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
});
|
|
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;
|
|
876
3882
|
return {
|
|
877
3883
|
type: isNested ? "data-tool-network" : "data-network",
|
|
878
3884
|
id: payload.runId,
|
|
@@ -886,14 +3892,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
886
3892
|
case "workflow-execution-end": {
|
|
887
3893
|
const current = bufferedNetworks.get(payload.runId);
|
|
888
3894
|
if (!current) return null;
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
});
|
|
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;
|
|
897
3902
|
return {
|
|
898
3903
|
type: isNested ? "data-tool-network" : "data-network",
|
|
899
3904
|
id: payload.runId,
|
|
@@ -908,12 +3913,24 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
908
3913
|
case "routing-agent-end": {
|
|
909
3914
|
const current = bufferedNetworks.get(payload.runId);
|
|
910
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;
|
|
911
3929
|
return {
|
|
912
3930
|
type: isNested ? "data-tool-network" : "data-network",
|
|
913
3931
|
id: payload.runId,
|
|
914
3932
|
data: {
|
|
915
3933
|
...current,
|
|
916
|
-
status: "finished",
|
|
917
3934
|
usage: payload.payload?.usage ?? current.usage,
|
|
918
3935
|
output: payload.payload?.result ?? current.output
|
|
919
3936
|
}
|
|
@@ -922,15 +3939,25 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
922
3939
|
case "network-execution-event-step-finish": {
|
|
923
3940
|
const current = bufferedNetworks.get(payload.runId);
|
|
924
3941
|
if (!current) return null;
|
|
925
|
-
|
|
3942
|
+
const resultText = payload.payload?.result;
|
|
3943
|
+
const dataNetworkChunk = {
|
|
926
3944
|
type: isNested ? "data-tool-network" : "data-network",
|
|
927
3945
|
id: payload.runId,
|
|
928
3946
|
data: {
|
|
929
3947
|
...current,
|
|
930
3948
|
status: "finished",
|
|
931
|
-
output:
|
|
3949
|
+
output: resultText ?? current.output
|
|
932
3950
|
}
|
|
933
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;
|
|
934
3961
|
}
|
|
935
3962
|
case "network-execution-event-finish": {
|
|
936
3963
|
const current = bufferedNetworks.get(payload.runId);
|
|
@@ -946,33 +3973,91 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
946
3973
|
}
|
|
947
3974
|
};
|
|
948
3975
|
}
|
|
3976
|
+
case "network-object":
|
|
3977
|
+
case "network-object-result": {
|
|
3978
|
+
return null;
|
|
3979
|
+
}
|
|
949
3980
|
default: {
|
|
950
|
-
if (
|
|
951
|
-
if (!("data" in payload)) {
|
|
3981
|
+
if (isAgentExecutionDataChunkType(payload)) {
|
|
3982
|
+
if (!("data" in payload.payload)) {
|
|
952
3983
|
throw new Error(
|
|
953
3984
|
`UI Messages require a data property when using data- prefixed chunks
|
|
954
3985
|
${JSON.stringify(payload)}`
|
|
955
3986
|
);
|
|
956
3987
|
}
|
|
957
|
-
|
|
3988
|
+
const { type, data, id } = payload.payload;
|
|
3989
|
+
return { type, data, ...id !== void 0 && { id } };
|
|
958
3990
|
}
|
|
959
|
-
if (
|
|
3991
|
+
if (isWorkflowExecutionDataChunkType(payload)) {
|
|
960
3992
|
if (!("data" in payload.payload)) {
|
|
961
3993
|
throw new Error(
|
|
962
3994
|
`UI Messages require a data property when using data- prefixed chunks
|
|
963
3995
|
${JSON.stringify(payload)}`
|
|
964
3996
|
);
|
|
965
3997
|
}
|
|
966
|
-
|
|
3998
|
+
const { type, data, id } = payload.payload;
|
|
3999
|
+
return { type, data, ...id !== void 0 && { id } };
|
|
967
4000
|
}
|
|
968
|
-
if (
|
|
969
|
-
|
|
4001
|
+
if (payload.type.startsWith("agent-execution-event-")) {
|
|
4002
|
+
const stepId = payload.payload.runId;
|
|
4003
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
4004
|
+
if (!current) return null;
|
|
4005
|
+
const step = current.steps.find((step2) => step2.id === stepId);
|
|
4006
|
+
if (!step) {
|
|
4007
|
+
return null;
|
|
4008
|
+
}
|
|
4009
|
+
step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
|
|
4010
|
+
const result = transformAgent(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
|
|
4011
|
+
if (result) {
|
|
4012
|
+
const { request, response, ...data } = result.data;
|
|
4013
|
+
step.task = data;
|
|
4014
|
+
}
|
|
4015
|
+
bufferedNetworks.set(payload.runId, current);
|
|
4016
|
+
return {
|
|
4017
|
+
type: isNested ? "data-tool-network" : "data-network",
|
|
4018
|
+
id: payload.runId,
|
|
4019
|
+
data: {
|
|
4020
|
+
...current,
|
|
4021
|
+
status: "running"
|
|
4022
|
+
}
|
|
4023
|
+
};
|
|
4024
|
+
}
|
|
4025
|
+
if (payload.type.startsWith("workflow-execution-event-")) {
|
|
4026
|
+
const stepId = payload.payload.runId;
|
|
4027
|
+
const current = bufferedNetworks.get(payload.runId);
|
|
4028
|
+
if (!current) return null;
|
|
4029
|
+
const step = current.steps.find((step2) => step2.id === stepId);
|
|
4030
|
+
if (!step) {
|
|
4031
|
+
return null;
|
|
4032
|
+
}
|
|
4033
|
+
step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
|
|
4034
|
+
const result = transformWorkflow(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
|
|
4035
|
+
if (result && "data" in result) {
|
|
4036
|
+
const data = result.data;
|
|
4037
|
+
step.task = data;
|
|
4038
|
+
if (data.name && step.task) {
|
|
4039
|
+
step.task.id = data.name;
|
|
4040
|
+
}
|
|
4041
|
+
}
|
|
4042
|
+
bufferedNetworks.set(payload.runId, current);
|
|
4043
|
+
return {
|
|
4044
|
+
type: isNested ? "data-tool-network" : "data-network",
|
|
4045
|
+
id: payload.runId,
|
|
4046
|
+
data: {
|
|
4047
|
+
...current,
|
|
4048
|
+
status: "running"
|
|
4049
|
+
}
|
|
4050
|
+
};
|
|
4051
|
+
}
|
|
4052
|
+
if (isDataChunkType(payload)) {
|
|
4053
|
+
if (!("data" in payload)) {
|
|
970
4054
|
throw new Error(
|
|
971
4055
|
`UI Messages require a data property when using data- prefixed chunks
|
|
972
4056
|
${JSON.stringify(payload)}`
|
|
973
4057
|
);
|
|
974
4058
|
}
|
|
975
|
-
|
|
4059
|
+
const { type, data, id } = payload;
|
|
4060
|
+
return { type, data, ...id !== void 0 && { id } };
|
|
976
4061
|
}
|
|
977
4062
|
return null;
|
|
978
4063
|
}
|
|
@@ -980,23 +4065,99 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
|
|
|
980
4065
|
}
|
|
981
4066
|
|
|
982
4067
|
// src/convert-streams.ts
|
|
983
|
-
function toAISdkV5Stream(stream, options = {
|
|
4068
|
+
function toAISdkV5Stream(stream, options = {
|
|
4069
|
+
from: "agent",
|
|
4070
|
+
sendStart: true,
|
|
4071
|
+
sendFinish: true
|
|
4072
|
+
}) {
|
|
984
4073
|
const from = options?.from;
|
|
985
4074
|
if (from === "workflow") {
|
|
986
|
-
|
|
4075
|
+
const includeTextStreamParts = options?.includeTextStreamParts ?? true;
|
|
4076
|
+
return stream.pipeThrough(
|
|
4077
|
+
WorkflowStreamToAISDKTransformer({ includeTextStreamParts })
|
|
4078
|
+
);
|
|
987
4079
|
}
|
|
988
4080
|
if (from === "network") {
|
|
989
4081
|
return stream.pipeThrough(AgentNetworkToAISDKTransformer());
|
|
990
4082
|
}
|
|
991
4083
|
const agentReadable = "fullStream" in stream ? stream.fullStream : stream;
|
|
992
|
-
return agentReadable.pipeThrough(
|
|
4084
|
+
return agentReadable.pipeThrough(
|
|
4085
|
+
AgentStreamToAISDKTransformer({
|
|
4086
|
+
lastMessageId: options?.lastMessageId,
|
|
4087
|
+
sendStart: options?.sendStart,
|
|
4088
|
+
sendFinish: options?.sendFinish,
|
|
4089
|
+
sendReasoning: options?.sendReasoning,
|
|
4090
|
+
sendSources: options?.sendSources,
|
|
4091
|
+
messageMetadata: options?.messageMetadata,
|
|
4092
|
+
onError: options?.onError
|
|
4093
|
+
})
|
|
4094
|
+
);
|
|
993
4095
|
}
|
|
994
4096
|
|
|
995
4097
|
// src/chat-route.ts
|
|
4098
|
+
async function handleChatStream({
|
|
4099
|
+
mastra,
|
|
4100
|
+
agentId,
|
|
4101
|
+
params,
|
|
4102
|
+
defaultOptions: defaultOptions2,
|
|
4103
|
+
sendStart = true,
|
|
4104
|
+
sendFinish = true,
|
|
4105
|
+
sendReasoning = false,
|
|
4106
|
+
sendSources = false
|
|
4107
|
+
}) {
|
|
4108
|
+
const { messages, resumeData, runId, requestContext, trigger, ...rest } = params;
|
|
4109
|
+
if (resumeData && !runId) {
|
|
4110
|
+
throw new Error("runId is required when resumeData is provided");
|
|
4111
|
+
}
|
|
4112
|
+
const agentObj = mastra.getAgentById(agentId);
|
|
4113
|
+
if (!agentObj) {
|
|
4114
|
+
throw new Error(`Agent ${agentId} not found`);
|
|
4115
|
+
}
|
|
4116
|
+
if (!Array.isArray(messages)) {
|
|
4117
|
+
throw new Error("Messages must be an array of UIMessage objects");
|
|
4118
|
+
}
|
|
4119
|
+
let lastMessageId;
|
|
4120
|
+
let messagesToSend = messages;
|
|
4121
|
+
if (messages.length > 0) {
|
|
4122
|
+
const lastMessage = messages[messages.length - 1];
|
|
4123
|
+
if (lastMessage?.role === "assistant") {
|
|
4124
|
+
lastMessageId = lastMessage.id;
|
|
4125
|
+
if (trigger === "regenerate-message") {
|
|
4126
|
+
messagesToSend = messages.slice(0, -1);
|
|
4127
|
+
}
|
|
4128
|
+
}
|
|
4129
|
+
}
|
|
4130
|
+
const mergedOptions = {
|
|
4131
|
+
...defaultOptions2,
|
|
4132
|
+
...rest,
|
|
4133
|
+
...runId && { runId },
|
|
4134
|
+
requestContext: requestContext || defaultOptions2?.requestContext
|
|
4135
|
+
};
|
|
4136
|
+
const result = resumeData ? await agentObj.resumeStream(resumeData, mergedOptions) : await agentObj.stream(messagesToSend, mergedOptions);
|
|
4137
|
+
return createUIMessageStream({
|
|
4138
|
+
originalMessages: messages,
|
|
4139
|
+
execute: async ({ writer }) => {
|
|
4140
|
+
for await (const part of toAISdkV5Stream(result, {
|
|
4141
|
+
from: "agent",
|
|
4142
|
+
lastMessageId,
|
|
4143
|
+
sendStart,
|
|
4144
|
+
sendFinish,
|
|
4145
|
+
sendReasoning,
|
|
4146
|
+
sendSources
|
|
4147
|
+
})) {
|
|
4148
|
+
writer.write(part);
|
|
4149
|
+
}
|
|
4150
|
+
}
|
|
4151
|
+
});
|
|
4152
|
+
}
|
|
996
4153
|
function chatRoute({
|
|
997
4154
|
path = "/chat/:agentId",
|
|
998
4155
|
agent,
|
|
999
|
-
defaultOptions
|
|
4156
|
+
defaultOptions: defaultOptions2,
|
|
4157
|
+
sendStart = true,
|
|
4158
|
+
sendFinish = true,
|
|
4159
|
+
sendReasoning = false,
|
|
4160
|
+
sendSources = false
|
|
1000
4161
|
}) {
|
|
1001
4162
|
if (!agent && !path.includes("/:agentId")) {
|
|
1002
4163
|
throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
|
|
@@ -1025,6 +4186,14 @@ function chatRoute({
|
|
|
1025
4186
|
schema: {
|
|
1026
4187
|
type: "object",
|
|
1027
4188
|
properties: {
|
|
4189
|
+
resumeData: {
|
|
4190
|
+
type: "object",
|
|
4191
|
+
description: "Resume data for the agent"
|
|
4192
|
+
},
|
|
4193
|
+
runId: {
|
|
4194
|
+
type: "string",
|
|
4195
|
+
description: "The run ID required when resuming an agent execution"
|
|
4196
|
+
},
|
|
1028
4197
|
messages: {
|
|
1029
4198
|
type: "array",
|
|
1030
4199
|
description: "Array of messages in the conversation",
|
|
@@ -1095,9 +4264,9 @@ function chatRoute({
|
|
|
1095
4264
|
}
|
|
1096
4265
|
},
|
|
1097
4266
|
handler: async (c) => {
|
|
1098
|
-
const
|
|
4267
|
+
const params = await c.req.json();
|
|
1099
4268
|
const mastra = c.get("mastra");
|
|
1100
|
-
const
|
|
4269
|
+
const contextRequestContext = c.get("requestContext");
|
|
1101
4270
|
let agentToUse = agent;
|
|
1102
4271
|
if (!agent) {
|
|
1103
4272
|
const agentId = c.req.param("agentId");
|
|
@@ -1108,32 +4277,25 @@ function chatRoute({
|
|
|
1108
4277
|
`Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
|
|
1109
4278
|
);
|
|
1110
4279
|
}
|
|
1111
|
-
|
|
1112
|
-
|
|
4280
|
+
const effectiveRequestContext = contextRequestContext || defaultOptions2?.requestContext || params.requestContext;
|
|
4281
|
+
if (contextRequestContext && defaultOptions2?.requestContext || contextRequestContext && params.requestContext || defaultOptions2?.requestContext && params.requestContext) {
|
|
4282
|
+
mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
|
|
1113
4283
|
}
|
|
1114
4284
|
if (!agentToUse) {
|
|
1115
4285
|
throw new Error("Agent ID is required");
|
|
1116
4286
|
}
|
|
1117
|
-
const
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
}
|
|
1130
|
-
const uiMessageStream = createUIMessageStream({
|
|
1131
|
-
originalMessages: messages,
|
|
1132
|
-
execute: async ({ writer }) => {
|
|
1133
|
-
for await (const part of toAISdkV5Stream(result, { from: "agent", lastMessageId })) {
|
|
1134
|
-
writer.write(part);
|
|
1135
|
-
}
|
|
1136
|
-
}
|
|
4287
|
+
const uiMessageStream = await handleChatStream({
|
|
4288
|
+
mastra,
|
|
4289
|
+
agentId: agentToUse,
|
|
4290
|
+
params: {
|
|
4291
|
+
...params,
|
|
4292
|
+
requestContext: effectiveRequestContext
|
|
4293
|
+
},
|
|
4294
|
+
defaultOptions: defaultOptions2,
|
|
4295
|
+
sendStart,
|
|
4296
|
+
sendFinish,
|
|
4297
|
+
sendReasoning,
|
|
4298
|
+
sendSources
|
|
1137
4299
|
});
|
|
1138
4300
|
return createUIMessageStreamResponse({
|
|
1139
4301
|
stream: uiMessageStream
|
|
@@ -1141,9 +4303,31 @@ function chatRoute({
|
|
|
1141
4303
|
}
|
|
1142
4304
|
});
|
|
1143
4305
|
}
|
|
4306
|
+
async function handleWorkflowStream({
|
|
4307
|
+
mastra,
|
|
4308
|
+
workflowId,
|
|
4309
|
+
params,
|
|
4310
|
+
includeTextStreamParts = true
|
|
4311
|
+
}) {
|
|
4312
|
+
const { runId, resourceId, inputData, resumeData, requestContext, ...rest } = params;
|
|
4313
|
+
const workflowObj = mastra.getWorkflowById(workflowId);
|
|
4314
|
+
if (!workflowObj) {
|
|
4315
|
+
throw new Error(`Workflow ${workflowId} not found`);
|
|
4316
|
+
}
|
|
4317
|
+
const run = await workflowObj.createRun({ runId, resourceId, ...rest });
|
|
4318
|
+
const stream = resumeData ? run.resumeStream({ resumeData, ...rest, requestContext }) : run.stream({ inputData, ...rest, requestContext });
|
|
4319
|
+
return createUIMessageStream({
|
|
4320
|
+
execute: async ({ writer }) => {
|
|
4321
|
+
for await (const part of toAISdkV5Stream(stream, { from: "workflow", includeTextStreamParts })) {
|
|
4322
|
+
writer.write(part);
|
|
4323
|
+
}
|
|
4324
|
+
}
|
|
4325
|
+
});
|
|
4326
|
+
}
|
|
1144
4327
|
function workflowRoute({
|
|
1145
4328
|
path = "/api/workflows/:workflowId/stream",
|
|
1146
|
-
workflow
|
|
4329
|
+
workflow,
|
|
4330
|
+
includeTextStreamParts = true
|
|
1147
4331
|
}) {
|
|
1148
4332
|
if (!workflow && !path.includes("/:workflowId")) {
|
|
1149
4333
|
throw new Error("Path must include :workflowId to route to the correct workflow or pass the workflow explicitly");
|
|
@@ -1170,9 +4354,13 @@ function workflowRoute({
|
|
|
1170
4354
|
schema: {
|
|
1171
4355
|
type: "object",
|
|
1172
4356
|
properties: {
|
|
4357
|
+
runId: { type: "string" },
|
|
4358
|
+
resourceId: { type: "string" },
|
|
1173
4359
|
inputData: { type: "object", additionalProperties: true },
|
|
4360
|
+
resumeData: { type: "object", additionalProperties: true },
|
|
1174
4361
|
requestContext: { type: "object", additionalProperties: true },
|
|
1175
|
-
tracingOptions: { type: "object", additionalProperties: true }
|
|
4362
|
+
tracingOptions: { type: "object", additionalProperties: true },
|
|
4363
|
+
step: { type: "string" }
|
|
1176
4364
|
}
|
|
1177
4365
|
}
|
|
1178
4366
|
}
|
|
@@ -1190,8 +4378,9 @@ function workflowRoute({
|
|
|
1190
4378
|
}
|
|
1191
4379
|
},
|
|
1192
4380
|
handler: async (c) => {
|
|
1193
|
-
const
|
|
4381
|
+
const params = await c.req.json();
|
|
1194
4382
|
const mastra = c.get("mastra");
|
|
4383
|
+
const contextRequestContext = c.get("requestContext");
|
|
1195
4384
|
let workflowToUse = workflow;
|
|
1196
4385
|
if (!workflow) {
|
|
1197
4386
|
const workflowId = c.req.param("workflowId");
|
|
@@ -1205,27 +4394,51 @@ function workflowRoute({
|
|
|
1205
4394
|
if (!workflowToUse) {
|
|
1206
4395
|
throw new Error("Workflow ID is required");
|
|
1207
4396
|
}
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
4397
|
+
if (contextRequestContext && params.requestContext) {
|
|
4398
|
+
mastra.getLogger()?.warn(
|
|
4399
|
+
`"requestContext" from the request body will be ignored because "requestContext" is already set in the route options.`
|
|
4400
|
+
);
|
|
1211
4401
|
}
|
|
1212
|
-
const
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
4402
|
+
const uiMessageStream = await handleWorkflowStream({
|
|
4403
|
+
mastra,
|
|
4404
|
+
workflowId: workflowToUse,
|
|
4405
|
+
params: {
|
|
4406
|
+
...params,
|
|
4407
|
+
requestContext: contextRequestContext || params.requestContext
|
|
4408
|
+
},
|
|
4409
|
+
includeTextStreamParts
|
|
1220
4410
|
});
|
|
1221
4411
|
return createUIMessageStreamResponse({ stream: uiMessageStream });
|
|
1222
4412
|
}
|
|
1223
4413
|
});
|
|
1224
4414
|
}
|
|
4415
|
+
async function handleNetworkStream({
|
|
4416
|
+
mastra,
|
|
4417
|
+
agentId,
|
|
4418
|
+
params,
|
|
4419
|
+
defaultOptions: defaultOptions2
|
|
4420
|
+
}) {
|
|
4421
|
+
const { messages, ...rest } = params;
|
|
4422
|
+
const agentObj = mastra.getAgentById(agentId);
|
|
4423
|
+
if (!agentObj) {
|
|
4424
|
+
throw new Error(`Agent ${agentId} not found`);
|
|
4425
|
+
}
|
|
4426
|
+
const result = await agentObj.network(messages, {
|
|
4427
|
+
...defaultOptions2,
|
|
4428
|
+
...rest
|
|
4429
|
+
});
|
|
4430
|
+
return createUIMessageStream({
|
|
4431
|
+
execute: async ({ writer }) => {
|
|
4432
|
+
for await (const part of toAISdkV5Stream(result, { from: "network" })) {
|
|
4433
|
+
writer.write(part);
|
|
4434
|
+
}
|
|
4435
|
+
}
|
|
4436
|
+
});
|
|
4437
|
+
}
|
|
1225
4438
|
function networkRoute({
|
|
1226
4439
|
path = "/network/:agentId",
|
|
1227
4440
|
agent,
|
|
1228
|
-
defaultOptions
|
|
4441
|
+
defaultOptions: defaultOptions2
|
|
1229
4442
|
}) {
|
|
1230
4443
|
if (!agent && !path.includes("/:agentId")) {
|
|
1231
4444
|
throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
|
|
@@ -1282,8 +4495,9 @@ function networkRoute({
|
|
|
1282
4495
|
}
|
|
1283
4496
|
},
|
|
1284
4497
|
handler: async (c) => {
|
|
1285
|
-
const
|
|
4498
|
+
const params = await c.req.json();
|
|
1286
4499
|
const mastra = c.get("mastra");
|
|
4500
|
+
const contextRequestContext = c.get("requestContext");
|
|
1287
4501
|
let agentToUse = agent;
|
|
1288
4502
|
if (!agent) {
|
|
1289
4503
|
const agentId = c.req.param("agentId");
|
|
@@ -1294,28 +4508,475 @@ function networkRoute({
|
|
|
1294
4508
|
`Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
|
|
1295
4509
|
);
|
|
1296
4510
|
}
|
|
4511
|
+
const effectiveRequestContext = contextRequestContext || defaultOptions2?.requestContext || params.requestContext;
|
|
4512
|
+
if (contextRequestContext && defaultOptions2?.requestContext || contextRequestContext && params.requestContext || defaultOptions2?.requestContext && params.requestContext) {
|
|
4513
|
+
mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
|
|
4514
|
+
}
|
|
1297
4515
|
if (!agentToUse) {
|
|
1298
4516
|
throw new Error("Agent ID is required");
|
|
1299
4517
|
}
|
|
1300
|
-
const
|
|
1301
|
-
|
|
1302
|
-
|
|
4518
|
+
const uiMessageStream = await handleNetworkStream({
|
|
4519
|
+
mastra,
|
|
4520
|
+
agentId: agentToUse,
|
|
4521
|
+
params: {
|
|
4522
|
+
...params,
|
|
4523
|
+
requestContext: effectiveRequestContext
|
|
4524
|
+
},
|
|
4525
|
+
defaultOptions: defaultOptions2
|
|
4526
|
+
});
|
|
4527
|
+
return createUIMessageStreamResponse({ stream: uiMessageStream });
|
|
4528
|
+
}
|
|
4529
|
+
});
|
|
4530
|
+
}
|
|
4531
|
+
function withMastra(model, options = {}) {
|
|
4532
|
+
const { memory, inputProcessors = [], outputProcessors = [] } = options;
|
|
4533
|
+
const allInputProcessors = [...inputProcessors];
|
|
4534
|
+
const allOutputProcessors = [...outputProcessors];
|
|
4535
|
+
if (memory) {
|
|
4536
|
+
const { storage, lastMessages, semanticRecall, workingMemory } = memory;
|
|
4537
|
+
const isWorkingMemoryEnabled = typeof workingMemory === "object" && workingMemory.enabled !== false;
|
|
4538
|
+
if (isWorkingMemoryEnabled && typeof workingMemory === "object") {
|
|
4539
|
+
let template;
|
|
4540
|
+
if (workingMemory.template) {
|
|
4541
|
+
template = {
|
|
4542
|
+
format: "markdown",
|
|
4543
|
+
content: workingMemory.template
|
|
4544
|
+
};
|
|
1303
4545
|
}
|
|
1304
|
-
const
|
|
1305
|
-
|
|
1306
|
-
|
|
4546
|
+
const workingMemoryProcessor = new WorkingMemory({
|
|
4547
|
+
storage,
|
|
4548
|
+
template,
|
|
4549
|
+
scope: workingMemory.scope,
|
|
4550
|
+
useVNext: "version" in workingMemory && workingMemory.version === "vnext"
|
|
4551
|
+
});
|
|
4552
|
+
allInputProcessors.push(workingMemoryProcessor);
|
|
4553
|
+
}
|
|
4554
|
+
if (lastMessages !== false && lastMessages !== void 0) {
|
|
4555
|
+
const messageHistory = new MessageHistory({
|
|
4556
|
+
storage,
|
|
4557
|
+
lastMessages: typeof lastMessages === "number" ? lastMessages : void 0
|
|
4558
|
+
});
|
|
4559
|
+
allInputProcessors.push(messageHistory);
|
|
4560
|
+
allOutputProcessors.push(messageHistory);
|
|
4561
|
+
}
|
|
4562
|
+
if (semanticRecall) {
|
|
4563
|
+
const { vector, embedder, indexName, ...semanticConfig } = semanticRecall;
|
|
4564
|
+
const semanticRecallProcessor = new SemanticRecall({
|
|
4565
|
+
storage,
|
|
4566
|
+
vector,
|
|
4567
|
+
embedder,
|
|
4568
|
+
indexName: indexName || "memory_messages",
|
|
4569
|
+
...semanticConfig
|
|
4570
|
+
});
|
|
4571
|
+
allInputProcessors.push(semanticRecallProcessor);
|
|
4572
|
+
allOutputProcessors.push(semanticRecallProcessor);
|
|
4573
|
+
}
|
|
4574
|
+
}
|
|
4575
|
+
return wrapLanguageModel({
|
|
4576
|
+
model,
|
|
4577
|
+
middleware: createProcessorMiddleware({
|
|
4578
|
+
inputProcessors: allInputProcessors,
|
|
4579
|
+
outputProcessors: allOutputProcessors,
|
|
4580
|
+
memory: memory ? {
|
|
4581
|
+
threadId: memory.threadId,
|
|
4582
|
+
resourceId: memory.resourceId
|
|
4583
|
+
} : void 0
|
|
4584
|
+
})
|
|
4585
|
+
});
|
|
4586
|
+
}
|
|
4587
|
+
function createProcessorMiddleware(options) {
|
|
4588
|
+
const { inputProcessors = [], outputProcessors = [], memory } = options;
|
|
4589
|
+
const requestContext = new RequestContext();
|
|
4590
|
+
if (memory) {
|
|
4591
|
+
requestContext.set("MastraMemory", {
|
|
4592
|
+
thread: memory.threadId ? { id: memory.threadId } : void 0,
|
|
4593
|
+
resourceId: memory.resourceId,
|
|
4594
|
+
memoryConfig: memory.config
|
|
4595
|
+
});
|
|
4596
|
+
}
|
|
4597
|
+
return {
|
|
4598
|
+
middlewareVersion: "v2",
|
|
4599
|
+
/**
|
|
4600
|
+
* Transform params runs input processors (processInput)
|
|
4601
|
+
*/
|
|
4602
|
+
async transformParams({ params }) {
|
|
4603
|
+
const messageList = new MessageList({
|
|
4604
|
+
threadId: memory?.threadId,
|
|
4605
|
+
resourceId: memory?.resourceId
|
|
1307
4606
|
});
|
|
1308
|
-
const
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
4607
|
+
for (const msg of params.prompt) {
|
|
4608
|
+
if (msg.role === "system") {
|
|
4609
|
+
messageList.addSystem(msg.content);
|
|
4610
|
+
} else {
|
|
4611
|
+
messageList.add(msg, "input");
|
|
4612
|
+
}
|
|
4613
|
+
}
|
|
4614
|
+
for (const processor of inputProcessors) {
|
|
4615
|
+
if (processor.processInput) {
|
|
4616
|
+
try {
|
|
4617
|
+
await processor.processInput({
|
|
4618
|
+
messages: messageList.get.input.db(),
|
|
4619
|
+
systemMessages: messageList.getAllSystemMessages(),
|
|
4620
|
+
messageList,
|
|
4621
|
+
requestContext,
|
|
4622
|
+
abort: (reason) => {
|
|
4623
|
+
throw new TripWire(reason || "Aborted by processor");
|
|
4624
|
+
}
|
|
4625
|
+
});
|
|
4626
|
+
} catch (error) {
|
|
4627
|
+
if (error instanceof TripWire) {
|
|
4628
|
+
return {
|
|
4629
|
+
...params,
|
|
4630
|
+
providerOptions: {
|
|
4631
|
+
...params.providerOptions,
|
|
4632
|
+
mastraProcessors: {
|
|
4633
|
+
tripwire: true,
|
|
4634
|
+
reason: error.message
|
|
4635
|
+
}
|
|
4636
|
+
}
|
|
4637
|
+
};
|
|
4638
|
+
}
|
|
4639
|
+
throw error;
|
|
1312
4640
|
}
|
|
1313
4641
|
}
|
|
4642
|
+
}
|
|
4643
|
+
const newPrompt = messageList.get.all.aiV5.prompt().map(aiV5ModelMessageToV2PromptMessage);
|
|
4644
|
+
return {
|
|
4645
|
+
...params,
|
|
4646
|
+
prompt: newPrompt
|
|
4647
|
+
};
|
|
4648
|
+
},
|
|
4649
|
+
/**
|
|
4650
|
+
* Wrap generate for non-streaming output processing
|
|
4651
|
+
*/
|
|
4652
|
+
async wrapGenerate({ doGenerate, params }) {
|
|
4653
|
+
const processorState = params.providerOptions?.mastraProcessors;
|
|
4654
|
+
if (processorState?.tripwire) {
|
|
4655
|
+
const reason = processorState.reason || "Blocked by processor";
|
|
4656
|
+
return {
|
|
4657
|
+
content: [{ type: "text", text: reason }],
|
|
4658
|
+
finishReason: "stop",
|
|
4659
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
4660
|
+
warnings: [{ type: "other", message: `Tripwire: ${reason}` }]
|
|
4661
|
+
};
|
|
4662
|
+
}
|
|
4663
|
+
const result = await doGenerate();
|
|
4664
|
+
if (!outputProcessors.length) return result;
|
|
4665
|
+
const messageList = new MessageList({
|
|
4666
|
+
threadId: memory?.threadId,
|
|
4667
|
+
resourceId: memory?.resourceId
|
|
1314
4668
|
});
|
|
1315
|
-
|
|
4669
|
+
for (const msg of params.prompt) {
|
|
4670
|
+
if (msg.role === "system") {
|
|
4671
|
+
messageList.addSystem(msg.content);
|
|
4672
|
+
} else {
|
|
4673
|
+
messageList.add(msg, "input");
|
|
4674
|
+
}
|
|
4675
|
+
}
|
|
4676
|
+
const textContent = result.content.filter((c) => c.type === "text").map((c) => c.text).join("");
|
|
4677
|
+
const responseMessage = {
|
|
4678
|
+
id: crypto.randomUUID(),
|
|
4679
|
+
role: "assistant",
|
|
4680
|
+
content: {
|
|
4681
|
+
format: 2,
|
|
4682
|
+
parts: [{ type: "text", text: textContent }]
|
|
4683
|
+
},
|
|
4684
|
+
createdAt: /* @__PURE__ */ new Date(),
|
|
4685
|
+
...memory?.threadId && { threadId: memory.threadId },
|
|
4686
|
+
...memory?.resourceId && { resourceId: memory.resourceId }
|
|
4687
|
+
};
|
|
4688
|
+
messageList.add(responseMessage, "response");
|
|
4689
|
+
for (const processor of outputProcessors) {
|
|
4690
|
+
if (processor.processOutputResult) {
|
|
4691
|
+
try {
|
|
4692
|
+
await processor.processOutputResult({
|
|
4693
|
+
messages: messageList.get.all.db(),
|
|
4694
|
+
messageList,
|
|
4695
|
+
requestContext,
|
|
4696
|
+
abort: (reason) => {
|
|
4697
|
+
throw new TripWire(reason || "Aborted by processor");
|
|
4698
|
+
}
|
|
4699
|
+
});
|
|
4700
|
+
} catch (error) {
|
|
4701
|
+
if (error instanceof TripWire) {
|
|
4702
|
+
return {
|
|
4703
|
+
content: [{ type: "text", text: error.message }],
|
|
4704
|
+
finishReason: "stop",
|
|
4705
|
+
usage: result.usage,
|
|
4706
|
+
warnings: [{ type: "other", message: `Output blocked: ${error.message}` }]
|
|
4707
|
+
};
|
|
4708
|
+
}
|
|
4709
|
+
throw error;
|
|
4710
|
+
}
|
|
4711
|
+
}
|
|
4712
|
+
}
|
|
4713
|
+
const processedText = messageList.get.response.db().map((m) => extractTextFromMastraMessage(m)).join("");
|
|
4714
|
+
return {
|
|
4715
|
+
...result,
|
|
4716
|
+
content: [{ type: "text", text: processedText }]
|
|
4717
|
+
};
|
|
4718
|
+
},
|
|
4719
|
+
/**
|
|
4720
|
+
* Wrap stream for streaming output processing
|
|
4721
|
+
*/
|
|
4722
|
+
async wrapStream({ doStream, params }) {
|
|
4723
|
+
const processorState = params.providerOptions?.mastraProcessors;
|
|
4724
|
+
if (processorState?.tripwire) {
|
|
4725
|
+
const reason = processorState.reason || "Blocked by processor";
|
|
4726
|
+
return {
|
|
4727
|
+
stream: createBlockedStream(reason)
|
|
4728
|
+
};
|
|
4729
|
+
}
|
|
4730
|
+
const { stream, ...rest } = await doStream();
|
|
4731
|
+
if (!outputProcessors.length) return { stream, ...rest };
|
|
4732
|
+
const processorStates = /* @__PURE__ */ new Map();
|
|
4733
|
+
const runId = crypto.randomUUID();
|
|
4734
|
+
const transformedStream = stream.pipeThrough(
|
|
4735
|
+
new TransformStream({
|
|
4736
|
+
async transform(chunk, controller) {
|
|
4737
|
+
let mastraChunk = convertFullStreamChunkToMastra(
|
|
4738
|
+
chunk,
|
|
4739
|
+
{ runId }
|
|
4740
|
+
);
|
|
4741
|
+
if (!mastraChunk) {
|
|
4742
|
+
controller.enqueue(chunk);
|
|
4743
|
+
return;
|
|
4744
|
+
}
|
|
4745
|
+
for (const processor of outputProcessors) {
|
|
4746
|
+
if (processor.processOutputStream && mastraChunk) {
|
|
4747
|
+
let state = processorStates.get(processor.id);
|
|
4748
|
+
if (!state) {
|
|
4749
|
+
state = { streamParts: [], customState: {} };
|
|
4750
|
+
processorStates.set(processor.id, state);
|
|
4751
|
+
}
|
|
4752
|
+
state.streamParts.push(mastraChunk);
|
|
4753
|
+
try {
|
|
4754
|
+
const result = await processor.processOutputStream({
|
|
4755
|
+
part: mastraChunk,
|
|
4756
|
+
streamParts: state.streamParts,
|
|
4757
|
+
state: state.customState,
|
|
4758
|
+
requestContext,
|
|
4759
|
+
abort: (reason) => {
|
|
4760
|
+
throw new TripWire(reason || "Aborted by processor");
|
|
4761
|
+
}
|
|
4762
|
+
});
|
|
4763
|
+
if (result === null || result === void 0) {
|
|
4764
|
+
mastraChunk = void 0;
|
|
4765
|
+
} else {
|
|
4766
|
+
mastraChunk = result;
|
|
4767
|
+
}
|
|
4768
|
+
} catch (error) {
|
|
4769
|
+
if (error instanceof TripWire) {
|
|
4770
|
+
controller.enqueue({
|
|
4771
|
+
type: "error",
|
|
4772
|
+
error: new Error(error.message)
|
|
4773
|
+
});
|
|
4774
|
+
controller.terminate();
|
|
4775
|
+
return;
|
|
4776
|
+
}
|
|
4777
|
+
throw error;
|
|
4778
|
+
}
|
|
4779
|
+
}
|
|
4780
|
+
}
|
|
4781
|
+
if (mastraChunk) {
|
|
4782
|
+
const aiChunk = convertMastraChunkToAISDKStreamPart(mastraChunk);
|
|
4783
|
+
if (aiChunk) {
|
|
4784
|
+
controller.enqueue(aiChunk);
|
|
4785
|
+
}
|
|
4786
|
+
}
|
|
4787
|
+
}
|
|
4788
|
+
})
|
|
4789
|
+
);
|
|
4790
|
+
return { stream: transformedStream, ...rest };
|
|
4791
|
+
}
|
|
4792
|
+
};
|
|
4793
|
+
}
|
|
4794
|
+
function createBlockedStream(reason) {
|
|
4795
|
+
return new ReadableStream({
|
|
4796
|
+
start(controller) {
|
|
4797
|
+
const id = crypto.randomUUID();
|
|
4798
|
+
controller.enqueue({
|
|
4799
|
+
type: "text-start",
|
|
4800
|
+
id
|
|
4801
|
+
});
|
|
4802
|
+
controller.enqueue({
|
|
4803
|
+
type: "text-delta",
|
|
4804
|
+
id,
|
|
4805
|
+
delta: reason
|
|
4806
|
+
});
|
|
4807
|
+
controller.enqueue({
|
|
4808
|
+
type: "text-end",
|
|
4809
|
+
id
|
|
4810
|
+
});
|
|
4811
|
+
controller.enqueue({
|
|
4812
|
+
type: "finish",
|
|
4813
|
+
finishReason: "stop",
|
|
4814
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }
|
|
4815
|
+
});
|
|
4816
|
+
controller.close();
|
|
1316
4817
|
}
|
|
1317
4818
|
});
|
|
1318
4819
|
}
|
|
4820
|
+
function extractTextFromMastraMessage(msg) {
|
|
4821
|
+
const content = msg.content;
|
|
4822
|
+
if (typeof content === "string") {
|
|
4823
|
+
return content;
|
|
4824
|
+
}
|
|
4825
|
+
if (content?.parts) {
|
|
4826
|
+
return content.parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join("");
|
|
4827
|
+
}
|
|
4828
|
+
return "";
|
|
4829
|
+
}
|
|
4830
|
+
function convertMastraChunkToAISDKStreamPart(chunk) {
|
|
4831
|
+
switch (chunk.type) {
|
|
4832
|
+
// Text streaming
|
|
4833
|
+
case "text-start":
|
|
4834
|
+
return {
|
|
4835
|
+
type: "text-start",
|
|
4836
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4837
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4838
|
+
};
|
|
4839
|
+
case "text-delta":
|
|
4840
|
+
return {
|
|
4841
|
+
type: "text-delta",
|
|
4842
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4843
|
+
delta: chunk.payload.text,
|
|
4844
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4845
|
+
};
|
|
4846
|
+
case "text-end":
|
|
4847
|
+
return {
|
|
4848
|
+
type: "text-end",
|
|
4849
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4850
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4851
|
+
};
|
|
4852
|
+
// Reasoning streaming
|
|
4853
|
+
case "reasoning-start":
|
|
4854
|
+
return {
|
|
4855
|
+
type: "reasoning-start",
|
|
4856
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4857
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4858
|
+
};
|
|
4859
|
+
case "reasoning-delta":
|
|
4860
|
+
return {
|
|
4861
|
+
type: "reasoning-delta",
|
|
4862
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4863
|
+
delta: chunk.payload.text,
|
|
4864
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4865
|
+
};
|
|
4866
|
+
case "reasoning-end":
|
|
4867
|
+
return {
|
|
4868
|
+
type: "reasoning-end",
|
|
4869
|
+
id: chunk.payload.id || crypto.randomUUID(),
|
|
4870
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4871
|
+
};
|
|
4872
|
+
// Tool call (complete)
|
|
4873
|
+
case "tool-call":
|
|
4874
|
+
return {
|
|
4875
|
+
type: "tool-call",
|
|
4876
|
+
toolCallId: chunk.payload.toolCallId,
|
|
4877
|
+
toolName: chunk.payload.toolName,
|
|
4878
|
+
input: JSON.stringify(chunk.payload.args),
|
|
4879
|
+
providerExecuted: chunk.payload.providerExecuted,
|
|
4880
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4881
|
+
};
|
|
4882
|
+
// Tool call input streaming
|
|
4883
|
+
case "tool-call-input-streaming-start":
|
|
4884
|
+
return {
|
|
4885
|
+
type: "tool-input-start",
|
|
4886
|
+
id: chunk.payload.toolCallId,
|
|
4887
|
+
toolName: chunk.payload.toolName,
|
|
4888
|
+
providerExecuted: chunk.payload.providerExecuted,
|
|
4889
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4890
|
+
};
|
|
4891
|
+
case "tool-call-delta":
|
|
4892
|
+
return {
|
|
4893
|
+
type: "tool-input-delta",
|
|
4894
|
+
id: chunk.payload.toolCallId,
|
|
4895
|
+
delta: chunk.payload.argsTextDelta,
|
|
4896
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4897
|
+
};
|
|
4898
|
+
case "tool-call-input-streaming-end":
|
|
4899
|
+
return {
|
|
4900
|
+
type: "tool-input-end",
|
|
4901
|
+
id: chunk.payload.toolCallId,
|
|
4902
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4903
|
+
};
|
|
4904
|
+
// Tool result
|
|
4905
|
+
case "tool-result":
|
|
4906
|
+
return {
|
|
4907
|
+
type: "tool-result",
|
|
4908
|
+
toolCallId: chunk.payload.toolCallId,
|
|
4909
|
+
toolName: chunk.payload.toolName,
|
|
4910
|
+
result: { type: "json", value: chunk.payload.result },
|
|
4911
|
+
isError: chunk.payload.isError,
|
|
4912
|
+
providerExecuted: chunk.payload.providerExecuted,
|
|
4913
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4914
|
+
};
|
|
4915
|
+
// Source (citations)
|
|
4916
|
+
case "source":
|
|
4917
|
+
if (chunk.payload.sourceType === "url") {
|
|
4918
|
+
return {
|
|
4919
|
+
type: "source",
|
|
4920
|
+
sourceType: "url",
|
|
4921
|
+
id: chunk.payload.id,
|
|
4922
|
+
url: chunk.payload.url,
|
|
4923
|
+
title: chunk.payload.title,
|
|
4924
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4925
|
+
};
|
|
4926
|
+
} else {
|
|
4927
|
+
return {
|
|
4928
|
+
type: "source",
|
|
4929
|
+
sourceType: "document",
|
|
4930
|
+
id: chunk.payload.id,
|
|
4931
|
+
mediaType: chunk.payload.mimeType,
|
|
4932
|
+
title: chunk.payload.title,
|
|
4933
|
+
filename: chunk.payload.filename,
|
|
4934
|
+
providerMetadata: chunk.payload.providerMetadata
|
|
4935
|
+
};
|
|
4936
|
+
}
|
|
4937
|
+
// File output
|
|
4938
|
+
case "file":
|
|
4939
|
+
return {
|
|
4940
|
+
type: "file",
|
|
4941
|
+
data: chunk.payload.data || chunk.payload.base64,
|
|
4942
|
+
mediaType: chunk.payload.mimeType
|
|
4943
|
+
};
|
|
4944
|
+
// Response metadata
|
|
4945
|
+
case "response-metadata":
|
|
4946
|
+
return {
|
|
4947
|
+
type: "response-metadata",
|
|
4948
|
+
...chunk.payload
|
|
4949
|
+
};
|
|
4950
|
+
// Raw provider data
|
|
4951
|
+
case "raw":
|
|
4952
|
+
return {
|
|
4953
|
+
type: "raw",
|
|
4954
|
+
rawValue: chunk.payload
|
|
4955
|
+
};
|
|
4956
|
+
// Finish
|
|
4957
|
+
case "finish": {
|
|
4958
|
+
const usage = chunk.payload.output?.usage;
|
|
4959
|
+
return {
|
|
4960
|
+
type: "finish",
|
|
4961
|
+
finishReason: toAISDKFinishReason(chunk.payload.stepResult?.reason || "stop"),
|
|
4962
|
+
usage: usage ? {
|
|
4963
|
+
inputTokens: usage.inputTokens || 0,
|
|
4964
|
+
outputTokens: usage.outputTokens || 0,
|
|
4965
|
+
totalTokens: usage.totalTokens || 0
|
|
4966
|
+
} : { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
4967
|
+
providerMetadata: chunk.payload.metadata?.providerMetadata
|
|
4968
|
+
};
|
|
4969
|
+
}
|
|
4970
|
+
// Error
|
|
4971
|
+
case "error":
|
|
4972
|
+
return {
|
|
4973
|
+
type: "error",
|
|
4974
|
+
error: chunk.payload.error || chunk.payload
|
|
4975
|
+
};
|
|
4976
|
+
default:
|
|
4977
|
+
return null;
|
|
4978
|
+
}
|
|
4979
|
+
}
|
|
1319
4980
|
|
|
1320
4981
|
// src/to-ai-sdk-format.ts
|
|
1321
4982
|
function toAISdkFormat() {
|
|
@@ -1324,6 +4985,6 @@ function toAISdkFormat() {
|
|
|
1324
4985
|
);
|
|
1325
4986
|
}
|
|
1326
4987
|
|
|
1327
|
-
export { chatRoute, networkRoute, toAISdkFormat, toAISdkV5Stream as toAISdkStream, workflowRoute };
|
|
4988
|
+
export { chatRoute, handleChatStream, handleNetworkStream, handleWorkflowStream, networkRoute, toAISdkFormat, toAISdkV5Stream as toAISdkStream, withMastra, workflowRoute };
|
|
1328
4989
|
//# sourceMappingURL=index.js.map
|
|
1329
4990
|
//# sourceMappingURL=index.js.map
|