@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.js
CHANGED
|
@@ -2,14 +2,15 @@ import * as z4 from "zod/v4";
|
|
|
2
2
|
import { array, boolean, custom, discriminatedUnion, enum as enum$1, instanceof as instanceof$1, lazy, literal, looseObject, never, null as null$1, number, object, record, safeParseAsync, string, union, unknown, z } from "zod/v4";
|
|
3
3
|
import { ZodFirstPartyTypeKind } from "zod/v3";
|
|
4
4
|
import { toJSONSchema } from "zod/v4/core";
|
|
5
|
+
import { MastraMemory } from "@mastra/core/memory";
|
|
6
|
+
import { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, RequestContext } from "@mastra/core/request-context";
|
|
5
7
|
import { registerApiRoute } from "@mastra/core/server";
|
|
6
8
|
import { DefaultGeneratedFile, DefaultGeneratedFileWithType, convertFullStreamChunkToMastra, smoothStream as smoothStream$1 } from "@mastra/core/stream";
|
|
7
9
|
import { ReadableStream as ReadableStream$1, TransformStream as TransformStream$1 } from "stream/web";
|
|
8
|
-
import { MASTRA_RESOURCE_ID_KEY } from "@mastra/core/request-context";
|
|
9
10
|
import { MessageList, TripWire, aiV5ModelMessageToV2PromptMessage } from "@mastra/core/agent";
|
|
10
|
-
import { RequestContext } from "@mastra/core/di";
|
|
11
|
+
import { RequestContext as RequestContext$1 } from "@mastra/core/di";
|
|
11
12
|
import { MessageHistory, SemanticRecall, WorkingMemory } from "@mastra/core/processors";
|
|
12
|
-
// ../../packages/_vendored/ai_v5/dist/dist-
|
|
13
|
+
// ../../packages/_vendored/ai_v5/dist/dist-BYnbJEqC.js
|
|
13
14
|
var marker$1$4 = "vercel.ai.error";
|
|
14
15
|
var symbol$1$4 = Symbol.for(marker$1$4);
|
|
15
16
|
var _a$1$4;
|
|
@@ -1219,6 +1220,20 @@ function asSchema$2(schema) {
|
|
|
1219
1220
|
}) : isSchema$2(schema) ? schema : typeof schema === "function" ? schema() : zodSchema$2(schema);
|
|
1220
1221
|
}
|
|
1221
1222
|
var { btoa: btoa$3, atob: atob$6 } = globalThis;
|
|
1223
|
+
var typedArrayTag$2 = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
|
|
1224
|
+
var arrayBufferByteLength$2 = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
|
|
1225
|
+
function isUint8Array$2(value) {
|
|
1226
|
+
return ArrayBuffer.isView(value) && typedArrayTag$2.call(value) === "Uint8Array";
|
|
1227
|
+
}
|
|
1228
|
+
function isArrayBuffer$2(value) {
|
|
1229
|
+
if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
|
|
1230
|
+
try {
|
|
1231
|
+
arrayBufferByteLength$2.call(value);
|
|
1232
|
+
return true;
|
|
1233
|
+
} catch (e) {
|
|
1234
|
+
return false;
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1222
1237
|
// ../../packages/_vendored/ai_v5/dist/index.js
|
|
1223
1238
|
/** only globals that common to node and browsers are allowed */
|
|
1224
1239
|
var _globalThis = typeof globalThis === "object" ? globalThis : global;
|
|
@@ -2036,8 +2051,8 @@ var NoObjectGeneratedError$1 = class extends AISDKError$2 {
|
|
|
2036
2051
|
_a7$2 = symbol7$2;
|
|
2037
2052
|
var dataContentSchema$1 = z.union([
|
|
2038
2053
|
z.string(),
|
|
2039
|
-
z.
|
|
2040
|
-
z.
|
|
2054
|
+
z.custom(isUint8Array$2, { message: "Must be a Uint8Array" }),
|
|
2055
|
+
z.custom(isArrayBuffer$2, { message: "Must be an ArrayBuffer" }),
|
|
2041
2056
|
z.custom((value) => {
|
|
2042
2057
|
var _a17, _b;
|
|
2043
2058
|
return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
|
|
@@ -3244,7 +3259,7 @@ function createUIMessageStream$2({ execute, onError = () => "An error occurred."
|
|
|
3244
3259
|
getOutcome: () => outcome
|
|
3245
3260
|
});
|
|
3246
3261
|
}
|
|
3247
|
-
// ../../packages/_vendored/ai_v6/dist/dist-
|
|
3262
|
+
// ../../packages/_vendored/ai_v6/dist/dist-DwNW4Hp7.js
|
|
3248
3263
|
var marker$1$2 = "vercel.ai.error";
|
|
3249
3264
|
var symbol$1$2 = Symbol.for(marker$1$2);
|
|
3250
3265
|
var _a$1;
|
|
@@ -3375,6 +3390,20 @@ Error message: ${getErrorMessage$1(cause)}`,
|
|
|
3375
3390
|
};
|
|
3376
3391
|
TransformStream;
|
|
3377
3392
|
var { btoa: btoa$2, atob: atob$4 } = globalThis;
|
|
3393
|
+
var typedArrayTag$1 = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
|
|
3394
|
+
var arrayBufferByteLength$1 = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
|
|
3395
|
+
function isUint8Array$1(value) {
|
|
3396
|
+
return ArrayBuffer.isView(value) && typedArrayTag$1.call(value) === "Uint8Array";
|
|
3397
|
+
}
|
|
3398
|
+
function isArrayBuffer$1(value) {
|
|
3399
|
+
if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
|
|
3400
|
+
try {
|
|
3401
|
+
arrayBufferByteLength$1.call(value);
|
|
3402
|
+
return true;
|
|
3403
|
+
} catch (e) {
|
|
3404
|
+
return false;
|
|
3405
|
+
}
|
|
3406
|
+
}
|
|
3378
3407
|
var createIdGenerator$1 = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => {
|
|
3379
3408
|
const generator = () => {
|
|
3380
3409
|
const alphabetLength = alphabet.length;
|
|
@@ -5329,8 +5358,8 @@ function mergeObjects$1(base, overrides) {
|
|
|
5329
5358
|
}
|
|
5330
5359
|
var dataContentSchema = z.union([
|
|
5331
5360
|
z.string(),
|
|
5332
|
-
z.
|
|
5333
|
-
z.
|
|
5361
|
+
z.custom(isUint8Array$1, { message: "Must be a Uint8Array" }),
|
|
5362
|
+
z.custom(isArrayBuffer$1, { message: "Must be an ArrayBuffer" }),
|
|
5334
5363
|
z.custom((value) => {
|
|
5335
5364
|
var _a23, _b;
|
|
5336
5365
|
return (_b = (_a23 = globalThis.Buffer) == null ? void 0 : _a23.isBuffer(value)) != null ? _b : false;
|
|
@@ -6921,7 +6950,7 @@ var doWrap = ({ model, middleware: { transformParams, wrapGenerate, wrapStream,
|
|
|
6921
6950
|
}
|
|
6922
6951
|
};
|
|
6923
6952
|
};
|
|
6924
|
-
// ../../packages/_vendored/ai_v7/dist/dist-
|
|
6953
|
+
// ../../packages/_vendored/ai_v7/dist/dist-CwN1TMYk.js
|
|
6925
6954
|
/**
|
|
6926
6955
|
* Symbol used for identifying AI SDK Error instances.
|
|
6927
6956
|
* Enables checking if an error is an instance of AISDKError across package versions.
|
|
@@ -7053,6 +7082,20 @@ var TypeValidationError = class TypeValidationError extends AISDKError {
|
|
|
7053
7082
|
TransformStream;
|
|
7054
7083
|
new TextDecoder();
|
|
7055
7084
|
const { btoa: btoa$1, atob: atob$2 } = globalThis;
|
|
7085
|
+
const typedArrayTag = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
|
|
7086
|
+
const arrayBufferByteLength = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, "byteLength").get;
|
|
7087
|
+
function isUint8Array(value) {
|
|
7088
|
+
return ArrayBuffer.isView(value) && typedArrayTag.call(value) === "Uint8Array";
|
|
7089
|
+
}
|
|
7090
|
+
function isArrayBuffer(value) {
|
|
7091
|
+
if (typeof value !== "object" || value === null || !("byteLength" in value)) return false;
|
|
7092
|
+
try {
|
|
7093
|
+
arrayBufferByteLength.call(value);
|
|
7094
|
+
return true;
|
|
7095
|
+
} catch {
|
|
7096
|
+
return false;
|
|
7097
|
+
}
|
|
7098
|
+
}
|
|
7056
7099
|
/**
|
|
7057
7100
|
* Creates an ID generator.
|
|
7058
7101
|
* The total length of the ID is the sum of the prefix, separator, and random part length.
|
|
@@ -8401,9 +8444,7 @@ function fixJson(input) {
|
|
|
8401
8444
|
lastValidIndex = i;
|
|
8402
8445
|
stack.pop();
|
|
8403
8446
|
break;
|
|
8404
|
-
default:
|
|
8405
|
-
lastValidIndex = i;
|
|
8406
|
-
processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
|
|
8447
|
+
default: processValueStart(char, i, "INSIDE_ARRAY_AFTER_VALUE");
|
|
8407
8448
|
}
|
|
8408
8449
|
break;
|
|
8409
8450
|
case "INSIDE_ARRAY_AFTER_VALUE":
|
|
@@ -9282,12 +9323,13 @@ function processUIMessageStream({ stream, messageMetadataSchema, dataPartSchemas
|
|
|
9282
9323
|
onError?.(new Error(chunk.errorText));
|
|
9283
9324
|
break;
|
|
9284
9325
|
default: if (isDataUIMessageChunk(chunk)) {
|
|
9285
|
-
|
|
9326
|
+
const dataPartSchema = dataPartSchemas?.[chunk.type.slice(5)];
|
|
9327
|
+
if (dataPartSchema != null) {
|
|
9286
9328
|
const partIdx = state.message.parts.findIndex((p) => "id" in p && "data" in p && p.id === chunk.id && p.type === chunk.type);
|
|
9287
9329
|
const actualPartIdx = partIdx >= 0 ? partIdx : state.message.parts.length;
|
|
9288
9330
|
await validateTypes({
|
|
9289
9331
|
value: chunk.data,
|
|
9290
|
-
schema:
|
|
9332
|
+
schema: dataPartSchema,
|
|
9291
9333
|
context: {
|
|
9292
9334
|
field: `message.parts[${actualPartIdx}].data`,
|
|
9293
9335
|
entityName: chunk.type,
|
|
@@ -9573,8 +9615,8 @@ createIdGenerator({
|
|
|
9573
9615
|
});
|
|
9574
9616
|
const fileInlineDataSchema = z$1.union([
|
|
9575
9617
|
z$1.string(),
|
|
9576
|
-
z$1.
|
|
9577
|
-
z$1.
|
|
9618
|
+
z$1.custom(isUint8Array, { message: "Must be a Uint8Array" }),
|
|
9619
|
+
z$1.custom(isArrayBuffer, { message: "Must be an ArrayBuffer" }),
|
|
9578
9620
|
z$1.custom(isBuffer, { message: "Must be a Buffer" })
|
|
9579
9621
|
]);
|
|
9580
9622
|
const providerReferenceSchema = z$1.record(z$1.string(), z$1.string());
|
|
@@ -11939,15 +11981,121 @@ const CREDENTIAL_HEADER_NAMES = /* @__PURE__ */ new Set([
|
|
|
11939
11981
|
"x-goog-api-key",
|
|
11940
11982
|
"cookie"
|
|
11941
11983
|
]);
|
|
11942
|
-
|
|
11943
|
-
|
|
11944
|
-
|
|
11984
|
+
/** Resolves one Editor agent version selector from the route query. */
|
|
11985
|
+
function resolveAgentVersionFromQuery(query, fallback) {
|
|
11986
|
+
const versionId = query("versionId");
|
|
11987
|
+
const status = query("status");
|
|
11988
|
+
if (versionId && status) throw new Error("Query parameters \"versionId\" and \"status\" are mutually exclusive");
|
|
11989
|
+
if (status && status !== "draft" && status !== "published") throw new Error("Query parameter \"status\" must be \"draft\" or \"published\"");
|
|
11990
|
+
return versionId ? { versionId } : status ? { status } : fallback;
|
|
11991
|
+
}
|
|
11992
|
+
/** Wraps a UI message stream in the response implementation for its AI SDK version. */
|
|
11993
|
+
function createChatUIMessageStreamResponse(stream, version) {
|
|
11994
|
+
if (version === "v7") return createUIMessageStreamResponse({ stream });
|
|
11995
|
+
if (version === "v6") return createUIMessageStreamResponse$1({ stream });
|
|
11996
|
+
return createUIMessageStreamResponse$2({ stream });
|
|
11997
|
+
}
|
|
11998
|
+
/** Resolves the configured agent, including Editor-stored overrides and explicit version selectors. */
|
|
11999
|
+
async function resolveChatAgent({ mastra, agentId, agentVersion, requestContext, defaultToPublished = true }) {
|
|
11945
12000
|
const baseAgent = mastra.getAgentById(agentId);
|
|
11946
12001
|
if (!baseAgent) throw new Error(`Agent ${agentId} not found`);
|
|
11947
|
-
let agentObj = baseAgent;
|
|
11948
12002
|
const editorAgent = mastra.getEditor?.()?.agent;
|
|
11949
|
-
if (editorAgent)
|
|
11950
|
-
|
|
12003
|
+
if (editorAgent) {
|
|
12004
|
+
if (!agentVersion && !defaultToPublished) return baseAgent;
|
|
12005
|
+
return editorAgent.applyStoredOverrides(baseAgent, agentVersion ?? { status: "published" }, requestContext);
|
|
12006
|
+
}
|
|
12007
|
+
if (agentVersion) return mastra.getAgentById(agentId, agentVersion);
|
|
12008
|
+
return baseAgent;
|
|
12009
|
+
}
|
|
12010
|
+
const MASTRA_AUTH_MODE_KEY = "mastra__authMode";
|
|
12011
|
+
/** Selects the FGA provider for the request's trusted authentication mode. */
|
|
12012
|
+
function resolveChatFGAProvider(mastra, requestContext) {
|
|
12013
|
+
const studioFga = mastra.getStudio()?.fga;
|
|
12014
|
+
const serverFga = mastra.getServer()?.fga;
|
|
12015
|
+
if (requestContext?.get(MASTRA_AUTH_MODE_KEY) === "studio" && studioFga) return studioFga;
|
|
12016
|
+
if (serverFga) return serverFga;
|
|
12017
|
+
return studioFga ? null : void 0;
|
|
12018
|
+
}
|
|
12019
|
+
/** Authorizes replay using the same resource ownership and thread FGA rules as run observation. */
|
|
12020
|
+
async function authorizeChatRunObservation({ mastra, agent, runRecord, requestContext }) {
|
|
12021
|
+
const resourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY);
|
|
12022
|
+
const server = mastra.getServer();
|
|
12023
|
+
const fgaProvider = resolveChatFGAProvider(mastra, requestContext);
|
|
12024
|
+
if (fgaProvider === null) return false;
|
|
12025
|
+
if (typeof (server?.auth)?.mapUserToResourceId === "function") {
|
|
12026
|
+
if (resourceId) {
|
|
12027
|
+
if (runRecord.resourceId !== resourceId) return false;
|
|
12028
|
+
} else if (!fgaProvider || !runRecord.threadId) return false;
|
|
12029
|
+
} else if (runRecord.resourceId && runRecord.resourceId !== resourceId) return false;
|
|
12030
|
+
if (!runRecord.threadId) return true;
|
|
12031
|
+
requestContext?.set(MASTRA_THREAD_ID_KEY, runRecord.threadId);
|
|
12032
|
+
const thread = await (await agent.getMemory({ requestContext }))?.getThreadById({ threadId: runRecord.threadId });
|
|
12033
|
+
if (resourceId && thread?.resourceId && thread.resourceId !== resourceId) return false;
|
|
12034
|
+
if (fgaProvider) {
|
|
12035
|
+
const user = requestContext?.get("user");
|
|
12036
|
+
if (!user || typeof user !== "object") return false;
|
|
12037
|
+
try {
|
|
12038
|
+
await MastraMemory.checkThreadFGA({
|
|
12039
|
+
mastra,
|
|
12040
|
+
user,
|
|
12041
|
+
threadId: runRecord.threadId,
|
|
12042
|
+
resourceId: thread?.resourceId ?? runRecord.resourceId ?? resourceId,
|
|
12043
|
+
requestContext,
|
|
12044
|
+
fgaProvider
|
|
12045
|
+
});
|
|
12046
|
+
} catch {
|
|
12047
|
+
return false;
|
|
12048
|
+
}
|
|
12049
|
+
}
|
|
12050
|
+
return true;
|
|
12051
|
+
}
|
|
12052
|
+
/** Converts a Mastra agent stream to the requested AI SDK UI message stream version. */
|
|
12053
|
+
function createChatUIMessageStream({ result, messages, version, lastMessageId, sendStart, sendFinish, sendReasoning, sendSources, includeSubAgentMetadata, experimentalTransform, onError, messageMetadata }) {
|
|
12054
|
+
if (version === "v6" || version === "v7") return (version === "v7" ? createUIMessageStream : createUIMessageStream$1)({
|
|
12055
|
+
originalMessages: messages,
|
|
12056
|
+
execute: async ({ writer }) => {
|
|
12057
|
+
for await (const part of toAISdkStream(result, {
|
|
12058
|
+
from: "agent",
|
|
12059
|
+
version: "v6",
|
|
12060
|
+
lastMessageId,
|
|
12061
|
+
sendStart,
|
|
12062
|
+
sendFinish,
|
|
12063
|
+
sendReasoning,
|
|
12064
|
+
sendSources,
|
|
12065
|
+
includeSubAgentMetadata,
|
|
12066
|
+
experimentalTransform,
|
|
12067
|
+
onError,
|
|
12068
|
+
messageMetadata
|
|
12069
|
+
})) writer.write(part);
|
|
12070
|
+
}
|
|
12071
|
+
});
|
|
12072
|
+
return createUIMessageStream$2({
|
|
12073
|
+
originalMessages: messages,
|
|
12074
|
+
execute: async ({ writer }) => {
|
|
12075
|
+
for await (const part of toAISdkStream(result, {
|
|
12076
|
+
from: "agent",
|
|
12077
|
+
lastMessageId,
|
|
12078
|
+
sendStart,
|
|
12079
|
+
sendFinish,
|
|
12080
|
+
sendReasoning,
|
|
12081
|
+
sendSources,
|
|
12082
|
+
includeSubAgentMetadata,
|
|
12083
|
+
experimentalTransform,
|
|
12084
|
+
onError,
|
|
12085
|
+
messageMetadata
|
|
12086
|
+
})) writer.write(part);
|
|
12087
|
+
}
|
|
12088
|
+
});
|
|
12089
|
+
}
|
|
12090
|
+
async function handleChatStream({ mastra, agentId, agentVersion, params, defaultOptions, experimentalTransform, version = "v5", sendStart = true, sendFinish = true, sendReasoning = false, sendSources = false, includeSubAgentMetadata = true, onError, messageMetadata }) {
|
|
12091
|
+
const { messages, resumeData, runId, requestContext, trigger, ...rest } = params;
|
|
12092
|
+
if (resumeData && !runId) throw new Error("runId is required when resumeData is provided");
|
|
12093
|
+
const agentObj = await resolveChatAgent({
|
|
12094
|
+
mastra,
|
|
12095
|
+
agentId,
|
|
12096
|
+
agentVersion,
|
|
12097
|
+
requestContext
|
|
12098
|
+
});
|
|
11951
12099
|
if (!Array.isArray(messages)) throw new Error("Messages must be an array of UIMessage objects");
|
|
11952
12100
|
let lastMessageId;
|
|
11953
12101
|
let messagesToSend = messages;
|
|
@@ -11997,101 +12145,31 @@ async function handleChatStream({ mastra, agentId, agentVersion, params, default
|
|
|
11997
12145
|
messageMetadata
|
|
11998
12146
|
});
|
|
11999
12147
|
}
|
|
12000
|
-
|
|
12001
|
-
|
|
12002
|
-
|
|
12003
|
-
|
|
12004
|
-
|
|
12005
|
-
|
|
12006
|
-
|
|
12007
|
-
|
|
12008
|
-
|
|
12009
|
-
|
|
12010
|
-
|
|
12011
|
-
|
|
12012
|
-
|
|
12013
|
-
|
|
12014
|
-
|
|
12015
|
-
|
|
12016
|
-
|
|
12017
|
-
|
|
12018
|
-
|
|
12019
|
-
experimentalTransform: effectiveExperimentalTransform,
|
|
12020
|
-
onError,
|
|
12021
|
-
messageMetadata
|
|
12022
|
-
})) writer.write(part);
|
|
12023
|
-
}
|
|
12024
|
-
});
|
|
12025
|
-
return createUIMessageStream$2({
|
|
12026
|
-
originalMessages: messages,
|
|
12027
|
-
execute: async ({ writer }) => {
|
|
12028
|
-
for await (const part of toAISdkStream(result, {
|
|
12029
|
-
from: "agent",
|
|
12030
|
-
lastMessageId,
|
|
12031
|
-
sendStart,
|
|
12032
|
-
sendFinish,
|
|
12033
|
-
sendReasoning,
|
|
12034
|
-
sendSources,
|
|
12035
|
-
includeSubAgentMetadata,
|
|
12036
|
-
experimentalTransform: effectiveExperimentalTransform,
|
|
12037
|
-
onError,
|
|
12038
|
-
messageMetadata
|
|
12039
|
-
})) writer.write(part);
|
|
12040
|
-
}
|
|
12148
|
+
return createChatUIMessageStream({
|
|
12149
|
+
result: resumeData ? structuredOutput ? await agentObj.resumeStream(resumeData, {
|
|
12150
|
+
...baseOptions,
|
|
12151
|
+
structuredOutput
|
|
12152
|
+
}) : await agentObj.resumeStream(resumeData, baseOptions) : structuredOutput ? await agentObj.stream(messagesToSend, {
|
|
12153
|
+
...baseOptions,
|
|
12154
|
+
structuredOutput
|
|
12155
|
+
}) : await agentObj.stream(messagesToSend, baseOptions),
|
|
12156
|
+
messages,
|
|
12157
|
+
version,
|
|
12158
|
+
lastMessageId,
|
|
12159
|
+
sendStart,
|
|
12160
|
+
sendFinish,
|
|
12161
|
+
sendReasoning,
|
|
12162
|
+
sendSources,
|
|
12163
|
+
includeSubAgentMetadata,
|
|
12164
|
+
experimentalTransform: effectiveExperimentalTransform,
|
|
12165
|
+
onError,
|
|
12166
|
+
messageMetadata
|
|
12041
12167
|
});
|
|
12042
12168
|
}
|
|
12043
|
-
|
|
12044
|
-
* Creates a chat route handler for streaming agent conversations using the AI SDK format.
|
|
12045
|
-
*
|
|
12046
|
-
* 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.
|
|
12047
|
-
*
|
|
12048
|
-
* @param {chatRouteOptions} options - Configuration options for the chat route
|
|
12049
|
-
* @param {string} [options.path='/chat/:agentId'] - The route path. Include `:agentId` for dynamic routing
|
|
12050
|
-
* @param {string} [options.agent] - Fixed agent ID when not using dynamic routing
|
|
12051
|
-
* @param {AgentExecutionOptions} [options.defaultOptions] - Default options passed to agent execution
|
|
12052
|
-
* @param {boolean} [options.sendStart=true] - Whether to send start events in the stream
|
|
12053
|
-
* @param {boolean} [options.sendFinish=true] - Whether to send finish events in the stream
|
|
12054
|
-
* @param {boolean} [options.sendReasoning=false] - Whether to include reasoning steps in the stream
|
|
12055
|
-
* @param {boolean} [options.sendSources=false] - Whether to include source citations in the stream
|
|
12056
|
-
* @param {boolean} [options.includeSubAgentMetadata=true] - Whether to emit `data-tool-agent` / `data-tool-agent-step` parts with sub-agent progress
|
|
12057
|
-
* @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`.
|
|
12058
|
-
* @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.
|
|
12059
|
-
* @param {Function} [options.messageMetadata] - Maps stream parts to metadata attached to AI SDK start and finish message parts. Receives `{ part, traceId }`.
|
|
12060
|
-
*
|
|
12061
|
-
* @returns {ReturnType<typeof registerApiRoute>} A registered API route handler
|
|
12062
|
-
*
|
|
12063
|
-
* @throws {Error} When path doesn't include `:agentId` and no fixed agent is specified
|
|
12064
|
-
* @throws {RangeError} When `heartbeatMs` is `NaN`, positive infinity, or greater than 2,147,483,647
|
|
12065
|
-
* @throws {Error} When agent ID is missing at runtime
|
|
12066
|
-
* @throws {Error} When specified agent is not found in Mastra instance
|
|
12067
|
-
*
|
|
12068
|
-
* @example
|
|
12069
|
-
* // Dynamic agent routing
|
|
12070
|
-
* chatRoute({
|
|
12071
|
-
* path: '/chat/:agentId',
|
|
12072
|
-
* });
|
|
12073
|
-
*
|
|
12074
|
-
* @example
|
|
12075
|
-
* // Fixed agent with custom path
|
|
12076
|
-
* chatRoute({
|
|
12077
|
-
* path: '/api/support-chat',
|
|
12078
|
-
* agent: 'support-agent',
|
|
12079
|
-
* defaultOptions: {
|
|
12080
|
-
* maxSteps: 5,
|
|
12081
|
-
* },
|
|
12082
|
-
* });
|
|
12083
|
-
*
|
|
12084
|
-
* @remarks
|
|
12085
|
-
* - The route handler expects a JSON body with a `messages` array
|
|
12086
|
-
* - Messages should follow the format: `{ role: 'user' | 'assistant' | 'system', content: string }`
|
|
12087
|
-
* - The response is a Server-Sent Events (SSE) stream compatible with the selected AI SDK version
|
|
12088
|
-
* - If both `agent` and `:agentId` are present, a warning is logged and the fixed `agent` takes precedence
|
|
12089
|
-
* - Request context from the incoming request overrides `defaultOptions.requestContext` if both are present
|
|
12090
|
-
*/
|
|
12091
|
-
function chatRoute({ path = "/chat/:agentId", agent, defaultOptions, experimentalTransform, version = "v5", agentVersion, sendStart = true, sendFinish = true, sendReasoning = false, sendSources = false, includeSubAgentMetadata = true, heartbeatMs, onError, messageMetadata }) {
|
|
12169
|
+
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 }) {
|
|
12092
12170
|
if (!agent && !path.includes("/:agentId")) throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
|
|
12093
12171
|
assertValidHeartbeatMs(heartbeatMs);
|
|
12094
|
-
|
|
12172
|
+
const postRoute = registerApiRoute(path, {
|
|
12095
12173
|
method: "POST",
|
|
12096
12174
|
openapi: {
|
|
12097
12175
|
summary: "Chat with an agent",
|
|
@@ -12194,22 +12272,29 @@ function chatRoute({ path = "/chat/:agentId", agent, defaultOptions, experimenta
|
|
|
12194
12272
|
let agentToUse = agent;
|
|
12195
12273
|
if (!agent) agentToUse = c.req.param("agentId");
|
|
12196
12274
|
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.`);
|
|
12197
|
-
const
|
|
12275
|
+
const configuredRequestContext = contextRequestContext || defaultOptions?.requestContext || params.requestContext;
|
|
12276
|
+
const effectiveRequestContext = resumable && params.id ? new RequestContext(configuredRequestContext ? configuredRequestContext.entries() : void 0) : configuredRequestContext;
|
|
12277
|
+
if (resumable && params.id) effectiveRequestContext.set(MASTRA_THREAD_ID_KEY, params.id);
|
|
12198
12278
|
if (contextRequestContext && defaultOptions?.requestContext || contextRequestContext && params.requestContext || defaultOptions?.requestContext && params.requestContext) mastra.getLogger()?.warn(`Multiple "requestContext" sources provided. Using priority: middleware > route options > body.`);
|
|
12199
12279
|
if (!agentToUse) throw new Error("Agent ID is required");
|
|
12200
|
-
const
|
|
12201
|
-
const
|
|
12202
|
-
|
|
12203
|
-
|
|
12204
|
-
|
|
12280
|
+
const effectiveAgentVersion = resolveAgentVersionFromQuery((name) => c.req.query(name), agentVersion);
|
|
12281
|
+
const resumableResourceId = (contextRequestContext || defaultOptions?.requestContext)?.get(MASTRA_RESOURCE_ID_KEY);
|
|
12282
|
+
const bodyResourceId = typeof params.memory === "object" ? params.memory?.resource : void 0;
|
|
12283
|
+
const bodyRequestContextResourceId = params.requestContext?.get(MASTRA_RESOURCE_ID_KEY);
|
|
12284
|
+
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);
|
|
12205
12285
|
const handlerOptions = {
|
|
12206
12286
|
mastra,
|
|
12207
12287
|
agentId: agentToUse,
|
|
12208
|
-
agentVersion:
|
|
12288
|
+
agentVersion: effectiveAgentVersion,
|
|
12209
12289
|
params: {
|
|
12210
12290
|
...params,
|
|
12291
|
+
...resumable && params.id ? { memory: {
|
|
12292
|
+
...typeof params.memory === "object" ? params.memory : {},
|
|
12293
|
+
...resumableResourceId ? { resource: resumableResourceId } : {},
|
|
12294
|
+
thread: params.id
|
|
12295
|
+
} } : {},
|
|
12211
12296
|
requestContext: effectiveRequestContext,
|
|
12212
|
-
abortSignal: c.req.raw.signal
|
|
12297
|
+
...!resumable && { abortSignal: c.req.raw.signal }
|
|
12213
12298
|
},
|
|
12214
12299
|
defaultOptions,
|
|
12215
12300
|
experimentalTransform,
|
|
@@ -12220,24 +12305,108 @@ function chatRoute({ path = "/chat/:agentId", agent, defaultOptions, experimenta
|
|
|
12220
12305
|
includeSubAgentMetadata,
|
|
12221
12306
|
onError
|
|
12222
12307
|
};
|
|
12223
|
-
|
|
12224
|
-
if (version === "v7") response = createUIMessageStreamResponse({ stream: await handleChatStream({
|
|
12308
|
+
return withSseHeartbeat(createChatUIMessageStreamResponse(version === "v7" ? await handleChatStream({
|
|
12225
12309
|
...handlerOptions,
|
|
12226
12310
|
version: "v7",
|
|
12227
12311
|
messageMetadata
|
|
12228
|
-
})
|
|
12229
|
-
else if (version === "v6") response = createUIMessageStreamResponse$1({ stream: await handleChatStream({
|
|
12312
|
+
}) : version === "v6" ? await handleChatStream({
|
|
12230
12313
|
...handlerOptions,
|
|
12231
12314
|
version: "v6",
|
|
12232
12315
|
messageMetadata
|
|
12233
|
-
})
|
|
12234
|
-
else response = createUIMessageStreamResponse$2({ stream: await handleChatStream({
|
|
12316
|
+
}) : await handleChatStream({
|
|
12235
12317
|
...handlerOptions,
|
|
12236
12318
|
messageMetadata
|
|
12237
|
-
})
|
|
12238
|
-
return withSseHeartbeat(response, heartbeatMs);
|
|
12319
|
+
}), version), heartbeatMs);
|
|
12239
12320
|
}
|
|
12240
12321
|
});
|
|
12322
|
+
if (!resumable) return postRoute;
|
|
12323
|
+
const reconnectPath = `${path.replace(/\/$/, "")}/:chatId/stream`;
|
|
12324
|
+
return [postRoute, registerApiRoute(reconnectPath, {
|
|
12325
|
+
method: "GET",
|
|
12326
|
+
openapi: {
|
|
12327
|
+
summary: "Reconnect to an agent chat stream",
|
|
12328
|
+
description: "Replay and follow the active agent run for an AI SDK chat",
|
|
12329
|
+
tags: ["ai-sdk"],
|
|
12330
|
+
parameters: [
|
|
12331
|
+
...path.includes(":agentId") ? [{
|
|
12332
|
+
name: "agentId",
|
|
12333
|
+
in: "path",
|
|
12334
|
+
required: true,
|
|
12335
|
+
schema: { type: "string" }
|
|
12336
|
+
}] : [],
|
|
12337
|
+
{
|
|
12338
|
+
name: "chatId",
|
|
12339
|
+
in: "path",
|
|
12340
|
+
required: true,
|
|
12341
|
+
schema: { type: "string" }
|
|
12342
|
+
},
|
|
12343
|
+
{
|
|
12344
|
+
name: "versionId",
|
|
12345
|
+
in: "query",
|
|
12346
|
+
required: false,
|
|
12347
|
+
schema: { type: "string" }
|
|
12348
|
+
},
|
|
12349
|
+
{
|
|
12350
|
+
name: "status",
|
|
12351
|
+
in: "query",
|
|
12352
|
+
required: false,
|
|
12353
|
+
schema: {
|
|
12354
|
+
type: "string",
|
|
12355
|
+
enum: ["draft", "published"]
|
|
12356
|
+
}
|
|
12357
|
+
}
|
|
12358
|
+
],
|
|
12359
|
+
responses: {
|
|
12360
|
+
"200": {
|
|
12361
|
+
description: "Replayable streaming response from the agent run",
|
|
12362
|
+
content: { "text/plain": { schema: { type: "string" } } }
|
|
12363
|
+
},
|
|
12364
|
+
"204": { description: "The chat has no active resumable run" },
|
|
12365
|
+
"404": { description: "The active run does not belong to the current resource or thread" }
|
|
12366
|
+
}
|
|
12367
|
+
},
|
|
12368
|
+
handler: async (c) => {
|
|
12369
|
+
const mastra = c.get("mastra");
|
|
12370
|
+
const requestContext = c.get("requestContext") || (defaultOptions?.requestContext ? new RequestContext(defaultOptions.requestContext.entries()) : void 0);
|
|
12371
|
+
const agentToUse = agent ?? c.req.param("agentId");
|
|
12372
|
+
const chatId = c.req.param("chatId");
|
|
12373
|
+
if (!agentToUse || !chatId) return new Response(null, { status: 204 });
|
|
12374
|
+
const agentObj = await resolveChatAgent({
|
|
12375
|
+
mastra,
|
|
12376
|
+
agentId: agentToUse,
|
|
12377
|
+
agentVersion: resolveAgentVersionFromQuery((name) => c.req.query(name), agentVersion),
|
|
12378
|
+
requestContext,
|
|
12379
|
+
defaultToPublished: false
|
|
12380
|
+
});
|
|
12381
|
+
const resourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY);
|
|
12382
|
+
const runId = agentObj.getActiveThreadRunId({
|
|
12383
|
+
threadId: chatId,
|
|
12384
|
+
resourceId
|
|
12385
|
+
});
|
|
12386
|
+
if (!runId) return new Response(null, { status: 204 });
|
|
12387
|
+
const runRecord = await agentObj.__getRunRecord(runId);
|
|
12388
|
+
if (!runRecord || runRecord.status === "finished") return new Response(null, { status: 204 });
|
|
12389
|
+
if (!await authorizeChatRunObservation({
|
|
12390
|
+
mastra,
|
|
12391
|
+
agent: agentObj,
|
|
12392
|
+
runRecord,
|
|
12393
|
+
requestContext
|
|
12394
|
+
})) return new Response(null, { status: 404 });
|
|
12395
|
+
return withSseHeartbeat(createChatUIMessageStreamResponse(createChatUIMessageStream({
|
|
12396
|
+
result: (await agentObj.observe(runId)).output,
|
|
12397
|
+
messages: [],
|
|
12398
|
+
version,
|
|
12399
|
+
sendStart,
|
|
12400
|
+
sendFinish,
|
|
12401
|
+
sendReasoning,
|
|
12402
|
+
sendSources,
|
|
12403
|
+
includeSubAgentMetadata,
|
|
12404
|
+
experimentalTransform,
|
|
12405
|
+
onError,
|
|
12406
|
+
messageMetadata
|
|
12407
|
+
}), version), heartbeatMs);
|
|
12408
|
+
}
|
|
12409
|
+
})];
|
|
12241
12410
|
}
|
|
12242
12411
|
// src/workflow-route.ts
|
|
12243
12412
|
async function handleWorkflowStream({ mastra, workflowId, params, version = "v5", includeTextStreamParts = true, sendReasoning = false, sendSources = false }) {
|
|
@@ -12866,7 +13035,7 @@ var StreamOutputAccumulator = class {
|
|
|
12866
13035
|
*/
|
|
12867
13036
|
function createProcessorMiddleware(options) {
|
|
12868
13037
|
const { inputProcessors = [], outputProcessors = [], memory } = options;
|
|
12869
|
-
const requestContext = new RequestContext();
|
|
13038
|
+
const requestContext = new RequestContext$1();
|
|
12870
13039
|
if (memory) requestContext.set("MastraMemory", {
|
|
12871
13040
|
thread: memory.threadId ? { id: memory.threadId } : void 0,
|
|
12872
13041
|
resourceId: memory.resourceId,
|