@mastra/ai-sdk 1.11.3 → 1.12.0-alpha.1

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.
Files changed (48) hide show
  1. package/dist/_types/{@internal_ai-sdk-v5 → @internal_ai-sdk-v5@0.0.95}/dist/index.d.ts +2 -2
  2. package/dist/_types/{@internal_ai-v6 → @internal_ai-v6@0.0.95}/dist/index.d.ts +99 -18
  3. package/dist/_types/{@internal_ai-v7 → @internal_ai-v7@0.0.95}/dist/index.d.ts +297 -94
  4. package/dist/chat-route.d.ts +21 -5
  5. package/dist/chat-route.d.ts.map +1 -1
  6. package/dist/convert-streams.d.ts +3 -3
  7. package/dist/docs/SKILL.md +49 -0
  8. package/dist/docs/assets/SOURCE_MAP.json +77 -0
  9. package/dist/docs/references/docs-guides-streaming.md +341 -0
  10. package/dist/docs/references/docs-memory-message-history.md +424 -0
  11. package/dist/docs/references/docs-server-custom-api-routes.md +379 -0
  12. package/dist/docs/references/integrations-agentic-ui-ai-sdk-ui.md +1700 -0
  13. package/dist/docs/references/reference-ai-sdk-chat-route.md +139 -0
  14. package/dist/docs/references/reference-ai-sdk-handle-chat-stream.md +101 -0
  15. package/dist/docs/references/reference-ai-sdk-handle-network-stream.md +49 -0
  16. package/dist/docs/references/reference-ai-sdk-handle-workflow-stream.md +63 -0
  17. package/dist/docs/references/reference-ai-sdk-network-route.md +86 -0
  18. package/dist/docs/references/reference-ai-sdk-overview.md +144 -0
  19. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-messages.md +115 -0
  20. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-stream.md +286 -0
  21. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v4-messages.md +83 -0
  22. package/dist/docs/references/reference-ai-sdk-to-ai-sdk-v5-messages.md +80 -0
  23. package/dist/docs/references/reference-ai-sdk-with-mastra.md +67 -0
  24. package/dist/docs/references/reference-ai-sdk-with-sse-heartbeat.md +49 -0
  25. package/dist/docs/references/reference-ai-sdk-workflow-route.md +87 -0
  26. package/dist/docs/references/reference-ai-sdk-workflow-snapshot-to-stream.md +55 -0
  27. package/dist/docs/references/reference-client-js-agents.md +1112 -0
  28. package/dist/docs/references/reference-memory-recall.md +169 -0
  29. package/dist/docs/references/reference-streaming-agents-stream.md +496 -0
  30. package/dist/docs/references/reference-streaming-smoothStream.md +137 -0
  31. package/dist/helpers.d.ts +4 -3
  32. package/dist/helpers.d.ts.map +1 -1
  33. package/dist/index.cjs +306 -130
  34. package/dist/index.cjs.map +1 -1
  35. package/dist/index.js +308 -132
  36. package/dist/index.js.map +1 -1
  37. package/dist/middleware.d.ts +2 -2
  38. package/dist/public-types.d.ts +3 -3
  39. package/dist/transformers.d.ts +28 -23
  40. package/dist/transformers.d.ts.map +1 -1
  41. package/package.json +19 -18
  42. /package/dist/_types/{@ai-sdk_provider → @ai-sdk_provider@2.0.5}/dist/index.d.ts +0 -0
  43. /package/dist/_types/{@ai-sdk_provider → @ai-sdk_provider@2.0.5}/package.json +0 -0
  44. /package/dist/_types/{@internal_ai-sdk-v5 → @internal_ai-sdk-v5@0.0.95}/package.json +0 -0
  45. /package/dist/_types/{@internal_ai-v6 → @internal_ai-v6@0.0.95}/package.json +0 -0
  46. /package/dist/_types/{@internal_ai-v7 → @internal_ai-v7@0.0.95}/package.json +0 -0
  47. /package/dist/_types/{@types_json-schema → @types_json-schema@7.0.15}/index.d.ts +0 -0
  48. /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-DRvrQv6K.js
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.instanceof(Uint8Array),
2040
- z.instanceof(ArrayBuffer),
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-Dl1sIpsh.js
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.instanceof(Uint8Array),
5333
- z.instanceof(ArrayBuffer),
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-5fMURLh0.js
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
- if (dataPartSchemas?.[chunk.type] != null) {
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: dataPartSchemas[chunk.type],
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.instanceof(Uint8Array),
9577
- z$1.instanceof(ArrayBuffer),
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());
@@ -9997,7 +10039,7 @@ function convertBackgroundTaskChunkToDataChunk(chunk) {
9997
10039
  }
