@mastra/ai-sdk 1.0.0-beta.3 → 1.0.0-beta.5

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/index.js CHANGED
@@ -8,6 +8,31 @@ import { DefaultGeneratedFile, DefaultGeneratedFileWithType } from '@mastra/core
8
8
  var isDataChunkType = (chunk) => {
9
9
  return chunk && typeof chunk === "object" && "type" in chunk && chunk.type?.startsWith("data-");
10
10
  };
11
+ var isMastraTextStreamChunk = (chunk) => {
12
+ return chunk && typeof chunk === "object" && "type" in chunk && typeof chunk.type === "string" && [
13
+ "text-start",
14
+ "text-delta",
15
+ "text-end",
16
+ "reasoning-start",
17
+ "reasoning-delta",
18
+ "reasoning-end",
19
+ "file",
20
+ "source",
21
+ "tool-input-start",
22
+ "tool-input-delta",
23
+ "tool-call",
24
+ "tool-result",
25
+ "tool-error",
26
+ "error",
27
+ "start-step",
28
+ "finish-step",
29
+ "start",
30
+ "finish",
31
+ "abort",
32
+ "tool-input-end",
33
+ "raw"
34
+ ].includes(chunk.type);
35
+ };
11
36
  function safeParseErrorObject(obj) {
12
37
  if (typeof obj !== "object" || obj === null) {
13
38
  return String(obj);
@@ -138,6 +163,28 @@ function convertMastraChunkToAISDKv5({
138
163
  toolName: chunk.payload.toolName,
139
164
  input: chunk.payload.args
140
165
  };
166
+ case "tool-call-approval":
167
+ return {
168
+ type: "data-tool-call-approval",
169
+ id: chunk.payload.toolCallId,
170
+ data: {
171
+ runId: chunk.runId,
172
+ toolCallId: chunk.payload.toolCallId,
173
+ toolName: chunk.payload.toolName,
174
+ args: chunk.payload.args
175
+ }
176
+ };
177
+ case "tool-call-suspended":
178
+ return {
179
+ type: "data-tool-call-suspended",
180
+ id: chunk.payload.toolCallId,
181
+ data: {
182
+ runId: chunk.runId,
183
+ toolCallId: chunk.payload.toolCallId,
184
+ toolName: chunk.payload.toolName,
185
+ suspendPayload: chunk.payload.suspendPayload
186
+ }
187
+ };
141
188
  case "tool-call-input-streaming-start":
142
189
  return {
143
190
  type: "tool-input-start",
@@ -467,7 +514,10 @@ function convertFullStreamChunkToUIMessageStream({
467
514
  }
468
515
 
469
516
  // src/transformers.ts
470
- function WorkflowStreamToAISDKTransformer() {
517
+ var PRIMITIVE_CACHE_SYMBOL = Symbol("primitive-cache");
518
+ function WorkflowStreamToAISDKTransformer({
519
+ includeTextStreamParts
520
+ } = {}) {
471
521
  const bufferedWorkflows = /* @__PURE__ */ new Map();
472
522
  return new TransformStream({
473
523
  start(controller) {
@@ -481,7 +531,7 @@ function WorkflowStreamToAISDKTransformer() {
481
531
  });
482
532
  },
483
533
  transform(chunk, controller) {
484
- const transformed = transformWorkflow(chunk, bufferedWorkflows);
534
+ const transformed = transformWorkflow(chunk, bufferedWorkflows, false, includeTextStreamParts);
485
535
  if (transformed) controller.enqueue(transformed);
486
536
  }
487
537
  });
@@ -510,7 +560,9 @@ function AgentStreamToAISDKTransformer({
510
560
  sendStart,
511
561
  sendFinish,
512
562
  sendReasoning,
513
- sendSources
563
+ sendSources,
564
+ messageMetadata,
565
+ onError
514
566
  }) {
515
567
  let bufferedSteps = /* @__PURE__ */ new Map();
516
568
  let tripwireOccurred = false;
@@ -528,11 +580,12 @@ function AgentStreamToAISDKTransformer({
528
580
  part,
529
581
  sendReasoning,
530
582
  sendSources,
583
+ messageMetadataValue: messageMetadata?.({ part }),
531
584
  sendStart,
532
585
  sendFinish,
533
586
  responseMessageId: lastMessageId,
534
587
  onError(error) {
535
- return safeParseErrorObject(error);
588
+ return onError ? onError(error) : safeParseErrorObject(error);
536
589
  }
537
590
  });
538
591
  if (transformedChunk) {
@@ -699,7 +752,7 @@ function transformAgent(payload, bufferedSteps) {
699
752
  }
700
753
  return null;
701
754
  }
702
- function transformWorkflow(payload, bufferedWorkflows, isNested) {
755
+ function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStreamParts) {
703
756
  switch (payload.type) {
704
757
  case "workflow-start":
705
758
  bufferedWorkflows.set(payload.runId, {
@@ -792,6 +845,29 @@ function transformWorkflow(payload, bufferedWorkflows, isNested) {
792
845
  }
793
846
  };
794
847
  }
848
+ case "workflow-step-output": {
849
+ const output = payload.payload.output;
850
+ if (includeTextStreamParts && output && isMastraTextStreamChunk(output)) {
851
+ const part = convertMastraChunkToAISDKv5({ chunk: output, mode: "stream" });
852
+ const transformedChunk = convertFullStreamChunkToUIMessageStream({
853
+ part,
854
+ onError(error) {
855
+ return safeParseErrorObject(error);
856
+ }
857
+ });
858
+ return transformedChunk;
859
+ }
860
+ if (output && isDataChunkType(output)) {
861
+ if (!("data" in output)) {
862
+ throw new Error(
863
+ `UI Messages require a data property when using data- prefixed chunks
864
+ ${JSON.stringify(output)}`
865
+ );
866
+ }
867
+ return output;
868
+ }
869
+ return null;
870
+ }
795
871
  default: {
796
872
  if (isDataChunkType(payload)) {
797
873
  if (!("data" in payload)) {
@@ -811,12 +887,29 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
811
887
  case "routing-agent-start": {
812
888
  if (!bufferedNetworks.has(payload.runId)) {
813
889
  bufferedNetworks.set(payload.runId, {
814
- name: payload.payload.agentId,
890
+ name: payload.payload.networkId,
815
891
  steps: [],
816
892
  usage: null,
817
893
  output: null
818
894
  });
819
895
  }
896
+ const current = bufferedNetworks.get(payload.runId);
897
+ current.steps.push({
898
+ id: payload.payload.runId,
899
+ name: payload.payload.agentId,
900
+ status: "running",
901
+ iteration: payload.payload.inputData.iteration,
902
+ input: {
903
+ task: payload.payload.inputData.task,
904
+ threadId: payload.payload.inputData.threadId,
905
+ threadResourceId: payload.payload.inputData.threadResourceId
906
+ },
907
+ output: "",
908
+ task: null,
909
+ suspendPayload: null,
910
+ resumePayload: null,
911
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
912
+ });
820
913
  return {
821
914
  type: isNested ? "data-tool-network" : "data-network",
822
915
  id: payload.runId,
@@ -847,14 +940,19 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
847
940
  };
848
941
  }
849
942
  case "agent-execution-start": {
850
- const current = bufferedNetworks.get(payload.runId) || { name: "", steps: [], usage: null, output: null };
943
+ const current = bufferedNetworks.get(payload.runId);
944
+ if (!current) return null;
851
945
  current.steps.push({
946
+ id: payload.payload.runId,
852
947
  name: payload.payload.agentId,
853
948
  status: "running",
854
- input: payload.payload.args || null,
949
+ iteration: payload.payload.args?.iteration ?? 0,
950
+ input: { prompt: payload.payload.args?.prompt ?? "" },
855
951
  output: null,
952
+ task: null,
856
953
  suspendPayload: null,
857
- resumePayload: null
954
+ resumePayload: null,
955
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
858
956
  });
859
957
  bufferedNetworks.set(payload.runId, current);
860
958
  return {
@@ -867,14 +965,19 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
867
965
  };
868
966
  }
869
967
  case "workflow-execution-start": {
870
- const current = bufferedNetworks.get(payload.runId) || { name: "", steps: [], usage: null, output: null };
968
+ const current = bufferedNetworks.get(payload.runId);
969
+ if (!current) return null;
871
970
  current.steps.push({
872
- name: payload.payload.name,
971
+ id: payload.payload.runId,
972
+ name: payload.payload.workflowId,
873
973
  status: "running",
874
- input: payload.payload.args || null,
974
+ iteration: payload.payload.args?.iteration ?? 0,
975
+ input: { prompt: payload.payload.args?.prompt ?? "" },
875
976
  output: null,
977
+ task: null,
876
978
  suspendPayload: null,
877
- resumePayload: null
979
+ resumePayload: null,
980
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
878
981
  });
879
982
  bufferedNetworks.set(payload.runId, current);
880
983
  return {
@@ -887,14 +990,21 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
887
990
  };
888
991
  }
889
992
  case "tool-execution-start": {
890
- const current = bufferedNetworks.get(payload.runId) || { name: "", steps: [], usage: null, output: null };
993
+ const current = bufferedNetworks.get(payload.runId);
994
+ if (!current) return null;
891
995
  current.steps.push({
996
+ id: payload.payload.args.toolCallId,
892
997
  name: payload.payload.args?.toolName,
893
998
  status: "running",
999
+ iteration: payload.payload.args?.iteration ? Number(payload.payload.args.iteration) : 0,
1000
+ task: {
1001
+ id: payload.payload.args?.toolName
1002
+ },
894
1003
  input: payload.payload.args?.args || null,
895
1004
  output: null,
896
1005
  suspendPayload: null,
897
- resumePayload: null
1006
+ resumePayload: null,
1007
+ [PRIMITIVE_CACHE_SYMBOL]: /* @__PURE__ */ new Map()
898
1008
  });
899
1009
  bufferedNetworks.set(payload.runId, current);
900
1010
  return {
@@ -909,14 +1019,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
909
1019
  case "agent-execution-end": {
910
1020
  const current = bufferedNetworks.get(payload.runId);
911
1021
  if (!current) return null;
912
- current.steps.push({
913
- name: payload.payload.agentId,
914
- status: "success",
915
- input: null,
916
- output: payload.payload.result,
917
- suspendPayload: null,
918
- resumePayload: null
919
- });
1022
+ const stepId = payload.payload.runId;
1023
+ const step = current.steps.find((step2) => step2.id === stepId);
1024
+ if (!step) {
1025
+ return null;
1026
+ }
1027
+ step.status = "success";
1028
+ step.output = payload.payload.result;
920
1029
  return {
921
1030
  type: isNested ? "data-tool-network" : "data-network",
922
1031
  id: payload.runId,
@@ -931,14 +1040,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
931
1040
  case "tool-execution-end": {
932
1041
  const current = bufferedNetworks.get(payload.runId);
933
1042
  if (!current) return null;
934
- current.steps.push({
935
- name: payload.payload.toolName,
936
- status: "success",
937
- input: null,
938
- output: payload.payload.result,
939
- suspendPayload: null,
940
- resumePayload: null
941
- });
1043
+ const stepId = payload.payload.toolCallId;
1044
+ const step = current.steps.find((step2) => step2.id === stepId);
1045
+ if (!step) {
1046
+ return null;
1047
+ }
1048
+ step.status = "success";
1049
+ step.output = payload.payload.result;
942
1050
  return {
943
1051
  type: isNested ? "data-tool-network" : "data-network",
944
1052
  id: payload.runId,
@@ -952,14 +1060,13 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
952
1060
  case "workflow-execution-end": {
953
1061
  const current = bufferedNetworks.get(payload.runId);
954
1062
  if (!current) return null;
955
- current.steps.push({
956
- name: payload.payload.name,
957
- status: "success",
958
- input: null,
959
- output: payload.payload.result,
960
- suspendPayload: null,
961
- resumePayload: null
962
- });
1063
+ const stepId = payload.payload.runId;
1064
+ const step = current.steps.find((step2) => step2.id === stepId);
1065
+ if (!step) {
1066
+ return null;
1067
+ }
1068
+ step.status = "success";
1069
+ step.output = payload.payload.result;
963
1070
  return {
964
1071
  type: isNested ? "data-tool-network" : "data-network",
965
1072
  id: payload.runId,
@@ -974,12 +1081,24 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
974
1081
  case "routing-agent-end": {
975
1082
  const current = bufferedNetworks.get(payload.runId);
976
1083
  if (!current) return null;
1084
+ const stepId = payload.payload.runId;
1085
+ const step = current.steps.find((step2) => step2.id === stepId);
1086
+ if (!step) {
1087
+ return null;
1088
+ }
1089
+ step.status = "success";
1090
+ step.task = {
1091
+ id: payload.payload.primitiveId,
1092
+ type: payload.payload.primitiveType,
1093
+ name: payload.payload.task,
1094
+ reason: payload.payload.selectionReason
1095
+ };
1096
+ step.output = payload.payload.result;
977
1097
  return {
978
1098
  type: isNested ? "data-tool-network" : "data-network",
979
1099
  id: payload.runId,
980
1100
  data: {
981
1101
  ...current,
982
- status: "finished",
983
1102
  usage: payload.payload?.usage ?? current.usage,
984
1103
  output: payload.payload?.result ?? current.output
985
1104
  }
@@ -1013,6 +1132,39 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
1013
1132
  };
1014
1133
  }
1015
1134
  default: {
1135
+ if (payload.type.startsWith("agent-execution-event-")) {
1136
+ const stepId = payload.payload.runId;
1137
+ const current = bufferedNetworks.get(payload.runId);
1138
+ if (!current) return null;
1139
+ const step = current.steps.find((step2) => step2.id === stepId);
1140
+ if (!step) {
1141
+ return null;
1142
+ }
1143
+ step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
1144
+ const result = transformAgent(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
1145
+ if (result) {
1146
+ const { request, response, ...data } = result.data;
1147
+ step.task = data;
1148
+ }
1149
+ }
1150
+ if (payload.type.startsWith("workflow-execution-event-")) {
1151
+ const stepId = payload.payload.runId;
1152
+ const current = bufferedNetworks.get(payload.runId);
1153
+ if (!current) return null;
1154
+ const step = current.steps.find((step2) => step2.id === stepId);
1155
+ if (!step) {
1156
+ return null;
1157
+ }
1158
+ step[PRIMITIVE_CACHE_SYMBOL] = step[PRIMITIVE_CACHE_SYMBOL] || /* @__PURE__ */ new Map();
1159
+ const result = transformWorkflow(payload.payload, step[PRIMITIVE_CACHE_SYMBOL]);
1160
+ if (result && "data" in result) {
1161
+ const data = result.data;
1162
+ step.task = data;
1163
+ if (data.name && step.task) {
1164
+ step.task.id = data.name;
1165
+ }
1166
+ }
1167
+ }
1016
1168
  if (isDataChunkType(payload)) {
1017
1169
  if (!("data" in payload)) {
1018
1170
  throw new Error(
@@ -1020,7 +1172,8 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
1020
1172
  ${JSON.stringify(payload)}`
1021
1173
  );
1022
1174
  }
1023
- return payload;
1175
+ const { type, data } = payload;
1176
+ return { type, data };
1024
1177
  }
1025
1178
  if (isAgentExecutionDataChunkType(payload)) {
1026
1179
  if (!("data" in payload.payload)) {
@@ -1029,7 +1182,8 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
1029
1182
  ${JSON.stringify(payload)}`
1030
1183
  );
1031
1184
  }
1032
- return payload.payload;
1185
+ const { type, data } = payload.payload;
1186
+ return { type, data };
1033
1187
  }
1034
1188
  if (isWorkflowExecutionDataChunkType(payload)) {
1035
1189
  if (!("data" in payload.payload)) {
@@ -1038,7 +1192,8 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
1038
1192
  ${JSON.stringify(payload)}`
1039
1193
  );
1040
1194
  }
1041
- return payload.payload;
1195
+ const { type, data } = payload.payload;
1196
+ return { type, data };
1042
1197
  }
1043
1198
  return null;
1044
1199
  }
@@ -1053,7 +1208,10 @@ function toAISdkV5Stream(stream, options = {
1053
1208
  }) {
1054
1209
  const from = options?.from;
1055
1210
  if (from === "workflow") {
1056
- return stream.pipeThrough(WorkflowStreamToAISDKTransformer());
1211
+ const includeTextStreamParts = options?.includeTextStreamParts ?? true;
1212
+ return stream.pipeThrough(
1213
+ WorkflowStreamToAISDKTransformer({ includeTextStreamParts })
1214
+ );
1057
1215
  }
1058
1216
  if (from === "network") {
1059
1217
  return stream.pipeThrough(AgentNetworkToAISDKTransformer());
@@ -1065,12 +1223,65 @@ function toAISdkV5Stream(stream, options = {
1065
1223
  sendStart: options?.sendStart,
1066
1224
  sendFinish: options?.sendFinish,
1067
1225
  sendReasoning: options?.sendReasoning,
1068
- sendSources: options?.sendSources
1226
+ sendSources: options?.sendSources,
1227
+ messageMetadata: options?.messageMetadata,
1228
+ onError: options?.onError
1069
1229
  })
1070
1230
  );
1071
1231
  }
1072
1232
 
1073
1233
  // src/chat-route.ts
1234
+ async function handleChatStream({
1235
+ mastra,
1236
+ agentId,
1237
+ params,
1238
+ defaultOptions,
1239
+ sendStart = true,
1240
+ sendFinish = true,
1241
+ sendReasoning = false,
1242
+ sendSources = false
1243
+ }) {
1244
+ const { messages, resumeData, runId, requestContext, ...rest } = params;
1245
+ if (resumeData && !runId) {
1246
+ throw new Error("runId is required when resumeData is provided");
1247
+ }
1248
+ const agentObj = mastra.getAgentById(agentId);
1249
+ if (!agentObj) {
1250
+ throw new Error(`Agent ${agentId} not found`);
1251
+ }
1252
+ if (!Array.isArray(messages)) {
1253
+ throw new Error("Messages must be an array of UIMessage objects");
1254
+ }
1255
+ const mergedOptions = {
1256
+ ...defaultOptions,
1257
+ ...rest,
1258
+ ...runId && { runId },
1259
+ requestContext: requestContext || defaultOptions?.requestContext
1260
+ };
1261
+ const result = resumeData ? await agentObj.resumeStream(resumeData, mergedOptions) : await agentObj.stream(messages, mergedOptions);
1262
+ let lastMessageId;
1263
+ if (messages.length) {
1264
+ const lastMessage = messages[messages.length - 1];
1265
+ if (lastMessage?.role === "assistant") {
1266
+ lastMessageId = lastMessage.id;
1267
+ }
1268
+ }
1269
+ return createUIMessageStream({
1270
+ originalMessages: messages,
1271
+ execute: async ({ writer }) => {
1272
+ for await (const part of toAISdkV5Stream(result, {
1273
+ from: "agent",
1274
+ lastMessageId,
1275
+ sendStart,
1276
+ sendFinish,
1277
+ sendReasoning,
1278
+ sendSources
1279
+ })) {
1280
+ writer.write(part);
1281
+ }
1282
+ }
1283
+ });
1284
+ }
1074
1285
  function chatRoute({
1075
1286
  path = "/chat/:agentId",
1076
1287
  agent,
@@ -1107,6 +1318,14 @@ function chatRoute({
1107
1318
  schema: {
1108
1319
  type: "object",
1109
1320
  properties: {
1321
+ resumeData: {
1322
+ type: "object",
1323
+ description: "Resume data for the agent"
1324
+ },
1325
+ runId: {
1326
+ type: "string",
1327
+ description: "The run ID required when resuming an agent execution"
1328
+ },
1110
1329
  messages: {
1111
1330
  type: "array",
1112
1331
  description: "Array of messages in the conversation",
@@ -1177,9 +1396,9 @@ function chatRoute({
1177
1396
  }
1178
1397
  },
1179
1398
  handler: async (c) => {
1180
- const { messages, ...rest } = await c.req.json();
1399
+ const params = await c.req.json();
1181
1400
  const mastra = c.get("mastra");
1182
- const requestContext = c.get("requestContext");
1401
+ const contextRequestContext = c.get("requestContext");
1183
1402
  let agentToUse = agent;
1184
1403
  if (!agent) {
1185
1404
  const agentId = c.req.param("agentId");
@@ -1190,39 +1409,24 @@ function chatRoute({
1190
1409
  `Fixed agent ID was set together with an agentId path parameter. This can lead to unexpected behavior.`
1191
1410
  );
1192
1411
  }
1193
- if (requestContext && defaultOptions?.requestContext) {
1412
+ if (contextRequestContext && defaultOptions?.requestContext) {
1194
1413
  mastra.getLogger()?.warn(`"requestContext" set in the route options will be overridden by the request's "requestContext".`);
1195
1414
  }
1196
1415
  if (!agentToUse) {
1197
1416
  throw new Error("Agent ID is required");
1198
1417
  }
1199
- const agentObj = mastra.getAgent(agentToUse);
1200
- if (!agentObj) {
1201
- throw new Error(`Agent ${agentToUse} not found`);
1202
- }
1203
- const result = await agentObj.stream(messages, {
1204
- ...defaultOptions,
1205
- ...rest,
1206
- requestContext: requestContext || defaultOptions?.requestContext
1207
- });
1208
- let lastMessageId;
1209
- if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1210
- lastMessageId = messages[messages.length - 1].id;
1211
- }
1212
- const uiMessageStream = createUIMessageStream({
1213
- originalMessages: messages,
1214
- execute: async ({ writer }) => {
1215
- for await (const part of toAISdkV5Stream(result, {
1216
- from: "agent",
1217
- lastMessageId,
1218
- sendStart,
1219
- sendFinish,
1220
- sendReasoning,
1221
- sendSources
1222
- })) {
1223
- writer.write(part);
1224
- }
1225
- }
1418
+ const uiMessageStream = await handleChatStream({
1419
+ mastra,
1420
+ agentId: agentToUse,
1421
+ params: {
1422
+ ...params,
1423
+ requestContext: contextRequestContext || params.requestContext
1424
+ },
1425
+ defaultOptions,
1426
+ sendStart,
1427
+ sendFinish,
1428
+ sendReasoning,
1429
+ sendSources
1226
1430
  });
1227
1431
  return createUIMessageStreamResponse({
1228
1432
  stream: uiMessageStream
@@ -1230,9 +1434,31 @@ function chatRoute({
1230
1434
  }
1231
1435
  });
1232
1436
  }
1437
+ async function handleWorkflowStream({
1438
+ mastra,
1439
+ workflowId,
1440
+ params,
1441
+ includeTextStreamParts = true
1442
+ }) {
1443
+ const { runId, resourceId, inputData, resumeData, requestContext, ...rest } = params;
1444
+ const workflowObj = mastra.getWorkflowById(workflowId);
1445
+ if (!workflowObj) {
1446
+ throw new Error(`Workflow ${workflowId} not found`);
1447
+ }
1448
+ const run = await workflowObj.createRun({ runId, resourceId, ...rest });
1449
+ const stream = resumeData ? run.resumeStream({ resumeData, ...rest, requestContext }) : run.stream({ inputData, ...rest, requestContext });
1450
+ return createUIMessageStream({
1451
+ execute: async ({ writer }) => {
1452
+ for await (const part of toAISdkV5Stream(stream, { from: "workflow", includeTextStreamParts })) {
1453
+ writer.write(part);
1454
+ }
1455
+ }
1456
+ });
1457
+ }
1233
1458
  function workflowRoute({
1234
1459
  path = "/api/workflows/:workflowId/stream",
1235
- workflow
1460
+ workflow,
1461
+ includeTextStreamParts = true
1236
1462
  }) {
1237
1463
  if (!workflow && !path.includes("/:workflowId")) {
1238
1464
  throw new Error("Path must include :workflowId to route to the correct workflow or pass the workflow explicitly");
@@ -1283,8 +1509,9 @@ function workflowRoute({
1283
1509
  }
1284
1510
  },
1285
1511
  handler: async (c) => {
1286
- const { runId, resourceId, inputData, resumeData, ...rest } = await c.req.json();
1512
+ const params = await c.req.json();
1287
1513
  const mastra = c.get("mastra");
1514
+ const contextRequestContext = c.get("requestContext");
1288
1515
  let workflowToUse = workflow;
1289
1516
  if (!workflow) {
1290
1517
  const workflowId = c.req.param("workflowId");
@@ -1298,23 +1525,47 @@ function workflowRoute({
1298
1525
  if (!workflowToUse) {
1299
1526
  throw new Error("Workflow ID is required");
1300
1527
  }
1301
- const workflowObj = mastra.getWorkflow(workflowToUse);
1302
- if (!workflowObj) {
1303
- throw new Error(`Workflow ${workflowToUse} not found`);
1528
+ if (contextRequestContext && params.requestContext) {
1529
+ mastra.getLogger()?.warn(
1530
+ `"requestContext" from the request body will be ignored because "requestContext" is already set in the route options.`
1531
+ );
1304
1532
  }
1305
- const run = await workflowObj.createRun({ runId, resourceId, ...rest });
1306
- const stream = resumeData ? run.resumeStream({ resumeData, ...rest }) : run.stream({ inputData, ...rest });
1307
- const uiMessageStream = createUIMessageStream({
1308
- execute: async ({ writer }) => {
1309
- for await (const part of toAISdkV5Stream(stream, { from: "workflow" })) {
1310
- writer.write(part);
1311
- }
1312
- }
1533
+ const uiMessageStream = await handleWorkflowStream({
1534
+ mastra,
1535
+ workflowId: workflowToUse,
1536
+ params: {
1537
+ ...params,
1538
+ requestContext: contextRequestContext || params.requestContext
1539
+ },
1540
+ includeTextStreamParts
1313
1541
  });
1314
1542
  return createUIMessageStreamResponse({ stream: uiMessageStream });
1315
1543
  }
1316
1544
  });
1317
1545
  }
1546
+ async function handleNetworkStream({
1547
+ mastra,
1548
+ agentId,
1549
+ params,
1550
+ defaultOptions
1551
+ }) {
1552
+ const { messages, ...rest } = params;
1553
+ const agentObj = mastra.getAgentById(agentId);
1554
+ if (!agentObj) {
1555
+ throw new Error(`Agent ${agentId} not found`);
1556
+ }
1557
+ const result = await agentObj.network(messages, {
1558
+ ...defaultOptions,
1559
+ ...rest
1560
+ });
1561
+ return createUIMessageStream({
1562
+ execute: async ({ writer }) => {
1563
+ for await (const part of toAISdkV5Stream(result, { from: "network" })) {
1564
+ writer.write(part);
1565
+ }
1566
+ }
1567
+ });
1568
+ }
1318
1569
  function networkRoute({
1319
1570
  path = "/network/:agentId",
1320
1571
  agent,
@@ -1375,7 +1626,7 @@ function networkRoute({
1375
1626
  }
1376
1627
  },
1377
1628
  handler: async (c) => {
1378
- const { messages, ...rest } = await c.req.json();
1629
+ const params = await c.req.json();
1379
1630
  const mastra = c.get("mastra");
1380
1631
  let agentToUse = agent;
1381
1632
  if (!agent) {
@@ -1390,20 +1641,11 @@ function networkRoute({
1390
1641
  if (!agentToUse) {
1391
1642
  throw new Error("Agent ID is required");
1392
1643
  }
1393
- const agentObj = mastra.getAgent(agentToUse);
1394
- if (!agentObj) {
1395
- throw new Error(`Agent ${agentToUse} not found`);
1396
- }
1397
- const result = await agentObj.network(messages, {
1398
- ...defaultOptions,
1399
- ...rest
1400
- });
1401
- const uiMessageStream = createUIMessageStream({
1402
- execute: async ({ writer }) => {
1403
- for await (const part of toAISdkV5Stream(result, { from: "network" })) {
1404
- writer.write(part);
1405
- }
1406
- }
1644
+ const uiMessageStream = await handleNetworkStream({
1645
+ mastra,
1646
+ agentId: agentToUse,
1647
+ params,
1648
+ defaultOptions
1407
1649
  });
1408
1650
  return createUIMessageStreamResponse({ stream: uiMessageStream });
1409
1651
  }
@@ -1417,6 +1659,6 @@ function toAISdkFormat() {
1417
1659
  );
1418
1660
  }
1419
1661
 
1420
- export { chatRoute, networkRoute, toAISdkFormat, toAISdkV5Stream as toAISdkStream, workflowRoute };
1662
+ export { chatRoute, handleChatStream, handleNetworkStream, handleWorkflowStream, networkRoute, toAISdkFormat, toAISdkV5Stream as toAISdkStream, workflowRoute };
1421
1663
  //# sourceMappingURL=index.js.map
1422
1664
  //# sourceMappingURL=index.js.map