@mastra/ai-sdk 1.11.3 → 1.12.0-alpha.0
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/dist/_types/{@internal_ai-sdk-v5 → @internal_ai-sdk-v5@0.0.95}/dist/index.d.ts +2 -2
- package/dist/_types/{@internal_ai-v6 → @internal_ai-v6@0.0.95}/dist/index.d.ts +99 -18
- package/dist/_types/{@internal_ai-v7 → @internal_ai-v7@0.0.95}/dist/index.d.ts +297 -94
- package/dist/chat-route.d.ts +21 -5
- package/dist/chat-route.d.ts.map +1 -1
- package/dist/convert-streams.d.ts +3 -3
- package/dist/docs/SKILL.md +49 -0
- package/dist/docs/assets/SOURCE_MAP.json +77 -0
- package/dist/docs/references/docs-guides-streaming.md +341 -0
- package/dist/docs/references/docs-memory-message-history.md +424 -0
- package/dist/docs/references/docs-server-custom-api-routes.md +379 -0
- package/dist/docs/references/integrations-agentic-ui-ai-sdk-ui.md +1700 -0
- package/dist/docs/references/reference-ai-sdk-chat-route.md +139 -0
- package/dist/docs/references/reference-ai-sdk-handle-chat-stream.md +101 -0
- package/dist/docs/references/reference-ai-sdk-handle-network-stream.md +49 -0
- package/dist/docs/references/reference-ai-sdk-handle-workflow-stream.md +63 -0
- package/dist/docs/references/reference-ai-sdk-network-route.md +86 -0
- package/dist/docs/references/reference-ai-sdk-overview.md +144 -0
- package/dist/docs/references/reference-ai-sdk-to-ai-sdk-messages.md +115 -0
- package/dist/docs/references/reference-ai-sdk-to-ai-sdk-stream.md +286 -0
- package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v4-messages.md +83 -0
- package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v5-messages.md +80 -0
- package/dist/docs/references/reference-ai-sdk-with-mastra.md +67 -0
- package/dist/docs/references/reference-ai-sdk-with-sse-heartbeat.md +49 -0
- package/dist/docs/references/reference-ai-sdk-workflow-route.md +87 -0
- package/dist/docs/references/reference-ai-sdk-workflow-snapshot-to-stream.md +55 -0
- package/dist/docs/references/reference-client-js-agents.md +1112 -0
- package/dist/docs/references/reference-memory-recall.md +169 -0
- package/dist/docs/references/reference-streaming-agents-stream.md +496 -0
- package/dist/docs/references/reference-streaming-smoothStream.md +137 -0
- package/dist/helpers.d.ts +2 -2
- package/dist/index.cjs +297 -128
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +299 -130
- package/dist/index.js.map +1 -1
- package/dist/middleware.d.ts +2 -2
- package/dist/public-types.d.ts +3 -3
- package/dist/transformers.d.ts +28 -23
- package/dist/transformers.d.ts.map +1 -1
- package/package.json +19 -18
- /package/dist/_types/{@ai-sdk_provider → @ai-sdk_provider@2.0.5}/dist/index.d.ts +0 -0
- /package/dist/_types/{@ai-sdk_provider → @ai-sdk_provider@2.0.5}/package.json +0 -0
- /package/dist/_types/{@internal_ai-sdk-v5 → @internal_ai-sdk-v5@0.0.95}/package.json +0 -0
- /package/dist/_types/{@internal_ai-v6 → @internal_ai-v6@0.0.95}/package.json +0 -0
- /package/dist/_types/{@internal_ai-v7 → @internal_ai-v7@0.0.95}/package.json +0 -0
- /package/dist/_types/{@types_json-schema → @types_json-schema@7.0.15}/index.d.ts +0 -0
- /package/dist/_types/{@types_json-schema → @types_json-schema@7.0.15}/package.json +0 -0
package/dist/index.cjs
CHANGED
|
@@ -24,14 +24,15 @@ let zod_v4 = require("zod/v4");
|
|
|
24
24
|
zod_v4 = __toESM(zod_v4, 1);
|
|
25
25
|
let zod_v3 = require("zod/v3");
|
|
26
26
|
let zod_v4_core = require("zod/v4/core");
|
|
27
|
+
let _mastra_core_memory = require("@mastra/core/memory");
|
|
28
|
+
let _mastra_core_request_context = require("@mastra/core/request-context");
|
|
27
29
|
let _mastra_core_server = require("@mastra/core/server");
|
|
28
30
|
let _mastra_core_stream = require("@mastra/core/stream");
|
|
29
31
|
let stream_web = require("stream/web");
|
|
30
|
-
let _mastra_core_request_context = require("@mastra/core/request-context");
|
|
31
32
|
let _mastra_core_agent = require("@mastra/core/agent");
|
|
32
33
|
let _mastra_core_di = require("@mastra/core/di");
|
|
33
34
|
let _mastra_core_processors = require("@mastra/core/processors");
|
|
34
|
-
// ../../packages/_vendored/ai_v5/dist/dist-
|
|
35
|
+
// ../../packages/_vendored/ai_v5/dist/dist-BYnbJEqC.js
|
|
35
36
|
var marker$1$4 = "vercel.ai.error";
|
|
36
37
|
var symbol$1$4 = Symbol.for(marker$1$4);
|
|
37
38
|
var _a$1$4;
|
|
@@ -1241,6 +1242,20 @@ function asSchema$2(schema) {
|
|
|
1241
1242
|
}) : isSchema$2(schema) ? schema : typeof schema === "function" ? schema() : zodSchema$2(schema);
|
|
1242
1243
|
}
|
|
1243
1244
|
var { btoa: btoa$3, atob: atob$6 } = globalThis;
|
|
1245
|
+
var typedArrayTag$2 = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
|
|
1246
|
+
var arrayBufferByteLength$2 = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
|
|
1247
|
+
function isUint8Array$2(value) {
|
|
1248
|
+
return ArrayBuffer.isView(value) && typedArrayTag$2.call(value) === "Uint8Array";
|
|
1249
|
+
}
|
|
1250
|
+
function isArrayBuffer$2(value) {
|
|
1251
|
+
if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
|
|
1252
|
+
try {
|
|
1253
|
+
arrayBufferByteLength$2.call(value);
|
|
1254
|
+
return true;
|
|
1255
|
+
} catch (e) {
|
|
1256
|
+
return false;
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1244
1259
|
// ../../packages/_vendored/ai_v5/dist/index.js
|
|
1245
1260
|
/** only globals that common to node and browsers are allowed */
|
|
1246
1261
|
var _globalThis = typeof globalThis === "object" ? globalThis : global;
|
|
@@ -2058,8 +2073,8 @@ var NoObjectGeneratedError$1 = class extends AISDKError$2 {
|
|
|
2058
2073
|
_a7$2 = symbol7$2;
|
|
2059
2074
|
var dataContentSchema$1 = zod_v4.z.union([
|
|
2060
2075
|
zod_v4.z.string(),
|
|
2061
|
-
zod_v4.z.
|
|
2062
|
-
zod_v4.z.
|
|
2076
|
+
zod_v4.z.custom(isUint8Array$2, { message: "Must be a Uint8Array" }),
|
|
2077
|
+
zod_v4.z.custom(isArrayBuffer$2, { message: "Must be an ArrayBuffer" }),
|
|
2063
2078
|
zod_v4.z.custom((value) => {
|
|
2064
2079
|
var _a17, _b;
|
|
2065
2080
|
return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
|
|
@@ -3266,7 +3281,7 @@ function createUIMessageStream$2({ execute, onError = () => "An error occurred."
|
|
|
3266
3281
|
getOutcome: () => outcome
|
|
3267
3282
|
});
|
|
3268
3283
|
}
|
|
3269
|
-
// ../../packages/_vendored/ai_v6/dist/dist-
|
|
3284
|
+
// ../../packages/_vendored/ai_v6/dist/dist-DwNW4Hp7.js
|
|
3270
3285
|
var marker$1$2 = "vercel.ai.error";
|
|
3271
3286
|
var symbol$1$2 = Symbol.for(marker$1$2);
|
|
3272
3287
|
var _a$1;
|
|
@@ -3397,6 +3412,20 @@ Error message: ${getErrorMessage$1(cause)}`,
|
|
|
3397
3412
|
};
|
|
3398
3413
|
TransformStream;
|
|
3399
3414
|
var { btoa: btoa$2, atob: atob$4 } = globalThis;
|
|
3415
|
+
var typedArrayTag$1 = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
|
|
3416
|
+
var arrayBufferByteLength$1 = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
|
|
3417
|
+
function isUint8Array$1(value) {
|
|
3418
|
+
return ArrayBuffer.isView(value) && typedArrayTag$1.call(value) === "Uint8Array";
|
|
3419
|
+
}
|
|
3420
|
+
function isArrayBuffer$1(value) {
|
|
3421
|
+
if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
|
|
3422
|
+
try {
|
|
3423
|
+
arrayBufferByteLength$1.call(value);
|
|
3424
|
+
return true;
|
|
3425
|
+
} catch (e) {
|
|
3426
|
+
return false;
|
|
3427
|
+
}
|
|
3428
|
+
}
|
|
3400
3429
|
var createIdGenerator$1 = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => {
|
|
3401
3430
|
const generator = () => {
|
|
3402
3431
|
const alphabetLength = alphabet.length;
|
|
@@ -5351,8 +5380,8 @@ function mergeObjects$1(base, overrides) {
|
|
|
5351
5380
|
}
|
|
5352
5381
|
var dataContentSchema = zod_v4.z.union([
|
|
5353
5382
|
zod_v4.z.string(),
|
|
5354
|
-
zod_v4.z.
|
|
5355
|
-
zod_v4.z.
|
|
5383
|
+
zod_v4.z.custom(isUint8Array$1, { message: "Must be a Uint8Array" }),
|
|
5384
|
+
zod_v4.z.custom(isArrayBuffer$1, { message: "Must be an ArrayBuffer" }),
|
|
5356
5385
|
zod_v4.z.custom((value) => {
|
|
5357
5386
|
var _a23, _b;
|
|
5358
5387
|
return (_b = (_a23 = globalThis.Buffer) == null ? void 0 : _a23.isBuffer(value)) != null ? _b : false;
|
|
@@ -6943,7 +6972,7 @@ var doWrap = ({ model, middleware: { transformParams, wrapGenerate, wrapStream,
|
|
|
6943
6972
|
}
|
|
6944
6973
|
};
|
|
6945
6974
|
};
|
|
6946
|
-
// ../../packages/_vendored/ai_v7/dist/dist-
|
|
6975
|
+
// ../../packages/_vendored/ai_v7/dist/dist-CwN1TMYk.js
|
|
6947
6976
|
/**
|
|
6948
6977
|
* Symbol used for identifying AI SDK Error instances.
|
|
6949
6978
|
* Enables checking if an error is an instance of AISDKError across package versions.
|
|
@@ -7075,6 +7104,20 @@ var TypeValidationError = class TypeValidationError extends AISDKError {
|
|
|
7075
7104
|
TransformStream;
|
|
7076
7105
|
new TextDecoder();
|
|
7077
7106
|
const { btoa: btoa$1, atob: atob$2 } = globalThis;
|
|
7107
|
+
const typedArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
|
|
7108
|
+
const arrayBufferByteLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
|
|
7109
|
+
function isUint8Array(value) {
|
|
7110
|
+
return ArrayBuffer.isView(value) && typedArrayTag.call(value) === "Uint8Array";
|
|
7111
|
+
}
|
|
7112
|
+
function isArrayBuffer(value) {
|
|
7113
|
+
if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
|
|
7114
|
+
try {
|
|
7115
|
+
arrayBufferByteLength.call(value);
|
|
7116
|
+
return true;
|
|
7117
|
+
} catch {
|
|
7118
|
+
return false;
|
|
7119
|
+
}
|
|
7120
|
+
}
|
|
7078
7121
|
/**
|
|
7079
7122
|
* Creates an ID generator.
|
|
7080
7123
|
* The total length of the ID is the sum of the prefix, separator, and random part length.
|
|
@@ -8423,9 +8466,7 @@ function fixJson(input) {
|
|
|
8423
8466
|
lastValidIndex = i;
|
|
8424
8467
|
stack.pop();
|
|
8425
8468
|
break;
|
|
8426
|
-
default:
|
|
8427
|
-
lastValidIndex = i;
|
|
8428
|
-
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
|
|
8469
|
+
default: processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
|
|
8429
8470
|
}
|
|
8430
8471
|
break;
|
|
8431
8472
|
case "INSIDE_ARRAY_AFTER_VALUE":
|
|
@@ -9304,12 +9345,13 @@ function processUIMessageStream({ stream, messageMetadataSchema, dataPartSchemas
|
|
|
9304
9345
|
onError?.(new Error(chunk.errorText));
|
|
9305
9346
|
break;
|
|
9306
9347
|
default: if (isDataUIMessageChunk(chunk)) {
|
|
9307
|
-
|
|
9348
|
+
const dataPartSchema = dataPartSchemas?.[chunk.type.slice(5)];
|
|
9349
|
+
if (dataPartSchema != null) {
|
|
9308
9350
|
const partIdx = state.message.parts.findIndex((p) => "id" in p && "data" in p && p.id === chunk.id && p.type === chunk.type);
|
|
9309
9351
|
const actualPartIdx = partIdx >= 0 ? partIdx : state.message.parts.length;
|
|
9310
9352
|
await validateTypes({
|
|
9311
9353
|
value: chunk.data,
|
|
9312
|
-
schema:
|
|
9354
|
+
schema: dataPartSchema,
|
|
9313
9355
|
context: {
|
|
9314
9356
|
field: `message.parts[${actualPartIdx}].data`,
|
|
9315
9357
|
entityName: chunk.type,
|
|
@@ -9595,8 +9637,8 @@ createIdGenerator({
|
|
|
9595
9637
|
});
|
|
9596
9638
|
const fileInlineDataSchema = z.union([
|
|
9597
9639
|
z.string(),
|
|
9598
|
-
z.
|
|
9599
|
-
z.
|
|
9640
|
+
z.custom(isUint8Array, { message: "Must be a Uint8Array" }),
|
|
9641
|
+
z.custom(isArrayBuffer, { message: "Must be an ArrayBuffer" }),
|
|
9600
9642
|
z.custom(isBuffer, { message: "Must be a Buffer" })
|
|
9601
9643
|
]);
|
|
9602
9644
|
const providerReferenceSchema = z.record(z.string(), z.string());
|
|
@@ -11961,15 +12003,121 @@ const CREDENTIAL_HEADER_NAMES = /* @__PURE__ */ new Set([
|
|
|
11961
12003
|
"x-goog-api-key",
|
|
11962
12004
|
"cookie"
|
|
11963
12005
|
]);
|
|
11964
|
-
|
|
11965
|
-
|
|
11966
|
-
|
|
12006
|
+
/** Resolves one Editor agent version selector from the route query. */
|
|
12007
|
+
function resolveAgentVersionFromQuery(query, fallback) {
|
|
12008
|
+
const versionId = query("versionId");
|
|
12009
|
+
const status = query("status");
|
|
12010
|
+
if (versionId && status) throw new Error("Query parameters \"versionId\" and \"status\" are mutually exclusive");
|
|
12011
|
+
if (status && status !== "draft" && status !== "published") throw new Error("Query parameter \"status\" must be \"draft\" or \"published\"");
|
|
12012
|
+
return versionId ? { versionId } : status ? { status } : fallback;
|
|
12013
|
+
}
|
|
12014
|
+
/** Wraps a UI message stream in the response implementation for its AI SDK version. */
|
|
12015
|
+
function createChatUIMessageStreamResponse(stream, version) {
|
|
12016
|
+
if (version === "v7") return createUIMessageStreamResponse({ stream });
|
|
12017
|
+
if (version === "v6") return createUIMessageStreamResponse$1({ stream });
|
|
12018
|
+
return createUIMessageStreamResponse$2({ stream });
|
|
12019
|
+
}
|
|
12020
|
+
/** Resolves the configured agent, including Editor-stored overrides and explicit version selectors. */
|
|
12021
|
+
async function resolveChatAgent({ mastra, agentId, agentVersion, requestContext, defaultToPublished = true }) {
|
|
11967
12022
|
const baseAgent = mastra.getAgentById(agentId);
|
|
11968
12023
|
if (!baseAgent) throw new Error(`Agent ${agentId} not found`);
|
|
11969
|
-
let agentObj = baseAgent;
|
|
11970
12024
|
const editorAgent = mastra.getEditor?.()?.agent;
|
|
11971
|
-
if (editorAgent)
|
|
11972
|
-
|
|
12025
|
+
if (editorAgent) {
|
|
12026
|
+
if (!agentVersion && !defaultToPublished) return baseAgent;
|
|
12027
|
+
return editorAgent.applyStoredOverrides(baseAgent, agentVersion ?? { status: "published" }, requestContext);
|
|
12028
|
+
}
|
|
12029
|
+
if (agentVersion) return mastra.getAgentById(agentId, agentVersion);
|
|
12030
|
+
return baseAgent;
|
|
12031
|
+
}
|
|
12032
|
+
const MASTRA_AUTH_MODE_KEY = "mastra__authMode";
|
|
12033
|
+
/** Selects the FGA provider for the request's trusted authentication mode. */
|
|
12034
|
+
function resolveChatFGAProvider(mastra, requestContext) {
|
|
12035
|
+
const studioFga = mastra.getStudio()?.fga;
|
|
12036
|
+
const serverFga = mastra.getServer()?.fga;
|
|
12037
|
+
if (requestContext?.get(MASTRA_AUTH_MODE_KEY) === "studio" && studioFga) return studioFga;
|
|
12038
|
+
if (serverFga) return serverFga;
|
|
12039
|
+
return studioFga ? null : void 0;
|
|
12040
|
+
}
|
|
12041
|
+
/** Authorizes replay using the same resource ownership and thread FGA rules as run observation. */
|
|
12042
|
+
async function authorizeChatRunObservation({ mastra, agent, runRecord, requestContext }) {
|
|
12043
|
+
const resourceId = requestContext?.get(_mastra_core_request_context.MASTRA_RESOURCE_ID_KEY);
|
|
12044
|
+
const server = mastra.getServer();
|
|
12045
|
+
const fgaProvider = resolveChatFGAProvider(mastra, requestContext);
|
|
12046
|
+
if (fgaProvider === null) return false;
|
|
12047
|
+
if (typeof (server?.auth)?.mapUserToResourceId === "function") {
|
|
12048
|
+
if (resourceId) {
|
|
12049
|
+
if (runRecord.resourceId !== resourceId) return false;
|
|
12050
|
+
} else if (!fgaProvider || !runRecord.threadId) return false;
|
|
12051
|
+
} else if (runRecord.resourceId && runRecord.resourceId !== resourceId) return false;
|
|
12052
|
+
if (!runRecord.threadId) return true;
|
|
12053
|
+
requestContext?.set(_mastra_core_request_context.MASTRA_THREAD_ID_KEY, runRecord.threadId);
|
|
12054
|
+
const thread = await (await agent.getMemory({ requestContext }))?.getThreadById({ threadId: runRecord.threadId });
|
|
12055
|
+
if (resourceId && thread?.resourceId && thread.resourceId !== resourceId) return false;
|
|
12056
|
+
if (fgaProvider) {
|
|
12057
|
+
const user = requestContext?.get("user");
|
|
12058
|
+
if (!user || typeof user !== "object") return false;
|
|
12059
|
+
try {
|
|
12060
|
+
await _mastra_core_memory.MastraMemory.checkThreadFGA({
|
|
12061
|
+
mastra,
|
|
12062
|
+
user,
|
|
12063
|
+
threadId: runRecord.threadId,
|
|
12064
|
+
resourceId: thread?.resourceId ?? runRecord.resourceId ?? resourceId,
|
|
12065
|
+
requestContext,
|
|
12066
|
+
fgaProvider
|
|
12067
|
+
});
|
|
12068
|
+
} catch {
|
|
12069
|
+
return false;
|
|
12070
|
+
}
|
|
12071
|
+
}
|
|
12072
|
+
return true;
|
|
12073
|
+
}
|
|
12074
|
+
/** Converts a Mastra agent stream to the requested AI SDK UI message stream version. */
|
|
12075
|
+
function createChatUIMessageStream({ result, messages, version, lastMessageId, sendStart, sendFinish, sendReasoning, sendSources, includeSubAgentMetadata, experimentalTransform, onError, messageMetadata }) {
|
|
12076
|
+
if (version === "v6" || version === "v7") return (version === "v7" ? createUIMessageStream : createUIMessageStream$1)({
|
|
12077
|
+
originalMessages: messages,
|
|
12078
|
+
execute: async ({ writer }) => {
|
|
12079
|
+
for await (const part of toAISdkStream(result, {
|
|
12080
|
+
from: "agent",
|
|
12081
|
+
version: "v6",
|
|
12082
|
+
lastMessageId,
|
|
12083
|
+
sendStart,
|
|
12084
|
+
sendFinish,
|
|
12085
|
+
sendReasoning,
|
|
12086
|
+
sendSources,
|
|
12087
|
+
includeSubAgentMetadata,
|
|
12088
|
+
experimentalTransform,
|
|
12089
|
+
onError,
|
|
12090
|
+
messageMetadata
|
|
12091
|
+
})) writer.write(part);
|
|
12092
|
+
}
|
|
12093
|
+
});
|
|
12094
|
+
return createUIMessageStream$2({
|
|
12095
|
+
originalMessages: messages,
|
|
12096
|
+
execute: async ({ writer }) => {
|
|
12097
|
+
for await (const part of toAISdkStream(result, {
|
|
12098
|
+
from: "agent",
|
|
12099
|
+
lastMessageId,
|
|
12100
|
+
sendStart,
|
|
12101
|
+
sendFinish,
|
|
12102
|
+
sendReasoning,
|
|
12103
|
+
sendSources,
|
|
12104
|
+
includeSubAgentMetadata,
|
|
12105
|
+
experimentalTransform,
|
|
12106
|
+
onError,
|
|
12107
|
+
messageMetadata
|
|
12108
|
+
})) writer.write(part);
|
|
12109
|
+
}
|
|
12110
|
+
});
|
|
12111
|
+
}
|
|
12112
|
+
async function handleChatStream({ mastra, agentId, agentVersion, params, defaultOptions, experimentalTransform, version = "v5", sendStart = true, sendFinish = true, sendReasoning = false, sendSources = false, includeSubAgentMetadata = true, onError, messageMetadata }) {
|
|
12113
|
+
const { messages, resumeData, runId, requestContext, trigger, ...rest } = params;
|
|
12114
|
+
if (resumeData && !runId) throw new Error("runId is required when resumeData is provided");
|
|
12115
|
+
const agentObj = await resolveChatAgent({
|
|
12116
|
+
mastra,
|
|
12117
|
+
agentId,
|
|
12118
|
+
agentVersion,
|
|
12119
|
+
requestContext
|
|
12120
|
+
});
|
|
11973
12121
|
if (!Array.isArray(messages)) throw new Error("Messages must be an array of UIMessage objects");
|
|
11974
12122
|
let lastMessageId;
|
|
11975
12123
|
let messagesToSend = messages;
|
|
@@ -12019,101 +12167,31 @@ async function handleChatStream({ mastra, agentId, agentVersion, params, default
|
|
|
12019
12167
|
messageMetadata
|
|
12020
12168
|
});
|
|
12021
12169
|
}
|
|
12022
|
-
|
|
12023
|
-
|
|
12024
|
-
|
|
12025
|
-
|
|
12026
|
-
|
|
12027
|
-
|
|
12028
|
-
|
|
12029
|
-
|
|
12030
|
-
|
|
12031
|
-
|
|
12032
|
-
|
|
12033
|
-
|
|
12034
|
-
|
|
12035
|
-
|
|
12036
|
-
|
|
12037
|
-
|
|
12038
|
-
|
|
12039
|
-
|
|
12040
|
-
|
|
12041
|
-
experimentalTransform: effectiveExperimentalTransform,
|
|
12042
|
-
onError,
|
|
12043
|
-
messageMetadata
|
|
12044
|
-
})) writer.write(part);
|
|
12045
|
-
}
|
|
12046
|
-
});
|
|
12047
|
-
return createUIMessageStream$2({
|
|
12048
|
-
originalMessages: messages,
|
|
12049
|
-
execute: async ({ writer }) => {
|
|
12050
|
-
for await (const part of toAISdkStream(result, {
|
|
12051
|
-
from: "agent",
|
|
12052
|
-
lastMessageId,
|
|
12053
|
-
sendStart,
|
|
12054
|
-
sendFinish,
|
|
12055
|
-
sendReasoning,
|
|
12056
|
-
sendSources,
|
|
12057
|
-
includeSubAgentMetadata,
|
|
12058
|
-
experimentalTransform: effectiveExperimentalTransform,
|
|
12059
|
-
onError,
|
|
12060
|
-
messageMetadata
|
|
12061
|
-
})) writer.write(part);
|
|
12062
|
-
}
|
|
12170
|
+
return createChatUIMessageStream({
|
|
12171
|
+
result: resumeData ? structuredOutput ? await agentObj.resumeStream(resumeData, {
|
|
12172
|
+
...baseOptions,
|
|
12173
|
+
structuredOutput
|
|
12174
|
+
}) : await agentObj.resumeStream(resumeData, baseOptions) : structuredOutput ? await agentObj.stream(messagesToSend, {
|
|
12175
|
+
...baseOptions,
|
|
12176
|
+
structuredOutput
|
|
12177
|
+
}) : await agentObj.stream(messagesToSend, baseOptions),
|
|
12178
|
+
messages,
|
|
12179
|
+
version,
|
|
12180
|
+
lastMessageId,
|
|
12181
|
+
sendStart,
|
|
12182
|
+
sendFinish,
|
|
12183
|
+
sendReasoning,
|
|
12184
|
+
sendSources,
|
|
12185
|
+
includeSubAgentMetadata,
|
|
12186
|
+
experimentalTransform: effectiveExperimentalTransform,
|
|
12187
|
+
onError,
|
|
12188
|
+
messageMetadata
|
|
12063
12189
|
});
|
|
12064
12190
|
}
|
|
12065
|
-
|
|
12066
|
-
* Creates a chat route handler for streaming agent conversations using the AI SDK format.
|
|
12067
|
-
*
|
|
12068
|
-
* This function registers an HTTP POST endpoint that accepts messages, executes an agent, and streams the response back to the client in AI SDK-compatible format.
|
|
12069
|
-
*
|
|
12070
|
-
* @param {chatRouteOptions} options - Configuration options for the chat route
|
|
12071
|
-
* @param {string} [options.path='/chat/:agentId'] - The route path. Include `:agentId` for dynamic routing
|
|
12072
|
-
* @param {string} [options.agent] - Fixed agent ID when not using dynamic routing
|
|
12073
|
-
* @param {AgentExecutionOptions} [options.defaultOptions] - Default options passed to agent execution
|
|
12074
|
-
* @param {boolean} [options.sendStart=true] - Whether to send start events in the stream
|
|
12075
|
-
* @param {boolean} [options.sendFinish=true] - Whether to send finish events in the stream
|
|
12076
|
-
* @param {boolean} [options.sendReasoning=false] - Whether to include reasoning steps in the stream
|
|
12077
|
-
* @param {boolean} [options.sendSources=false] - Whether to include source citations in the stream
|
|
12078
|
-
* @param {boolean} [options.includeSubAgentMetadata=true] - Whether to emit `data-tool-agent` / `data-tool-agent-step` parts with sub-agent progress
|
|
12079
|
-
* @param {number} [options.heartbeatMs] - Target interval for periodic SSE comment heartbeats. Already-buffered source events and stream lifecycle signals take priority. Values up to 0 disable heartbeats. `NaN`, positive infinity, and values above 2,147,483,647 throw a `RangeError`.
|
|
12080
|
-
* @param {(error: unknown) => string} [options.onError] - Custom error serializer streamed to the client. When omitted, errors are passed through a default serializer that strips sensitive fields (e.g. `APICallError.requestBodyValues`, which holds the system prompt) before they reach the client.
|
|
12081
|
-
* @param {Function} [options.messageMetadata] - Maps stream parts to metadata attached to AI SDK start and finish message parts. Receives `{ part, traceId }`.
|
|
12082
|
-
*
|
|
12083
|
-
* @returns {ReturnType<typeof registerApiRoute>} A registered API route handler
|
|
12084
|
-
*
|
|
12085
|
-
* @throws {Error} When path doesn't include `:agentId` and no fixed agent is specified
|
|
12086
|
-
* @throws {RangeError} When `heartbeatMs` is `NaN`, positive infinity, or greater than 2,147,483,647
|
|
12087
|
-
* @throws {Error} When agent ID is missing at runtime
|
|
12088
|
-
* @throws {Error} When specified agent is not found in Mastra instance
|
|
12089
|
-
*
|
|
12090
|
-
* @example
|
|
12091
|
-
* // Dynamic agent routing
|
|
12092
|
-
* chatRoute({
|
|
12093
|
-
* path: '/chat/:agentId',
|
|
12094
|
-
* });
|
|
12095
|
-
*
|
|
12096
|
-
* @example
|
|
12097
|
-
* // Fixed agent with custom path
|
|
12098
|
-
* chatRoute({
|
|
12099
|
-
* path: '/api/support-chat',
|
|
12100
|
-
* agent: 'support-agent',
|
|
12101
|
-
* defaultOptions: {
|
|
12102
|
-
* maxSteps: 5,
|
|
12103
|
-
* },
|
|
12104
|
-
* });
|
|
12105
|
-
*
|
|
12106
|
-
* @remarks
|
|
12107
|
-
* - The route handler expects a JSON body with a `messages` array
|
|
12108
|
-
* - Messages should follow the format: `{ role: 'user' | 'assistant' | 'system', content: string }`
|
|
12109
|
-
* - The response is a Server-Sent Events (SSE) stream compatible with the selected AI SDK version
|
|
12110
|
-
* - If both `agent` and `:agentId` are present, a warning is logged and the fixed `agent` takes precedence
|
|
12111
|
-
* - Request context from the incoming request overrides `defaultOptions.requestContext` if both are present
|
|
12112
|
-
*/
|
|
12113
|
-
function chatRoute({ path = "/chat/:agentId", agent, defaultOptions, experimentalTransform, version = "v5", agentVersion, sendStart = true, sendFinish = true, sendReasoning = false, sendSources = false, includeSubAgentMetadata = true, heartbeatMs, onError, messageMetadata }) {
|
|
12191
|
+
function chatRoute({ path = "/chat/:agentId", agent, defaultOptions, experimentalTransform, version = "v5", agentVersion, resumable = false, sendStart = true, sendFinish = true, sendReasoning = false, sendSources = false, includeSubAgentMetadata = true, heartbeatMs, onError, messageMetadata }) {
|
|
12114
12192
|
if (!agent && !path.includes("/:agentId")) throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
|
|
12115
12193
|
assertValidHeartbeatMs(heartbeatMs);
|
|
12116
|
-
|
|
12194
|
+
const postRoute = (0, _mastra_core_server.registerApiRoute)(path, {
|
|
12117
12195
|
method: "POST",
|
|
12118
12196
|
openapi: {
|
|
12119
12197
|
summary: "Chat with an agent",
|
|
@@ -12216,22 +12294,29 @@ function chatRoute({ path = "/chat/:agentId", agent, defaultOptions, experimenta
|
|
|
12216
12294
|
let agentToUse = agent;
|
|
12217
12295
|
if (!agent) agentToUse = c.req.param("agentId");
|
|
12218
12296
|
if (c.req.param("agentId") && agent) mastra.getLogger()?.warn(`Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`);
|
|
12219
|
-
const
|
|
12297
|
+
const configuredRequestContext = contextRequestContext || defaultOptions?.requestContext || params.requestContext;
|
|
12298
|
+
const effectiveRequestContext = resumable && params.id ? new _mastra_core_request_context.RequestContext(configuredRequestContext ? configuredRequestContext.entries() : void 0) : configuredRequestContext;
|
|
12299
|
+
if (resumable && params.id) effectiveRequestContext.set(_mastra_core_request_context.MASTRA_THREAD_ID_KEY, params.id);
|
|
12220
12300
|
if (contextRequestContext && defaultOptions?.requestContext || contextRequestContext && params.requestContext || defaultOptions?.requestContext && params.requestContext) mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
|
|
12221
12301
|
if (!agentToUse) throw new Error("Agent ID is required");
|
|
12222
|
-
const
|
|
12223
|
-
const
|
|
12224
|
-
|
|
12225
|
-
|
|
12226
|
-
|
|
12302
|
+
const effectiveAgentVersion = resolveAgentVersionFromQuery((name) => c.req.query(name), agentVersion);
|
|
12303
|
+
const resumableResourceId = (contextRequestContext || defaultOptions?.requestContext)?.get(_mastra_core_request_context.MASTRA_RESOURCE_ID_KEY);
|
|
12304
|
+
const bodyResourceId = typeof params.memory === "object" ? params.memory?.resource : void 0;
|
|
12305
|
+
const bodyRequestContextResourceId = params.requestContext?.get(_mastra_core_request_context.MASTRA_RESOURCE_ID_KEY);
|
|
12306
|
+
if (resumable && (bodyResourceId || bodyRequestContextResourceId) && !resumableResourceId) return c.json({ error: "Resumable chat resource IDs must be set by authentication middleware or route request context, not in the request body." }, 400);
|
|
12227
12307
|
const handlerOptions = {
|
|
12228
12308
|
mastra,
|
|
12229
12309
|
agentId: agentToUse,
|
|
12230
|
-
agentVersion:
|
|
12310
|
+
agentVersion: effectiveAgentVersion,
|
|
12231
12311
|
params: {
|
|
12232
12312
|
...params,
|
|
12313
|
+
...resumable && params.id ? { memory: {
|
|
12314
|
+
...typeof params.memory === "object" ? params.memory : {},
|
|
12315
|
+
...resumableResourceId ? { resource: resumableResourceId } : {},
|
|
12316
|
+
thread: params.id
|
|
12317
|
+
} } : {},
|
|
12233
12318
|
requestContext: effectiveRequestContext,
|
|
12234
|
-
abortSignal: c.req.raw.signal
|
|
12319
|
+
...!resumable && { abortSignal: c.req.raw.signal }
|
|
12235
12320
|
},
|
|
12236
12321
|
defaultOptions,
|
|
12237
12322
|
experimentalTransform,
|
|
@@ -12242,24 +12327,108 @@ function chatRoute({ path = "/chat/:agentId", agent, defaultOptions, experimenta
|
|
|
12242
12327
|
includeSubAgentMetadata,
|
|
12243
12328
|
onError
|
|
12244
12329
|
};
|
|
12245
|
-
|
|
12246
|
-
if (version === "v7") response = createUIMessageStreamResponse({ stream: await handleChatStream({
|
|
12330
|
+
return withSseHeartbeat(createChatUIMessageStreamResponse(version === "v7" ? await handleChatStream({
|
|
12247
12331
|
...handlerOptions,
|
|
12248
12332
|
version: "v7",
|
|
12249
12333
|
messageMetadata
|
|
12250
|
-
})
|
|
12251
|
-
else if (version === "v6") response = createUIMessageStreamResponse$1({ stream: await handleChatStream({
|
|
12334
|
+
}) : version === "v6" ? await handleChatStream({
|
|
12252
12335
|
...handlerOptions,
|
|
12253
12336
|
version: "v6",
|
|
12254
12337
|
messageMetadata
|
|
12255
|
-
})
|
|
12256
|
-
else response = createUIMessageStreamResponse$2({ stream: await handleChatStream({
|
|
12338
|
+
}) : await handleChatStream({
|
|
12257
12339
|
...handlerOptions,
|
|
12258
12340
|
messageMetadata
|
|
12259
|
-
})
|
|
12260
|
-
return withSseHeartbeat(response, heartbeatMs);
|
|
12341
|
+
}), version), heartbeatMs);
|
|
12261
12342
|
}
|
|
12262
12343
|
});
|
|
12344
|
+
if (!resumable) return postRoute;
|
|
12345
|
+
const reconnectPath = `${path.replace(/\/$/, "")}/:chatId/stream`;
|
|
12346
|
+
return [postRoute, (0, _mastra_core_server.registerApiRoute)(reconnectPath, {
|
|
12347
|
+
method: "GET",
|
|
12348
|
+
openapi: {
|
|
12349
|
+
summary: "Reconnect to an agent chat stream",
|
|
12350
|
+
description: "Replay and follow the active agent run for an AI SDK chat",
|
|
12351
|
+
tags: ["ai-sdk"],
|
|
12352
|
+
parameters: [
|
|
12353
|
+
...path.includes(":agentId") ? [{
|
|
12354
|
+
name: "agentId",
|
|
12355
|
+
in: "path",
|
|
12356
|
+
required: true,
|
|
12357
|
+
schema: { type: "string" }
|
|
12358
|
+
}] : [],
|
|
12359
|
+
{
|
|
12360
|
+
name: "chatId",
|
|
12361
|
+
in: "path",
|
|
12362
|
+
required: true,
|
|
12363
|
+
schema: { type: "string" }
|
|
12364
|
+
},
|
|
12365
|
+
{
|
|
12366
|
+
name: "versionId",
|
|
12367
|
+
in: "query",
|
|
12368
|
+
required: false,
|
|
12369
|
+
schema: { type: "string" }
|
|
12370
|
+
},
|
|
12371
|
+
{
|
|
12372
|
+
name: "status",
|
|
12373
|
+
in: "query",
|
|
12374
|
+
required: false,
|
|
12375
|
+
schema: {
|
|
12376
|
+
type: "string",
|
|
12377
|
+
enum: ["draft", "published"]
|
|
12378
|
+
}
|
|
12379
|
+
}
|
|
12380
|
+
],
|
|
12381
|
+
responses: {
|
|
12382
|
+
"200": {
|
|
12383
|
+
description: "Replayable streaming response from the agent run",
|
|
12384
|
+
content: { "text/plain": { schema: { type: "string" } } }
|
|
12385
|
+
},
|
|
12386
|
+
"204": { description: "The chat has no active resumable run" },
|
|
12387
|
+
"404": { description: "The active run does not belong to the current resource or thread" }
|
|
12388
|
+
}
|
|
12389
|
+
},
|
|
12390
|
+
handler: async (c) => {
|
|
12391
|
+
const mastra = c.get("mastra");
|
|
12392
|
+
const requestContext = c.get("requestContext") || (defaultOptions?.requestContext ? new _mastra_core_request_context.RequestContext(defaultOptions.requestContext.entries()) : void 0);
|
|
12393
|
+
const agentToUse = agent ?? c.req.param("agentId");
|
|
12394
|
+
const chatId = c.req.param("chatId");
|
|
12395
|
+
if (!agentToUse || !chatId) return new Response(null, { status: 204 });
|
|
12396
|
+
const agentObj = await resolveChatAgent({
|
|
12397
|
+
mastra,
|
|
12398
|
+
agentId: agentToUse,
|
|
12399
|
+
agentVersion: resolveAgentVersionFromQuery((name) => c.req.query(name), agentVersion),
|
|
12400
|
+
requestContext,
|
|
12401
|
+
defaultToPublished: false
|
|
12402
|
+
});
|
|
12403
|
+
const resourceId = requestContext?.get(_mastra_core_request_context.MASTRA_RESOURCE_ID_KEY);
|
|
12404
|
+
const runId = agentObj.getActiveThreadRunId({
|
|
12405
|
+
threadId: chatId,
|
|
12406
|
+
resourceId
|
|
12407
|
+
});
|
|
12408
|
+
if (!runId) return new Response(null, { status: 204 });
|
|
12409
|
+
const runRecord = await agentObj.__getRunRecord(runId);
|
|
12410
|
+
if (!runRecord || runRecord.status === "finished") return new Response(null, { status: 204 });
|
|
12411
|
+
if (!await authorizeChatRunObservation({
|
|
12412
|
+
mastra,
|
|
12413
|
+
agent: agentObj,
|
|
12414
|
+
runRecord,
|
|
12415
|
+
requestContext
|
|
12416
|
+
})) return new Response(null, { status: 404 });
|
|
12417
|
+
return withSseHeartbeat(createChatUIMessageStreamResponse(createChatUIMessageStream({
|
|
12418
|
+
result: (await agentObj.observe(runId)).output,
|
|
12419
|
+
messages: [],
|
|
12420
|
+
version,
|
|
12421
|
+
sendStart,
|
|
12422
|
+
sendFinish,
|
|
12423
|
+
sendReasoning,
|
|
12424
|
+
sendSources,
|
|
12425
|
+
includeSubAgentMetadata,
|
|
12426
|
+
experimentalTransform,
|
|
12427
|
+
onError,
|
|
12428
|
+
messageMetadata
|
|
12429
|
+
}), version), heartbeatMs);
|
|
12430
|
+
}
|
|
12431
|
+
})];
|
|
12263
12432
|
}
|
|
12264
12433
|
// src/workflow-route.ts
|
|
12265
12434
|
async function handleWorkflowStream({ mastra, workflowId, params, version = "v5", includeTextStreamParts = true, sendReasoning = false, sendSources = false }) {
|