9998
10040
  };
9999
10041
  }
10000
- function convertMastraChunkToAISDKBase({ chunk, mode = "stream", normalizeWarnings, normalizeUsage, normalizeFinishReason, includeRawFinishReason = false }) {
10042
+ function convertMastraChunkToAISDKBase({ chunk, mode = "stream", normalizeWarnings, normalizeUsage, normalizeFinishReason, includeRawFinishReason = false, includeToolTitle = false }) {
10001
10043
  const displayInputTransform = getTransformedToolPayload(chunk.metadata, "display", "input-available");
10002
10044
  const displayInputDeltaTransform = getTransformedToolPayload(chunk.metadata, "display", "input-delta");
10003
10045
  const displayOutputTransform = getTransformedToolPayload(chunk.metadata, "display", "output-available");
@@ -10084,6 +10126,7 @@ function convertMastraChunkToAISDKBase({ chunk, mode = "stream", normalizeWarnin
10084
10126
  providerMetadata: chunk.payload.providerMetadata,
10085
10127
  providerExecuted: chunk.payload.providerExecuted,
10086
10128
  toolName: chunk.payload.toolName,
10129
+ ...includeToolTitle && chunk.payload.title != null ? { title: chunk.payload.title } : {},
10087
10130
  input: hasTransformedToolPayload(displayInputTransform) ? displayInputTransform.transformed : chunk.payload.args,
10088
10131
  ...chunk.payload.observability ? { observability: chunk.payload.observability } : {},
10089
10132
  ...chunk.payload.toolMetadata ? { toolMetadata: chunk.payload.toolMetadata } : {}
@@ -10151,6 +10194,7 @@ function convertMastraChunkToAISDKBase({ chunk, mode = "stream", normalizeWarnin
10151
10194
  type: "tool-input-start",
10152
10195
  id: chunk.payload.toolCallId,
10153
10196
  toolName: chunk.payload.toolName,
10197
+ ...includeToolTitle && chunk.payload.title != null ? { title: chunk.payload.title } : {},
10154
10198
  dynamic: !!chunk.payload.dynamic,
10155
10199
  providerMetadata: chunk.payload.providerMetadata,
10156
10200
  providerExecuted: chunk.payload.providerExecuted,
@@ -10343,7 +10387,8 @@ function convertMastraChunkToAISDKv6({ chunk, mode = "stream" }) {
10343
10387
  normalizeWarnings: normalizeV6Warnings,
10344
10388
  normalizeUsage: normalizeV6Usage,
10345
10389
  normalizeFinishReason: toAISDKFinishReasonV6,
10346
- includeRawFinishReason: true
10390
+ includeRawFinishReason: true,
10391
+ includeToolTitle: true
10347
10392
  });
10348
10393
  }
10349
10394
  function createToolOutputAncestryEntry(toolCallId, toolName) {
@@ -10454,10 +10499,12 @@ function convertFullStreamChunkToUIMessageStream({ part, messageMetadataValue, s
10454
10499
  return;
10455
10500
  case "tool-input-start": {
10456
10501
  const toolMetadata = part.toolMetadata;
10502
+ const title = part.title;
10457
10503
  return {
10458
10504
  type: "tool-input-start",
10459
10505
  toolCallId: part.id,
10460
10506
  toolName: part.toolName,
10507
+ ...title != null ? { title } : {},
10461
10508
  ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},
10462
10509
  ...part.dynamic != null ? { dynamic: part.dynamic } : {},
10463
10510
  ...toolMetadata != null ? { toolMetadata } : {}
@@ -10471,10 +10518,12 @@ function convertFullStreamChunkToUIMessageStream({ part, messageMetadataValue, s
10471
10518
  case "tool-call": {
10472
10519
  const observability = part.observability;
10473
10520
  const toolMetadata = part.toolMetadata;
10521
+ const title = part.title;
10474
10522
  return {
10475
10523
  type: "tool-input-available",
10476
10524
  toolCallId: part.toolCallId,
10477
10525
  toolName: part.toolName,
10526
+ ...title != null ? { title } : {},
10478
10527
  input: part.input,
10479
10528
  ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},
10480
10529
  ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},
@@ -11939,15 +11988,121 @@ const CREDENTIAL_HEADER_NAMES = /* @__PURE__ */ new Set([
11939
11988
  "x-goog-api-key",
11940
11989
  "cookie"
11941
11990
  ]);
11942
- async function handleChatStream({ mastra, agentId, agentVersion, params, defaultOptions, experimentalTransform, version = "v5", sendStart = true, sendFinish = true, sendReasoning = false, sendSources = false, includeSubAgentMetadata = true, onError, messageMetadata }) {
11943
- const { messages, resumeData, runId, requestContext, trigger, ...rest } = params;
11944
- if (resumeData && !runId) throw new Error("runId is required when resumeData is provided");
11991
+ /** Resolves one Editor agent version selector from the route query. */
11992
+ function resolveAgentVersionFromQuery(query, fallback) {
11993
+ const versionId = query("versionId");
11994
+ const status = query("status");
11995
+ if (versionId && status) throw new Error("Query parameters \"versionId\" and \"status\" are mutually exclusive");
11996
+ if (status && status !== "draft" && status !== "published") throw new Error("Query parameter \"status\" must be \"draft\" or \"published\"");
11997
+ return versionId ? { versionId } : status ? { status } : fallback;
11998
+ }
11999
+ /** Wraps a UI message stream in the response implementation for its AI SDK version. */
12000
+ function createChatUIMessageStreamResponse(stream, version) {
12001
+ if (version === "v7") return createUIMessageStreamResponse({ stream });
12002
+ if (version === "v6") return createUIMessageStreamResponse$1({ stream });
12003
+ return createUIMessageStreamResponse$2({ stream });
12004
+ }
12005
+ /** Resolves the configured agent, including Editor-stored overrides and explicit version selectors. */
12006
+ async function resolveChatAgent({ mastra, agentId, agentVersion, requestContext, defaultToPublished = true }) {
11945
12007
  const baseAgent = mastra.getAgentById(agentId);
11946
12008
  if (!baseAgent) throw new Error(`Agent ${agentId} not found`);
11947
- let agentObj = baseAgent;
11948
12009
  const editorAgent = mastra.getEditor?.()?.agent;
11949
- if (editorAgent) agentObj = await editorAgent.applyStoredOverrides(baseAgent, agentVersion ?? { status: "published" }, requestContext);
11950
- else if (agentVersion) agentObj = await mastra.getAgentById(agentId, agentVersion);
12010
+ if (editorAgent) {
12011
+ if (!agentVersion && !defaultToPublished) return baseAgent;
12012
+ return editorAgent.applyStoredOverrides(baseAgent, agentVersion ?? { status: "published" }, requestContext);
12013
+ }
12014
+ if (agentVersion) return mastra.getAgentById(agentId, agentVersion);
12015
+ return baseAgent;
12016
+ }
12017
+ const MASTRA_AUTH_MODE_KEY = "mastra__authMode";
12018
+ /** Selects the FGA provider for the request's trusted authentication mode. */
12019
+ function resolveChatFGAProvider(mastra, requestContext) {
12020
+ const studioFga = mastra.getStudio()?.fga;
12021
+ const serverFga = mastra.getServer()?.fga;
12022
+ if (requestContext?.get(MASTRA_AUTH_MODE_KEY) === "studio" && studioFga) return studioFga;
12023
+ if (serverFga) return serverFga;
12024
+ return studioFga ? null : void 0;
12025
+ }
12026
+ /** Authorizes replay using the same resource ownership and thread FGA rules as run observation. */
12027
+ async function authorizeChatRunObservation({ mastra, agent, runRecord, requestContext }) {
12028
+ const resourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY);
12029
+ const server = mastra.getServer();
12030
+ const fgaProvider = resolveChatFGAProvider(mastra, requestContext);
12031
+ if (fgaProvider === null) return false;
12032
+ if (typeof (server?.auth)?.mapUserToResourceId === "function") {
12033
+ if (resourceId) {
12034
+ if (runRecord.resourceId !== resourceId) return false;
12035
+ } else if (!fgaProvider || !runRecord.threadId) return false;
12036
+ } else if (runRecord.resourceId && runRecord.resourceId !== resourceId) return false;
12037
+ if (!runRecord.threadId) return true;
12038
+ requestContext?.set(MASTRA_THREAD_ID_KEY, runRecord.threadId);
12039
+ const thread = await (await agent.getMemory({ requestContext }))?.getThreadById({ threadId: runRecord.threadId });
12040
+ if (resourceId && thread?.resourceId && thread.resourceId !== resourceId) return false;
12041
+ if (fgaProvider) {
12042
+ const user = requestContext?.get("user");
12043
+ if (!user || typeof user !== "object") return false;
12044
+ try {
12045
+ await MastraMemory.checkThreadFGA({
12046
+ mastra,
12047
+ user,
12048
+ threadId: runRecord.threadId,
12049
+ resourceId: thread?.resourceId ?? runRecord.resourceId ?? resourceId,
12050
+ requestContext,
12051
+ fgaProvider
12052
+ });
12053
+ } catch {
12054
+ return false;
12055
+ }
12056
+ }
12057
+ return true;
12058
+ }
12059
+ /** Converts a Mastra agent stream to the requested AI SDK UI message stream version. */
12060
+ function createChatUIMessageStream({ result, messages, version, lastMessageId, sendStart, sendFinish, sendReasoning, sendSources, includeSubAgentMetadata, experimentalTransform, onError, messageMetadata }) {
12061
+ if (version === "v6" || version === "v7") return (version === "v7" ? createUIMessageStream : createUIMessageStream$1)({
12062
+ originalMessages: messages,
12063
+ execute: async ({ writer }) => {
12064
+ for await (const part of toAISdkStream(result, {
12065
+ from: "agent",
12066
+ version: "v6",
12067
+ lastMessageId,
12068
+ sendStart,
12069
+ sendFinish,
12070
+ sendReasoning,
12071
+ sendSources,
12072
+ includeSubAgentMetadata,
12073
+ experimentalTransform,
12074
+ onError,
12075
+ messageMetadata
12076
+ })) writer.write(part);
12077
+ }
12078
+ });
12079
+ return createUIMessageStream$2({
12080
+ originalMessages: messages,
12081
+ execute: async ({ writer }) => {
12082
+ for await (const part of toAISdkStream(result, {
12083
+ from: "agent",
12084
+ lastMessageId,
12085
+ sendStart,
12086
+ sendFinish,
12087
+ sendReasoning,
12088
+ sendSources,
12089
+ includeSubAgentMetadata,
12090
+ experimentalTransform,
12091
+ onError,
12092
+ messageMetadata
12093
+ })) writer.write(part);
12094
+ }
12095
+ });
12096
+ }
12097
+ async function handleChatStream({ mastra, agentId, agentVersion, params, defaultOptions, experimentalTransform, version = "v5", sendStart = true, sendFinish = true, sendReasoning = false, sendSources = false, includeSubAgentMetadata = true, onError, messageMetadata }) {
12098
+ const { messages, resumeData, runId, requestContext, trigger, ...rest } = params;
12099
+ if (resumeData && !runId) throw new Error("runId is required when resumeData is provided");
12100
+ const agentObj = await resolveChatAgent({
12101
+ mastra,
12102
+ agentId,
12103
+ agentVersion,
12104
+ requestContext
12105
+ });
11951
12106
  if (!Array.isArray(messages)) throw new Error("Messages must be an array of UIMessage objects");
11952
12107
  let lastMessageId;
11953
12108
  let messagesToSend = messages;
@@ -11997,101 +12152,31 @@ async function handleChatStream({ mastra, agentId, agentVersion, params, default
11997
12152
  messageMetadata
11998
12153
  });
11999
12154
  }
12000
- const result = resumeData ? structuredOutput ? await agentObj.resumeStream(resumeData, {
12001
- ...baseOptions,
12002
- structuredOutput
12003
- }) : await agentObj.resumeStream(resumeData, baseOptions) : structuredOutput ? await agentObj.stream(messagesToSend, {
12004
- ...baseOptions,
12005
- structuredOutput
12006
- }) : await agentObj.stream(messagesToSend, baseOptions);
12007
- if (version === "v6" || version === "v7") return (version === "v7" ? createUIMessageStream : createUIMessageStream$1)({
12008
- originalMessages: messages,
12009
- execute: async ({ writer }) => {
12010
- for await (const part of toAISdkStream(result, {
12011
- from: "agent",
12012
- version: "v6",
12013
- lastMessageId,
12014
- sendStart,
12015
- sendFinish,
12016
- sendReasoning,
12017
- sendSources,
12018
- includeSubAgentMetadata,
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
- }
12155
+ return createChatUIMessageStream({
12156
+ result: resumeData ? structuredOutput ? await agentObj.resumeStream(resumeData, {
12157
+ ...baseOptions,
12158
+ structuredOutput
12159
+ }) : await agentObj.resumeStream(resumeData, baseOptions) : structuredOutput ? await agentObj.stream(messagesToSend, {
12160
+ ...baseOptions,
12161
+ structuredOutput
12162
+ }) : await agentObj.stream(messagesToSend, baseOptions),
12163
+ messages,
12164
+ version,
12165
+ lastMessageId,
12166
+ sendStart,
12167
+ sendFinish,
12168
+ sendReasoning,
12169
+ sendSources,
12170
+ includeSubAgentMetadata,
12171
+ experimentalTransform: effectiveExperimentalTransform,
12172
+ onError,
12173
+ messageMetadata
12041
12174
  });
12042
12175
  }
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 }) {
12176
+ 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
12177
  if (!agent && !path.includes("/:agentId")) throw new Error("Path must include :agentId to route to the correct agent or pass the agent explicitly");
12093
12178
  assertValidHeartbeatMs(heartbeatMs);
12094
- return registerApiRoute(path, {
12179
+ const postRoute = registerApiRoute(path, {
12095
12180
  method: "POST",
12096
12181
  openapi: {
12097
12182
  summary: "Chat with an agent",
@@ -12194,22 +12279,29 @@ function chatRoute({ path = "/chat/:agentId", agent, defaultOptions, experimenta
12194
12279
  let agentToUse = agent;
12195
12280
  if (!agent) agentToUse = c.req.param("agentId");
12196
12281
  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 effectiveRequestContext = contextRequestContext || defaultOptions?.requestContext || params.requestContext;
12282
+ const configuredRequestContext = contextRequestContext || defaultOptions?.requestContext || params.requestContext;
12283
+ const effectiveRequestContext = resumable && params.id ? new RequestContext(configuredRequestContext ? configuredRequestContext.entries() : void 0) : configuredRequestContext;
12284
+ if (resumable && params.id) effectiveRequestContext.set(MASTRA_THREAD_ID_KEY, params.id);
12198
12285
  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
12286
  if (!agentToUse) throw new Error("Agent ID is required");
12200
- const queryVersionId = c.req.query("versionId");
12201
- const rawStatus = c.req.query("status");
12202
- if (queryVersionId && rawStatus) throw new Error("Query parameters \"versionId\" and \"status\" are mutually exclusive");
12203
- if (rawStatus && rawStatus !== "draft" && rawStatus !== "published") throw new Error("Query parameter \"status\" must be \"draft\" or \"published\"");
12204
- const queryStatus = rawStatus;
12287
+ const effectiveAgentVersion = resolveAgentVersionFromQuery((name) => c.req.query(name), agentVersion);
12288
+ const resumableResourceId = (contextRequestContext || defaultOptions?.requestContext)?.get(MASTRA_RESOURCE_ID_KEY);
12289
+ const bodyResourceId = typeof params.memory === "object" ? params.memory?.resource : void 0;
12290
+ const bodyRequestContextResourceId = params.requestContext?.get(MASTRA_RESOURCE_ID_KEY);
12291
+ 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
12292
  const handlerOptions = {
12206
12293
  mastra,
12207
12294
  agentId: agentToUse,
12208
- agentVersion: queryVersionId ? { versionId: queryVersionId } : queryStatus ? { status: queryStatus } : agentVersion,
12295
+ agentVersion: effectiveAgentVersion,
12209
12296
  params: {
12210
12297
  ...params,
12298
+ ...resumable && params.id ? { memory: {
12299
+ ...typeof params.memory === "object" ? params.memory : {},
12300
+ ...resumableResourceId ? { resource: resumableResourceId } : {},
12301
+ thread: params.id
12302
+ } } : {},
12211
12303
  requestContext: effectiveRequestContext,
12212
- abortSignal: c.req.raw.signal
12304
+ ...!resumable && { abortSignal: c.req.raw.signal }
12213
12305
  },
12214
12306
  defaultOptions,
12215
12307
  experimentalTransform,
@@ -12220,24 +12312,108 @@ function chatRoute({ path = "/chat/:agentId", agent, defaultOptions, experimenta
12220
12312
  includeSubAgentMetadata,
12221
12313
  onError
12222
12314
  };
12223
- let response;
12224
- if (version === "v7") response = createUIMessageStreamResponse({ stream: await handleChatStream({
12315
+ return withSseHeartbeat(createChatUIMessageStreamResponse(version === "v7" ? await handleChatStream({
12225
12316
  ...handlerOptions,
12226
12317
  version: "v7",
12227
12318
  messageMetadata
12228
- }) });
12229
- else if (version === "v6") response = createUIMessageStreamResponse$1({ stream: await handleChatStream({
12319
+ }) : version === "v6" ? await handleChatStream({
12230
12320
  ...handlerOptions,
12231
12321
  version: "v6",
12232
12322
  messageMetadata
12233
- }) });
12234
- else response = createUIMessageStreamResponse$2({ stream: await handleChatStream({
12323
+ }) : await handleChatStream({
12235
12324
  ...handlerOptions,
12236
12325
  messageMetadata
12237
- }) });
12238
- return withSseHeartbeat(response, heartbeatMs);
12326
+ }), version), heartbeatMs);
12239
12327
  }
12240
12328
  });
12329
+ if (!resumable) return postRoute;
12330
+ const reconnectPath = `${path.replace(/\/$/, "")}/:chatId/stream`;
12331
+ return [postRoute, registerApiRoute(reconnectPath, {
12332
+ method: "GET",
12333
+ openapi: {
12334
+ summary: "Reconnect to an agent chat stream",
12335
+ description: "Replay and follow the active agent run for an AI SDK chat",
12336
+ tags: ["ai-sdk"],
12337
+ parameters: [
12338
+ ...path.includes(":agentId") ? [{
12339
+ name: "agentId",
12340
+ in: "path",
12341
+ required: true,
12342
+ schema: { type: "string" }
12343
+ }] : [],
12344
+ {
12345
+ name: "chatId",
12346
+ in: "path",
12347
+ required: true,
12348
+ schema: { type: "string" }
12349
+ },
12350
+ {
12351
+ name: "versionId",
12352
+ in: "query",
12353
+ required: false,
12354
+ schema: { type: "string" }
12355
+ },
12356
+ {
12357
+ name: "status",
12358
+ in: "query",
12359
+ required: false,
12360
+ schema: {
12361
+ type: "string",
12362
+ enum: ["draft", "published"]
12363
+ }
12364
+ }
12365
+ ],
12366
+ responses: {
12367
+ "200": {
12368
+ description: "Replayable streaming response from the agent run",
12369
+ content: { "text/plain": { schema: { type: "string" } } }
12370
+ },
12371
+ "204": { description: "The chat has no active resumable run" },
12372
+ "404": { description: "The active run does not belong to the current resource or thread" }
12373
+ }
12374
+ },
12375
+ handler: async (c) => {
12376
+ const mastra = c.get("mastra");
12377
+ const requestContext = c.get("requestContext") || (defaultOptions?.requestContext ? new RequestContext(defaultOptions.requestContext.entries()) : void 0);
12378
+ const agentToUse = agent ?? c.req.param("agentId");
12379
+ const chatId = c.req.param("chatId");
12380
+ if (!agentToUse || !chatId) return new Response(null, { status: 204 });
12381
+ const agentObj = await resolveChatAgent({
12382
+ mastra,
12383
+ agentId: agentToUse,
12384
+ agentVersion: resolveAgentVersionFromQuery((name) => c.req.query(name), agentVersion),
12385
+ requestContext,
12386
+ defaultToPublished: false
12387
+ });
12388
+ const resourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY);
12389
+ const runId = agentObj.getActiveThreadRunId({
12390
+ threadId: chatId,
12391
+ resourceId
12392
+ });
12393
+ if (!runId) return new Response(null, { status: 204 });
12394
+ const runRecord = await agentObj.__getRunRecord(runId);
12395
+ if (!runRecord || runRecord.status === "finished") return new Response(null, { status: 204 });
12396
+ if (!await authorizeChatRunObservation({
12397
+ mastra,
12398
+ agent: agentObj,
12399
+ runRecord,
12400
+ requestContext
12401
+ })) return new Response(null, { status: 404 });
12402
+ return withSseHeartbeat(createChatUIMessageStreamResponse(createChatUIMessageStream({
12403
+ result: (await agentObj.observe(runId)).output,
12404
+ messages: [],
12405
+ version,
12406
+ sendStart,
12407
+ sendFinish,
12408
+ sendReasoning,
12409
+ sendSources,
12410
+ includeSubAgentMetadata,
12411
+ experimentalTransform,
12412
+ onError,
12413
+ messageMetadata
12414
+ }), version), heartbeatMs);
12415
+ }
12416
+ })];
12241
12417
  }
12242
12418
  // src/workflow-route.ts
12243
12419
  async function handleWorkflowStream({ mastra, workflowId, params, version = "v5", includeTextStreamParts = true, sendReasoning = false, sendSources = false }) {
@@ -12866,7 +13042,7 @@ var StreamOutputAccumulator = class {
12866
13042
  */
12867
13043
  function createProcessorMiddleware(options) {
12868
13044
  const { inputProcessors = [], outputProcessors = [], memory } = options;
12869
- const requestContext = new RequestContext();
13045
+ const requestContext = new RequestContext$1();
12870
13046
  if (memory) requestContext.set("MastraMemory", {
12871
13047
  thread: memory.threadId ? { id: memory.threadId } : void 0,
12872
13048
  resourceId: memory.resourceId,